Пример #1
0
    def __init__(self, fetcher):
        self.fetcher = fetcher
        self.connect(self.fetcher, SIGNAL("want_update"), self.requestData)
        self.fragment = fetcher.fragment
        self.cumulative_mode = False
        self.interval = Interval('daily')

        self.reset_start = False
        self.saved_start = 0
        self.is_closed = False

        self.uuid = QUuid.createUuid().toString()

        # ugl, ugl, ugl, it's ugly yeah \o/
#        print type(self.parent().window)
        if hasattr(self.parent().window, 'current_page'):
            self.current_page = self.parent().window.current_page
        else:
            self.current_page = None
        self.user_settings = None

        # XXX this is ugly
        # TODO kill the crap who has written this.
        top_window = self.parent()
        while top_window:
            try:
                self.user_settings = top_window.user_settings
            except AttributeError:
                top_window = top_window.parent()
            else:
                break

        self.title = QLabel()
        self.title.setAlignment(Qt.AlignLeft | Qt.AlignTop)
        self.title.setStyleSheet('font: bold 13px')
Пример #2
0
    def createSqlLayer( self, sqlQuery, layerName = '' ):
        isVectorLayer, fieldName = self.findGeomColumns(sqlQuery)
        print 'I:geom columns=', fieldName.toLatin1().data(), ' isVectorLayer=', isVectorLayer
	
        if fieldName.isEmpty():
            print 'cannot find column with type geometry'
            return		
   
        if  len(layerName) == 0:
			layerName = 'query ' + QUuid.createUuid().toString()
        else:
            layers = QgsMapLayerRegistry.instance().mapLayersByName(layerName)
            print 'test layer count:', len(layers)	
            if len(layers) > 0:
                QgsMapLayerRegistry.instance().removeMapLayer( layers[0].id() );
			
        if  isVectorLayer == True:			
            uri = QgsDataSourceURI()
            uri.setConnection(self.host, self.port, self.dbname, self.user, self.passw)	
            uri.setDataSource("", self.appendIdColumn(sqlQuery, fieldName), fieldName, "", "id") #qgis.core.QgsDataSourceURI.setDataSource?4(QString, QString, QString, QString aSql=QString(), QString aKeyColumn=QString())    
            layer = QgsVectorLayer( uri.uri(), layerName, "postgres" ) 
        else:
            viewName = self.generateView(sqlQuery)
            connString = "PG: dbname=%s host=%s user=%s password=%s port=%s schema=%s table=%s" % ( self.dbname, self.host, self.user, self.passw, self.port, self.schemaName, viewName )
            print 'I:connString=', connString
            layer = QgsRasterLayer( connString, layerName )		
		
        if not layer.isValid() :
            print "Failed to load"	
            return 	
        
        QgsMapLayerRegistry.instance().addMapLayer( layer )	
Пример #3
0
    def connectToDb( self ):
        self.uidConnection = self.uidConnection + QUuid.createUuid().toString()
        d = QSqlDatabase.addDatabase( "QPSQL",  self.uidConnection)
        d.setHostName( self.host )
        d.setPort( int( self.port ) )
        d.setDatabaseName( self.dbname )
        d.setUserName( self.user )
        d.setPassword( self.passw )
        if not d.open():
            showError(None, 'error', 'error connect DB:  host:' + self.host + ' dbname:' + self.dbname + ' user:'******' passw=' + self.passw )
		
        self.createScheme()
        def _createNewActivity(id=None, otherActivity=None):

            # Connect to the protocol signal
            self.connect(self.activityProtocol, SIGNAL("created( bool, int, QString )"), _createNewActivityFinished)

            # Create a new Uuid
            if id is not None:
                uid = QPlainUuid(id)
            else:
                uid = QPlainUuid(QUuid.createUuid())

            tagGroups = list(TagGroup() for i in range(len(groups)))

            # attrs is a dictionary: key = field index, value = QgsFeatureAttribute
            # show all attributes and their values
            self.log("Attribute list:")
            for (k, attr) in attrs.iteritems():
                if k is not identifierColumnIndex:
                    self.log("%s: %s" % (fieldIndexMap[k], attr.toString()))

                    # First search the correct taggroup to append
                    attributeName = provider.fields()[k].name()
                    currentTagGroup = 0
                    for g in groups:
                        if attributeName in g:
                            break
                        else:
                            currentTagGroup += 1

                    if attr is not None and attr.toString() != '':
                        tag = Tag(key=fieldIndexMap[k], value=attr.toString())
                        tagGroups[currentTagGroup].addTag(tag)
                        if tagGroups[currentTagGroup].mainTag() is None:
                            tagGroups[currentTagGroup].setMainTag(tag)

            a = Activity(id=uid)
            a.setGeometry(feature.geometry())
            for tg in tagGroups:
                if len(tg.tags) > 0:
                    a.addTagGroup(tg)

            wrapperObj = {}

            wrapperObj['activities'] = [a.createDiff(otherActivity)]

            self.activityProtocol.add(json.dumps(wrapperObj, sort_keys=True, indent=4 * ' '))
Пример #5
0
    def __openDatabase(self, dbPath):
        """

        :type dbPath: str
        :return:
        """
        qDebug("\n(VFK) Open DB: {}".format(dbPath))
        if not QSqlDatabase.isDriverAvailable('QSQLITE'):
            raise VFKError(u'Databázový ovladač QSQLITE není dostupný.')

        connectionName = QUuid.createUuid().toString()
        db = QSqlDatabase.addDatabase("QSQLITE", connectionName)
        db.setDatabaseName(dbPath)
        if not db.open():
            raise VFKError(u'Nepodařilo se otevřít databázi. ')

        self.setProperty("connectionName", connectionName)
    def __openDatabase(self, dbPath):
        """

        :type dbPath: str
        :return:
        """
        qDebug("\n(VFK) Open DB: {}".format(dbPath))
        if not QSqlDatabase.isDriverAvailable('QSQLITE'):
            raise VFKError(u'Databázový ovladač QSQLITE není dostupný.')

        connectionName = QUuid.createUuid().toString()
        db = QSqlDatabase.addDatabase("QSQLITE", connectionName)
        db.setDatabaseName(dbPath)
        if not db.open():
            raise VFKError(u'Nepodařilo se otevřít databázi. ')

        self.setProperty("connectionName", connectionName)
Пример #7
0
allAttrs = provider.attributeIndexes()

# start data retreival: fetch geometry and all attributes for each feature
#provider.select([fieldIndex])
provider.select(allAttrs)

caps = provider.capabilities()

# retreive every feature with its geometry and attributes
while provider.nextFeature(feat):

    # fetch map of attributes
    attrs = feat.attributeMap()

    # attrs is a dictionary: key = field index, value = QgsFeatureAttribute
    # show all attributes and their values
    for (k, attr) in attrs.iteritems():
        if k == fieldIndex:
            #if attr.toString() == "":
            if caps & QgsVectorDataProvider.ChangeAttributeValues:
                identifier = QUuid().createUuid().toString()
                # Remove the unwanted brackets
                identifier.remove(QChar('{'), Qt.CaseInsensitive)
                identifier.remove(QChar('}'), Qt.CaseInsensitive)
                print "Newly create UUID: %s" % identifier
                attrs = { fieldIndex : QVariant(identifier)}
                success = provider.changeAttributeValues({ feat.id() : attrs })
                #print success

QgsApplication.exitQgis()
Пример #8
0
 def __init__(self, string):
     QUuid.__init__(self, string)
Пример #9
0
    def _open_database(self, dbPath):
        """Opens a database.
        
        Checks if there are geometry_columns and spatial_ref_sys
        tables in the database, if not it creates and fills those tables.
        
        Checks if there are all PU columns in PAR table,
        if it it creates and fills those columns.
        
        Args:
            dbPath (str): A full path to the database.
        
        Raises:
            dw.puError: When SQLITE database driver is not available
                or when database connection fails.
        
        """

        if not QSqlDatabase.isDriverAvailable('QSQLITE'):
            raise self.dW.puError(
                self.dW, self, u'SQLITE database driver is not available.',
                u'Databázový ovladač QSQLITE není dostupný.',
                u'Databázový ovladač QSQLITE není dostupný.')

        connectionName = QUuid.createUuid().toString()
        db = QSqlDatabase.addDatabase('QSQLITE', connectionName)
        db.setDatabaseName(dbPath)
        db.open()

        if not db.open():
            raise self.dW.puError(self.dW, self,
                                  u'Database connection failed.',
                                  u'Nepodařilo se připojit k databázi.',
                                  u'Nepodařilo se připojit k databázi.')

        self.set_text_statusbar.emit(u'Kontroluji tabulky a sloupce...', 0,
                                     False)

        QgsApplication.processEvents()

        sqlQuery = QSqlQuery(db)

        sqlDir = QDir(self.pluginDir.path() + u'/data/sql')

        query = self._read_text_from_file(sqlDir.filePath(u'check_gc_srs.sql'))

        sqlQuery.exec_(query)

        QgsApplication.processEvents()

        checkGcSrsSize = 0

        while sqlQuery.next():
            checkGcSrsSize += 1

        if checkGcSrsSize < 2:
            queries = self._read_text_from_file(
                sqlDir.filePath(u'create_fill_gc_srs.sql')).split(';')

            for query in queries:
                sqlQuery.exec_(query)

                QgsApplication.processEvents()

        query = self._read_text_from_file(
            sqlDir.filePath(u'check_pu_columns_PAR.sql'))

        sqlQuery.exec_(query)

        QgsApplication.processEvents()

        columns = []

        while sqlQuery.next():
            record = sqlQuery.record()
            name = str(record.value('name'))
            columns.append(name)

        if not all(column in columns for column in self.dW.allPuColumns):
            queries = self._read_text_from_file(
                sqlDir.filePath(u'add_pu_columns_PAR.sql')).split(';')

            for query in queries:
                sqlQuery.exec_(query)

                QgsApplication.processEvents()

        queries = self._read_text_from_file(
            sqlDir.filePath(u'create_sobr_spol.sql')).split(';')

        for query in queries:
            sqlQuery.exec_(query)

        db.close()