def get_db_tables(self):
     """Retrieve all tables from the selected database."""
     self.dlg.cmb_geo.clear()
     db_name = self.dlg.cmb_db.currentText()
     con_name = self.dlg.cmb_con.currentText()
     con_str = "{db}/connections/{con}/".format(db=db_name, con=con_name)
     qs = QSettings()
     db_host = qs.value(con_str + "host")
     db_port = qs.value(con_str + "port")
     db_name = qs.value(con_str + "database")
     con_usr = qs.value(con_str + "username")
     con_pwd = qs.value(con_str + "password")
     uri = QgsDataSourceURI()
     uri.setConnection(db_host, db_port, db_name, con_usr, con_pwd)
     post_c = pg_con.PostGisDBConnector(uri)
     tbl_list = []
     for table in post_c.getTables():
         if table[3] or table[1] == 'spatial_ref_sys':
             pass
         else:
             tbl_list.append(table[1])
     if len(tbl_list) == 0:
         QMessageBox.warning(None,
                             'Layer and Tables',
                             """There are no tables to geo-code in this database.""")
     else:
         self.dlg.cmb_geo.addItems(tbl_list)
Пример #2
0
	def connect(self, parent=None):
		conn_name = self.connectionName()
		settings = QSettings()
		settings.beginGroup( u"/%s/%s" % (self.connectionSettingsKey(), conn_name) )

		if not settings.contains( "database" ): # non-existent entry?
			raise InvalidDataException( u'there is no defined database connection "%s".' % conn_name )

		from qgis.core import QgsDataSourceURI
		uri = QgsDataSourceURI()
	
		get_value_str = lambda x: settings.value(x).toString()
		host, port, database, username, password = map(get_value_str, ["host", "port", "database", "username", "password"])

		# qgis1.5 use 'savePassword' instead of 'save' setting
		savedPassword = settings.value("save", False).toBool() or settings.value("savePassword", False).toBool()

		useEstimatedMetadata = settings.value("estimatedMetadata", False).toBool()
		sslmode = settings.value("sslmode", QgsDataSourceURI.SSLprefer).toInt()[0]

		settings.endGroup()

		uri.setConnection(host, port, database, username, password, sslmode)
		uri.setUseEstimatedMetadata(useEstimatedMetadata)

		err = QString()
		try:
			return DBPlugin.connect(self, uri)
		except ConnectionError, e:
			err = QString( str(e) )
Пример #3
0
 def onUpdateSqlLayer(self):
     l = self.iface.legendInterface().currentLayer()
     if l.dataProvider().name() in ['postgres', 'spatialite', 'oracle']:
         uri = QgsDataSourceURI(l.source())
         if re.search('^\(SELECT .+ FROM .+\)$', uri.table(), re.S):
             self.run()
             self.dlg.runSqlLayerWindow(l)
Пример #4
0
def pg_layerNamesIDMapping():
    '''
    Returns a dictionary containing the original table names and corresponding layer IDs in the
    QGIS legend for only those layers from a postgres database.
    '''
    mapping = ReverseDict()
    layers = QgsMapLayerRegistry.instance().mapLayers()
    
    for name,layer in layers.iteritems():
        if hasattr(layer, 'dataProvider'):
            if layer.dataProvider().name() == 'postgres':
                layerConnStr = layer.dataProvider().dataSourceUri()
                dataSourceURI = QgsDataSourceURI(layerConnStr)
                mapping[dataSourceURI.table()] = layer.id()
    
    return mapping
    
    
    
    
    
    
    
    
    
Пример #5
0
    def ogrConnectionString(self, uri):
        ogrstr = None

        layer = dataobjects.getObjectFromUri(uri, False)
        if layer is None:
            return uri
        provider = layer.dataProvider().name()
        if provider == 'spatialite':
            # dbname='/geodata/osm_ch.sqlite' table="places" (Geometry) sql=
            regex = re.compile("dbname='(.+)'")
            r = regex.search(unicode(layer.source()))
            ogrstr = r.groups()[0]
        elif provider == 'postgres':
            # dbname='ktryjh_iuuqef' host=spacialdb.com port=9999
            # user='******' password='******' sslmode=disable
            # key='gid' estimatedmetadata=true srid=4326 type=MULTIPOLYGON
            # table="t4" (geom) sql=
            dsUri = QgsDataSourceURI(layer.dataProvider().dataSourceUri())
            connInfo = dsUri.connectionInfo()
            (success, user, passwd ) = QgsCredentials.instance().get(connInfo, None, None)
            if success:
                QgsCredentials.instance().put(connInfo, user, passwd)
            ogrstr = ("PG:dbname='%s' host='%s' port='%s' user='******' password='******'"
                      % (dsUri.database(), dsUri.host(), dsUri.port(), user, passwd))
        else:
            ogrstr = unicode(layer.source()).split("|")[0]
        return '"' + ogrstr + '"'
Пример #6
0
 def getAll(self, expression=None):
     uri = QgsDataSourceURI(expression)
     if uri.table() != self.layer:
         raise Exception('Invalid expression %s. Expected table %s but got %s'%(expression, self.layer, uri.table))
     qgsLayer = getLayerByUri(self.layer, uri.uri())
     if not qgsLayer:
         raise Exception('Layer with uri %s not found'%QgsDataSourceURI.removePassword(uri.uri()))
Пример #7
0
 def getLayers(self, dbName):
     lyrList = []
     for lyr in self.iface.legendInterface().layers():
         if isinstance(lyr, QgsVectorLayer):
             candidateUri = QgsDataSourceURI(lyr.dataProvider().dataSourceUri())
             if candidateUri.database() == dbName and lyr.providerType() in ['postgres', 'spatialite']:
                 lyrList.append(lyr)
     return lyrList
Пример #8
0
def getLayerByUri(layerName, uri):
    reg = QgsMapLayerRegistry.instance()
    allLayers = reg.mapLayersByName(layerName)
    for a in allLayers:
        dsUri = QgsDataSourceURI(a.dataProvider().dataSourceUri())
        if dsUri.uri() == uri:
            return a
    return None
Пример #9
0
 def createBlockLayer(self):
     uri = QgsDataSourceURI()
     uri.setConnection(self.db_hostName, str(self.db_Port), self.db_databaseName, self.db_UserName, self.db_password)
     uri.setDataSource("cadastre", "spatial_unit_group", "geom", "hierarchy_level=5")
     uri.uri()
     print uri.uri()
     rlayer = self.iface.addVectorLayer(uri.uri(), "Blocks", "postgres")
     rlayer.loadNamedStyle(self.plugin_dir + '/lga.qml')
Пример #10
0
 def getDatabaseList(self):
     dbList = []
     for lyr in self.iface.legendInterface().layers():
         if isinstance(lyr, QgsVectorLayer):
             candidateUri = QgsDataSourceURI(lyr.dataProvider().dataSourceUri())
             dbName = candidateUri.database()
             if dbName not in dbList and lyr.providerType() in ['postgres', 'spatialite']:
                 dbList.append(dbName)
     return dbList
Пример #11
0
    def dropMimeData(self, data, action, row, column, parent):
        global isImportVectorAvail

        if action == Qt.IgnoreAction:
            return True

        # vectors/tables to be imported must be dropped on connected db, schema or table
        canImportLayer = isImportVectorAvail and parent.isValid() and \
            (isinstance(parent.internalPointer(), (SchemaItem, TableItem)) or
             (isinstance(parent.internalPointer(), ConnectionItem) and parent.internalPointer().populated))

        added = 0

        if data.hasUrls():
            for u in data.urls():
                filename = u.toLocalFile()
                if filename == "":
                    continue

                if self.hasSpatialiteSupport:
                    from .db_plugins.spatialite.connector import SpatiaLiteDBConnector

                    if SpatiaLiteDBConnector.isValidDatabase(filename):
                        # retrieve the SL plugin tree item using its path
                        index = self._rPath2Index(["spatialite"])
                        if not index.isValid():
                            continue
                        item = index.internalPointer()

                        conn_name = QFileInfo(filename).fileName()
                        uri = QgsDataSourceURI()
                        uri.setDatabase(filename)
                        item.getItemData().addConnection(conn_name, uri)
                        item.itemChanged.emit(item)
                        added += 1
                        continue

                if canImportLayer:
                    if QgsRasterLayer.isValidRasterFileName(filename):
                        layerType = 'raster'
                        providerKey = 'gdal'
                    else:
                        layerType = 'vector'
                        providerKey = 'ogr'

                    layerName = QFileInfo(filename).completeBaseName()
                    if self.importLayer(layerType, providerKey, layerName, filename, parent):
                        added += 1

        if data.hasFormat(self.QGIS_URI_MIME):
            for uri in QgsMimeDataUtils.decodeUriList(data):
                if canImportLayer:
                    if self.importLayer(uri.layerType, uri.providerKey, uri.name, uri.uri, parent):
                        added += 1

        return added > 0
Пример #12
0
    def toQgsDataSourceUri(self):
        """
        Returns a QgsDataSourceURI object with database connection properties
        defined.
        """
        dt_source = QgsDataSourceURI()
        dt_source.setConnection(self.Host, unicode(self.Port), self.Database,
                                self.User.UserName, unicode(self.User.Password))

        return dt_source
Пример #13
0
 def fromLayer(cls, layer):
     uri = QgsDataSourceURI(layer.dataProvider().dataSourceUri())
     connectioninfo = {
         "host": uri.host(),
         "database": uri.database(),
         "user": uri.username(),
         "password": uri.password(),
         "connectionname": layer.id()
     }
     database = Database.connect(**connectioninfo)
     return database
Пример #14
0
    def toQgsDataSourceUri(self):
        """
        Returns a QgsDataSourceURI object with database connection properties
        defined.
        """
        dt_source = QgsDataSourceURI()
        dt_source.setConnection(self.Host, unicode(self.Port),
                                self.Database, self.User.UserName,
                                unicode(self.User.Password))

        return dt_source
Пример #15
0
 def getFullLayerName(self, sender):
     """
     Gets the layer name as present in the rules
     """
     try:
         uri = sender.dataProvider().dataSourceUri()
         dsUri = QgsDataSourceURI(uri)
         name = '.'.join([dsUri.schema(), dsUri.table()])
     except:
         name = ''
     return name
Пример #16
0
    def importLayer(self, layerType, providerKey, layerName, uriString,
                    parent):
        global isImportVectorAvail

        if not isImportVectorAvail:
            return False

        if layerType == 'raster':
            return False  # not implemented yet
            inLayer = QgsRasterLayer(uriString, layerName, providerKey)
        else:
            inLayer = QgsVectorLayer(uriString, layerName, providerKey)

        if not inLayer.isValid():
            # invalid layer
            QMessageBox.warning(
                None, self.tr("Invalid layer"),
                self.tr("Unable to load the layer %s") % inLayer.name())
            return False

        # retrieve information about the new table's db and schema
        outItem = parent.internalPointer()
        outObj = outItem.getItemData()
        outDb = outObj.database()
        outSchema = None
        if isinstance(outItem, SchemaItem):
            outSchema = outObj
        elif isinstance(outItem, TableItem):
            outSchema = outObj.schema()

        # toIndex will point to the parent item of the new table
        toIndex = parent
        if isinstance(toIndex.internalPointer(), TableItem):
            toIndex = toIndex.parent()

        if inLayer.type() == inLayer.VectorLayer:
            # create the output uri
            schema = outSchema.name if outDb.schemas(
            ) is not None and outSchema is not None else ""
            pkCol = geomCol = ""

            # default pk and geom field name value
            if providerKey in ['postgres', 'spatialite']:
                inUri = QgsDataSourceURI(inLayer.source())
                pkCol = inUri.keyColumn()
                geomCol = inUri.geometryColumn()

            outUri = outDb.uri()
            outUri.setDataSource(schema, layerName, geomCol, "", pkCol)

            self.importVector.emit(inLayer, outDb, outUri, toIndex)
            return True

        return False
Пример #17
0
    def postgis_path_to_uri(path):
        """Convert layer path from QgsBrowserModel to full QgsDataSourceURI.

        :param path: The layer path from QgsBrowserModel
        :type path: string

        :returns: layer uri.
        :rtype: QgsDataSourceURI
        """

        connection_name = path.split('/')[1]
        schema = path.split('/')[2]
        table_name = path.split('/')[3]

        settings = QSettings()
        key = "/PostgreSQL/connections/" + connection_name
        service = settings.value(key + "/service")
        host = settings.value(key + "/host")
        port = settings.value(key + "/port")
        if not port:
            port = "5432"
        db = settings.value(key + "/database")
        use_estimated_metadata = settings.value(
            key + "/estimatedMetadata", False, type=bool)
        sslmode = settings.value(
            key + "/sslmode", QgsDataSourceURI.SSLprefer, type=int)
        username = ""
        password = ""
        if settings.value(key + "/saveUsername") == "true":
            username = settings.value(key + "/username")

        if settings.value(key + "/savePassword") == "true":
            password = settings.value(key + "/password")

        # Old save setting
        if settings.contains(key + "/save"):
            username = settings.value(key + "/username")
            if settings.value(key + "/save") == "true":
                password = settings.value(key + "/password")

        uri = QgsDataSourceURI()
        if service:
            uri.setConnection(service, db, username, password, sslmode)
        else:
            uri.setConnection(host, port, db, username, password, sslmode)

        uri.setUseEstimatedMetadata(use_estimated_metadata)

        # Obtain the geometry column name
        connector = PostGisDBConnector(uri)
        tables = connector.getVectorTables(schema)
        tables = [table for table in tables if table[1] == table_name]
        if not tables:
            return None
        table = tables[0]
        geom_col = table[8]

        uri.setDataSource(schema, table_name, geom_col)
        return uri
Пример #18
0
    def commit(self):
        """merge modifiactions into database"""
        print "commit"
        if self.unresolved_conflicts():
            return

        layer = QgsMapLayerRegistry.instance().mapLayer(self.current_layers[0])
        uri = QgsDataSourceURI(layer.source())

        late_by = 0
        if layer.providerType() == "spatialite":
            late_by = versioning_base.late(uri.database(), self.pg_conn_info())
        else:  #postgres
            late_by = versioning_base.pg_late(self.pg_conn_info(),
                                              uri.schema())

        if late_by:
            QMessageBox.warning(
                self.iface.mainWindow(), "Warning",
                "This working copy is not up to date (late by " +
                str(late_by) + " commit(s)).\n\n"
                "Please update before commiting your modifications")
            print "aborted"
            return

        # time to get the commit message
        if not self.q_commit_msg_dlg.exec_():
            return
        commit_msg = self.commit_msg_dlg.commitMessage.document().toPlainText()
        if not commit_msg:
            QMessageBox.warning(self.iface.mainWindow(), "Warning",
                                "No commit message, aborting commit")
            print "aborted"
            return

        nb_of_updated_layer = 0
        rev = 0
        if layer.providerType() == "spatialite":
            nb_of_updated_layer = versioning_base.commit(
                uri.database(), commit_msg, self.pg_conn_info())
            rev = versioning_base.revision(uri.database())
        else:  # postgres
            nb_of_updated_layer = versioning_base.pg_commit(
                uri.connectionInfo(), uri.schema(), commit_msg)
            rev = versioning_base.pg_revision(uri.connectionInfo(),
                                              uri.schema())

        if nb_of_updated_layer:
            QMessageBox.information(
                self.iface.mainWindow(), "Info",
                "You have successfully commited revision " + str(rev))
        else:
            QMessageBox.information(self.iface.mainWindow(), "Info",
                                    "There was no modification to commit")
Пример #19
0
 def updateOriginalLayer(self, pgInputLayer, qgisOutputVector, featureList=None, featureTupleList=None):
     """
     Updates the original layer using the grass output layer
     pgInputLyr: postgis input layer
     grassOutputLyr: grass output layer
     """
     provider = pgInputLayer.dataProvider()
     # getting keyColumn because we want to be generic
     uri = QgsDataSourceURI(pgInputLayer.dataProvider().dataSourceUri())
     keyColumn = uri.keyColumn()
     # starting edition mode
     pgInputLayer.startEditing()
     addList = []
     idsToRemove = []
     #making the changes and inserts
     for feature in pgInputLayer.getFeatures():
         id = feature.id()
         outFeats = []
         #getting the output features with the specific id
         if qgisOutputVector:
             for gf in qgisOutputVector.dataProvider().getFeatures(QgsFeatureRequest(QgsExpression("{0}={1}".format(keyColumn, id)))):
                 outFeats.append(gf)
         elif featureTupleList:
             for gfid, gf in featureTupleList:
                 if gfid == id and gf['classname'] == pgInputLayer.name():
                     outFeats.append(gf)
         else:
             for gf in [gf for gf in featureList if gf.id() == id]:
                 outFeats.append(gf)
         #starting to make changes
         for i in range(len(outFeats)):
             if i == 0:
                 #let's update this feature
                 newGeom = outFeats[i].geometry()
                 newGeom.convertToMultiType()
                 feature.setGeometry(newGeom)
                 pgInputLayer.updateFeature(feature)
             else:
                 #for the rest, let's add them
                 newFeat = QgsFeature(feature)
                 newGeom = outFeats[i].geometry()
                 newGeom.convertToMultiType()
                 newFeat.setGeometry(newGeom)
                 idx = newFeat.fieldNameIndex(keyColumn)
                 newFeat.setAttribute(idx, provider.defaultValue(idx))
                 addList.append(newFeat)
         #in the case we don't find features in the output we should mark them to be removed
         if len(outFeats) == 0:
             idsToRemove.append(id)
     #pushing the changes into the edit buffer
     pgInputLayer.addFeatures(addList, True)
     #removing features from the layer.
     pgInputLayer.deleteFeatures(idsToRemove)
Пример #20
0
def editmultilayer():
    for layer in QgsMapLayerRegistry.instance().mapLayers().values():
        uri = QgsDataSourceURI(layer.source())
        name = uri.schema() + "." + uri.table()
        if name in [
                "qwat_od.pipe", "qwat_od.valve", "qwat_od.part",
                "qwat_od.hydrant", "qwat_od.subscriber", "qwat_od.leak"
        ]:
            if not layer.isEditable():
                layer.startEditing()
        else:
            pass
Пример #21
0
 def getDatabaseList(self):
     dbList = []
     for lyr in self.iface.legendInterface().layers():
         if isinstance(lyr, QgsVectorLayer):
             candidateUri = QgsDataSourceURI(
                 lyr.dataProvider().dataSourceUri())
             dbName = candidateUri.database()
             if dbName not in dbList and lyr.providerType() in [
                     'postgres', 'spatialite'
             ]:
                 dbList.append(dbName)
     return dbList
Пример #22
0
 def __init__(self, iface, abstractDb, loadCentroids):
     """Constructor."""
     super(EDGVLayerLoader, self).__init__()
     
     self.abstractDb = abstractDb
     self.uri = QgsDataSourceURI() 
     self.iface = iface
     self.utils = Utils()
     self.logErrorDict = dict()
     self.errorLog = ''
     self.geomTypeDict = self.abstractDb.getGeomTypeDict(loadCentroids)
     self.geomDict = self.abstractDb.getGeomDict(self.geomTypeDict)
     self.correspondenceDict = {'POINT':'Point', 'MULTIPOINT':'Point', 'LINESTRING':'Line','MULTILINESTRING':'Line', 'POLYGON':'Area', 'MULTIPOLYGON':'Area'}
Пример #23
0
    def connect(self, parent=None):
        conn_name = self.connectionName()
        settings = QSettings()
        settings.beginGroup(u"/%s/%s" % (self.connectionSettingsKey(), conn_name))

        if not settings.contains("sqlitepath"):  # non-existent entry?
            raise InvalidDataException(u'there is no defined database connection "%s".' % conn_name)

        database = settings.value("sqlitepath")

        uri = QgsDataSourceURI()
        uri.setDatabase(database)
        return self.connectToUri(uri)
Пример #24
0
    def connect(self, parent=None):
        conn_name = self.connectionName()
        settings = QSettings()
        settings.beginGroup(u"/%s/%s" % (self.connectionSettingsKey(), conn_name))

        if not settings.contains("sqlitepath"):  # non-existent entry?
            raise InvalidDataException(u'there is no defined database connection "%s".' % conn_name)

        database = settings.value("sqlitepath")

        uri = QgsDataSourceURI()
        uri.setDatabase(database)
        return self.connectToUri(uri)
Пример #25
0
    def __getPostgisPath(self, mslayer):
        """docstring for __getPostgisPath"""
        _uri = "{conn} type={type} srid={srid}".format(
            conn=mslayer["connection"],
            type=mslayer["config"]["type"],
            srid=mslayer["config"]["srid"])

        uri = QgsDataSourceURI(_uri)
        uri.setDataSource(mslayer["config"]["schema"],
                          mslayer["config"]["table"],
                          mslayer["config"]["geom"], mslayer["config"]["sql"],
                          mslayer["config"]["uid"])
        return uri.uri()
Пример #26
0
    def setWorldDatabase(self, database):
        '''Sets the world database
        :param database: Local database file (hard coded properties are used in this function)
        :return: Nothing (stores self.attributedOutputLayer, which contains assignments)
        '''

        if not os.path.exists(database):
            raise ValueError('LQF Database file ' + database + ' not found')
        self.databaseLocation = database
        self.dburi = QgsDataSourceURI()
        self.dburi.setDatabase(database)
        self.dbschema = ''
        self.dbtable = 'World'
Пример #27
0
 def getUsedDatabases():
     """
     To get all used databases in the project
     :return: databases uri list
     """
     dbs = {}
     for layer in list(QgsMapLayerRegistry.instance().mapLayers().values()):
         if layer is not None and layer.type(
         ) == QgsMapLayer.VectorLayer and layer.providerType(
         ) == "postgres":
             uri = QgsDataSourceURI(layer.source())
             if uri.database() not in dbs:
                 dbs[uri.database()] = uri
     return dbs
Пример #28
0
class SelectDateDialog(QDialog, Ui_SelectDate):
    """
    Class responsible for handling the date selection.
    """
    def __init__(self, iface):
        QDialog.__init__(self)
        self.setupUi(self)
        self.iface = iface
        self.dbconn = DBConn(iface)
        self.cmbDate.clear()
        self.get_dates()

    def get_dates(self):
        """Get all historized dates from layer"""
        provider = self.iface.activeLayer().dataProvider()
        self.uri = QgsDataSourceURI(provider.dataSourceUri())
        self.conn = self.dbconn.connect_to_DB(self.uri)
        # self.schema = self.uri.schema()
        self.execute = SQLExecute(self.iface, self.iface.mainWindow(),
                                  self.uri)
        dateList = self.execute.retrieve_all_table_versions(
            self.iface.activeLayer().name(), self.uri.schema())

        if not dateList:
            self.records = False
            QMessageBox.warning(self.iface.mainWindow(), self.tr(u"Error"),
                                self.tr(u"No historized versions found!"))
        else:
            for date in dateList:
                self.cmbDate.addItem(str(date[0]))
                self.records = True

    @pyqtSignature("")
    def on_buttonBox_accepted(self):
        """
        Run hist_tabs.version() SQL-function
        """
        if self.records:
            self.execute.get_older_table_version(
                self.uri.schema(),
                self.iface.activeLayer().name(), self.cmbDate.currentText(),
                self.uri)

    @pyqtSignature("")
    def on_buttonBox_rejected(self):
        """
        Close Window and DB-Connection
        """
        self.conn.close()
        self.close()
Пример #29
0
    def makeValueRelationDict(self, valueDict):
        ret = dict()

        codes = valueDict['FilterExpression'].replace('code in (', '').replace(')','').split(',')
        keyColumn = valueDict['Key']
        valueColumn = valueDict['Value']
        table = valueDict['Layer'][:-17]#removing the date-time characters
        
        uri = QgsDataSourceURI(self.currLayer.dataProvider().dataSourceUri())
        if uri.host() == '':
            db = QSqlDatabase('QSQLITE')
            db.setDatabaseName(uri.database())
        else:
            db = QSqlDatabase('QPSQL')
            db.setHostName(uri.host())
            db.setPort(int(uri.port()))
            db.setDatabaseName(uri.database())
            db.setUserName(uri.username())
            db.setPassword(uri.password())
        
        if not db.open():
            db.close()
            return ret

        in_clause = ','.join(map(str, codes))
        query = QSqlQuery('select code, code_name from dominios.%s where code in (%s)' % (table, in_clause), db)
        while query.next():
            code = str(query.value(0))
            code_name = query.value(1)
            ret[code_name] = code
            
        db.close()
                
        return ret
Пример #30
0
    def fromLayer(cls, layer):
        source = layer.source()
        uri = QgsDataSourceURI(layer.dataProvider().dataSourceUri())
        if ".sqlite" in source:
            try:
                index = source.index("|")
                source = source[:index]
            except ValueError:
                pass
            if uri.database():
                source = uri.database()

            connectioninfo = {"type": "QSQLITE",
                              "database": source}
        else:
            uri = QgsDataSourceURI(layer.dataProvider().dataSourceUri())
            connectioninfo = {
                "host": uri.host(),
                "database": uri.database(),
                "user": uri.username(),
                "password": uri.password()
            }
        connectioninfo["connectionname"] = layer.id()
        database = Database.connect(**connectioninfo)
        return database
Пример #31
0
def uri_from_name(conn_name):
    settings = QSettings()
    settings.beginGroup(u"/PostgreSQL/connections/%s" % conn_name)

    if not settings.contains("database"):  # non-existent entry?
        raise DbError('There is no defined database connection "%s".' %
                      conn_name)

    uri = QgsDataSourceURI()

    settingsList = [
        "service", "host", "port", "database", "username", "password",
        "authcfg"
    ]
    service, host, port, database, username, password, authcfg = [
        settings.value(x, "", type=str) for x in settingsList
    ]

    useEstimatedMetadata = settings.value("estimatedMetadata",
                                          False,
                                          type=bool)
    sslmode = settings.value("sslmode", QgsDataSourceURI.SSLprefer, type=int)

    settings.endGroup()

    if service:
        uri.setConnection(service, database, username, password, sslmode,
                          authcfg)
    else:
        uri.setConnection(host, port, database, username, password, sslmode,
                          authcfg)

    uri.setUseEstimatedMetadata(useEstimatedMetadata)

    return uri
Пример #32
0
    def importLayer(self, layerType, providerKey, layerName, uriString, parent):
        global isImportVectorAvail

        if not isImportVectorAvail:
            return False

        if layerType == 'raster':
            return False  # not implemented yet
            inLayer = QgsRasterLayer(uriString, layerName, providerKey)
        else:
            inLayer = QgsVectorLayer(uriString, layerName, providerKey)

        if not inLayer.isValid():
            # invalid layer
            QMessageBox.warning(None, self.tr("Invalid layer"), self.tr("Unable to load the layer %s") % inLayer.name())
            return False

        # retrieve information about the new table's db and schema
        outItem = parent.internalPointer()
        outObj = outItem.getItemData()
        outDb = outObj.database()
        outSchema = None
        if isinstance(outItem, SchemaItem):
            outSchema = outObj
        elif isinstance(outItem, TableItem):
            outSchema = outObj.schema()

        # toIndex will point to the parent item of the new table
        toIndex = parent
        if isinstance(toIndex.internalPointer(), TableItem):
            toIndex = toIndex.parent()

        if inLayer.type() == inLayer.VectorLayer:
            # create the output uri
            schema = outSchema.name if outDb.schemas() is not None and outSchema is not None else ""
            pkCol = geomCol = ""

            # default pk and geom field name value
            if providerKey in ['postgres', 'spatialite']:
                inUri = QgsDataSourceURI(inLayer.source())
                pkCol = inUri.keyColumn()
                geomCol = inUri.geometryColumn()

            outUri = outDb.uri()
            outUri.setDataSource(schema, layerName, geomCol, "", pkCol)

            self.importVector.emit(inLayer, outDb, outUri, toIndex)
            return True

        return False
Пример #33
0
    def addConnectionActionSlot(self, item, action, parent, index):
        QApplication.restoreOverrideCursor()
        try:
            filename = QFileDialog.getOpenFileName(parent, "Choose Sqlite/Spatialite/Geopackage file")
            if not filename:
                return
        finally:
            QApplication.setOverrideCursor(Qt.WaitCursor)

        conn_name = QFileInfo(filename).fileName()
        uri = QgsDataSourceURI()
        uri.setDatabase(filename)
        self.addConnection(conn_name, uri)
        index.internalPointer().emit(SIGNAL('itemChanged'), index.internalPointer())
Пример #34
0
    def addConnectionActionSlot(self, item, action, parent, index):
        QApplication.restoreOverrideCursor()
        try:
            filename = QFileDialog.getOpenFileName(parent, "Choose Sqlite/Spatialite/Geopackage file")
            if not filename:
                return
        finally:
            QApplication.setOverrideCursor(Qt.WaitCursor)

        conn_name = QFileInfo(filename).fileName()
        uri = QgsDataSourceURI()
        uri.setDatabase(filename)
        self.addConnection(conn_name, uri)
        index.internalPointer().itemChanged.emit(index.internalPointer())
Пример #35
0
 def checkLoaded(self, name, loadedLayers):
     """
     Checks if the layers is already loaded in the QGIS' TOC
     :param name:
     :param loadedLayers:
     :return:
     """
     loaded = None
     for ll in loadedLayers:
         if ll.name() == name:
             candidateUri = QgsDataSourceURI(ll.dataProvider().dataSourceUri())
             if self.host == candidateUri.host() and self.database == candidateUri.database() and self.port == int(candidateUri.port()):
                 return ll
     return loaded
Пример #36
0
	def connect(self, parent=None):
		conn_name = self.connectionName()
		settings = QSettings()
		settings.beginGroup( u"/%s/%s" % (self.connectionSettingsKey(), conn_name) )

		if not settings.contains( "database" ): # non-existent entry?
			raise InvalidDataException( self.tr('There is no defined database connection "%s".') % conn_name )

		from qgis.core import QgsDataSourceURI
		uri = QgsDataSourceURI()

		settingsList = ["service", "host", "port", "database", "username", "password"]
		service, host, port, database, username, password = map(lambda x: settings.value(x, "", type=str), settingsList)

		# qgis1.5 use 'savePassword' instead of 'save' setting
		savedPassword = settings.value("save", False, type=bool) or settings.value("savePassword", False, type=bool)

		useEstimatedMetadata = settings.value("estimatedMetadata", False, type=bool)
		sslmode = settings.value("sslmode", QgsDataSourceURI.SSLprefer, type=int)

		settings.endGroup()

		if service:
			uri.setConnection(service, database, username, password, sslmode)
		else:
			uri.setConnection(host, port, database, username, password, sslmode)

		uri.setUseEstimatedMetadata(useEstimatedMetadata)

		try:
			return self.connectToUri(uri)
		except ConnectionError, e:
			return False
Пример #37
0
    def commit(self):
        """merge modifiactions into database"""
        print "commit"
        if self.unresolved_conflicts():
            return

        layer = QgsMapLayerRegistry.instance().mapLayer(
                self.current_layers[0] )
        uri = QgsDataSourceURI(layer.source())

        late_by = 0
        if layer.providerType() == "spatialite":
            late_by = versioning_base.late(
                    uri.database(), self.pg_conn_info() )
        else:#postgres
            late_by = versioning_base.pg_late(
                    self.pg_conn_info(), uri.schema() )

        if late_by:
            QMessageBox.warning(self.iface.mainWindow(), "Warning",
                    "This working copy is not up to date (late by "
                    +str(late_by)+" commit(s)).\n\n"
                    "Please update before commiting your modifications")
            print "aborted"
            return

        # time to get the commit message
        if not self.q_commit_msg_dlg.exec_():
            return
        commit_msg = self.commit_msg_dlg.commitMessage.document().toPlainText()
        if not commit_msg:
            QMessageBox.warning(self.iface.mainWindow(), "Warning",
                    "No commit message, aborting commit")
            print "aborted"
            return

        nb_of_updated_layer = 0
        rev = 0
        if layer.providerType() == "spatialite":
            nb_of_updated_layer = versioning_base.commit( uri.database(),
                    commit_msg, self.pg_conn_info() )
            rev = versioning_base.revision(uri.database())
        else: # postgres
            nb_of_updated_layer = versioning_base.pg_commit(
                    uri.connectionInfo(), uri.schema(), commit_msg )
            rev = versioning_base.pg_revision(
                    uri.connectionInfo(), uri.schema())

        if nb_of_updated_layer:
            QMessageBox.information(self.iface.mainWindow(), "Info",
                    "You have successfully commited revision "+str( rev ) )
        else:
            QMessageBox.information(self.iface.mainWindow(), "Info",
                    "There was no modification to commit")
Пример #38
0
    def load(self, crs, idSubgrupo = None):
        vlayerQml = os.path.join(self.abstractDb.getQmlDir(), self.qmlName+'.qml')
        

        database = self.abstractDb.db.databaseName()

        vlayer = iface.addVectorLayer(self.uri.uri(), self.layer_name, self.provider)
        if not vlayer:
            return None

        vlayer.setCrs(crs)
        if self.schema <> 'views':
            vlayer.loadNamedStyle(vlayerQml, False)
            attrList = vlayer.pendingFields()
            for field in attrList:
                i = vlayer.fieldNameIndex(field.name())
                if vlayer.editorWidgetV2(i) == 'ValueRelation':
                    groupList = iface.legendInterface().groups()
                    groupRelationshipList = iface.legendInterface().groupLayerRelationship()
                    filename = os.path.basename(database).split('.')[0]
                    if filename not in groupList:
                        idx = iface.legendInterface().addGroup(filename, True,-1)
                        domainIdGroup = iface.legendInterface().addGroup(self.tr("Dominios"), True, idx)
                    else:
                        idx = groupList.index(filename)
                        if "Dominios" not in groupList[idx::]:
                            domainIdGroup = iface.legendInterface().addGroup(self.tr("Dominios"), True, idx)
                        else:
                            domainIdGroup = groupList[idx::].index("Dominios")
    
                    valueRelationDict = vlayer.editorWidgetV2Config(i)
                    domainTableName = valueRelationDict['Layer']
                    loadedLayers = iface.legendInterface().layers()
                    domainLoaded = False
                    for ll in loadedLayers:
                        if ll.name() == domainTableName:
                            candidateUri = QgsDataSourceURI(ll.dataProvider().dataSourceUri())
                            if database == candidateUri.database():
                                domainLoaded = True
                                domLayer = ll
                    if not domainLoaded:
                        uri = QgsDataSourceURI()
                        uri.setDatabase(database)
                        uri.setDataSource('', 'dominios_'+domainTableName, None)
                        #TODO Load domain layer into a group
                        domLayer = iface.addVectorLayer(uri.uri(), domainTableName, self.provider)
                        iface.legendInterface().moveLayer(domLayer, domainIdGroup)
                    valueRelationDict['Layer'] = domLayer.id()
                    vlayer.setEditorWidgetV2Config(i,valueRelationDict)
    
            self.qmlLoaded.emit()
        

        iface.legendInterface().moveLayer(vlayer, idSubgrupo)
            
        if not vlayer.isValid():
            QgsMessageLog.logMessage(vlayer.error().summary(), "DSG Tools Plugin", QgsMessageLog.CRITICAL)

        return vlayer
Пример #39
0
 def checkLoaded(self, name, loadedLayers):
     """
     Checks if the layers is already loaded in the QGIS' TOC
     :param name: 
     :param loadedLayers: 
     :return:
     """
     loaded = None
     database = self.abstractDb.db.databaseName()
     for ll in loadedLayers:
         if ll.name() == name:
             candidateUri = QgsDataSourceURI(ll.dataProvider().dataSourceUri())
             if database == candidateUri.database():
                 return ll
     return loaded
Пример #40
0
def pg_layerNamesIDMapping():
    '''
    Returns a dictionary containing the original table names and corresponding layer IDs in the
    QGIS legend for only those layers from a postgres database.
    '''
    mapping = ReverseDict()
    layers = QgsMapLayerRegistry.instance().mapLayers()

    for name, layer in layers.iteritems():
        if layer.dataProvider().name() == 'postgres':
            layerConnStr = layer.dataProvider().dataSourceUri()
            dataSourceURI = QgsDataSourceURI(layerConnStr)
            mapping[dataSourceURI.table()] = layer.id()

    return mapping
Пример #41
0
    def refresh(self):
        """
        Refreshes the network graph. It will force a refresh of the materialized views in the database and then reload
        and recreate the graph.
        """
        uri = QgsDataSourceURI(self.nodeLayer.dataProvider().dataSourceUri())

        db = QSqlDatabase.addDatabase(
            "QPSQL")  # Name of the driver -- doesn't change

        str_connect_option = "requiressl=0;service=" + uri.service()
        db.setConnectOptions(str_connect_option)

        if not db.open():
            self.iface.messageBar().pushMessage(self.tr("Warning"),
                                                db.lastError().text(),
                                                level=QgsMessageBar.CRITICAL)

        query_template = "REFRESH MATERIALIZED VIEW qgep.vw_network_segment;"
        query = QSqlQuery(db)
        if not query.exec_(query_template):
            str_result = query.lastError().text()
            self.iface.messageBar().pushMessage(self.tr("Warning"),
                                                str_result,
                                                level=QgsMessageBar.CRITICAL)
        else:
            self.iface.messageBar().pushMessage(
                self.tr("Success"),
                "vw_network_segment successfully updated",
                level=QgsMessageBar.SUCCESS,
                duration=2)

        query_template = "REFRESH MATERIALIZED VIEW qgep.vw_network_node;"
        query = QSqlQuery(db)
        if not query.exec_(query_template):
            str_result = query.lastError().text()
            self.iface.messageBar().pushMessage(self.tr("Warning"),
                                                str_result,
                                                level=QgsMessageBar.CRITICAL)
        else:
            self.iface.messageBar().pushMessage(
                self.tr("Success"),
                "vw_network_node successfully updated",
                level=QgsMessageBar.SUCCESS,
                duration=2)
        # recreate networkx graph
        self.graph.clear()
        self.createGraph()
Пример #42
0
    def set_importable_tables(self):
        """Populates combobox with importable tables

           Name Structure <schema.tablename>"""
        self.uri = QgsDataSourceURI(self.provider.dataSourceUri())
        self.execute = SQLExecute(
            self.iface, self.iface.mainWindow(), self.uri)

        # Returns Result to be parsed
        schemaTableList = self.execute.retrieve_all_importable_tables()
        cmbList = list()
        if schemaTableList:
            for entry in schemaTableList:
                cmbEntry = entry[0] + '.' + entry[1]
                cmbList.append(cmbEntry)
        self.cmbImportTable.addItems(cmbList)
    def selection_changed(self, newSelection, oldSelection):
        """
        Triggered when the user clicks on a postgresql table in the tree.
        :param newSelection:
        :param oldSelection:
        :return:
        """
        self.empty_fields()
        selected = newSelection.indexes()

        if len(selected) > 0:

            b = self.model.dataItem(selected[0])

            if type(b) == QgsLayerItem:

                self.schema = QgsDataSourceURI(b.uri()).schema()

                self.selected_item = b
                self.update_grid()
                self.activate_fields()

                if self.has_table_data:
                    self.tableView.selectRow(0)
                else:
                    self.tableView.setModel(None)
                    self.currentlySelectedLine = None
                    self.dateEdit.setDateTime(datetime.now())
            else:
                self.deactivate_fields()
Пример #44
0
    def get_layer_source_from_credentials(self):

        # Get database parameters from layer 'version'
        layer = self.get_layer_by_tablename("version")
        if not layer:
            self.last_error = self.tr("Layer not found") + ": 'version'"
            return None

        layer_source = self.get_layer_source(layer)
        self.schema_name = layer_source['schema']

        conn_info = QgsDataSourceURI(
            layer.dataProvider().dataSourceUri()).connectionInfo()
        (success, user,
         pwd) = QgsCredentials.instance().get(conn_info, None, None)
        # Put the credentials back (for yourself and the provider), as QGIS removes it when you "get" it
        if success:
            QgsCredentials.instance().put(conn_info, user, pwd)
            layer_source['user'] = user
            layer_source['password'] = pwd
            return layer_source
        else:
            self.log_info("Error getting credentials")
            self.last_error = "Error getting credentials"
            return None
Пример #45
0
 def pgUri(self):
     """QgsDataSourceURI for selected PostGIS DB"""
     key = u"/PostgreSQL/connections/" + self.ui.cbDbConnections.currentText()
     settings = QSettings()
     settings.beginGroup(key)
     uri = QgsDataSourceURI()
     uri.setConnection(
         settings.value("host", type=str),
         settings.value("port", type=str),
         settings.value("database", type=str),
         settings.value("username", type=str),
         settings.value("password", type=str),
         QgsDataSourceURI.SSLmode(settings.value("sslmode", type=int))
     )
     uri.setUseEstimatedMetadata(settings.value("estimatedMetadata", type=bool))
     return uri
Пример #46
0
    def createParcelLayer(self):
        uri = QgsDataSourceURI()
        uri.setConnection(self.db_hostName, str(self.db_Port), self.db_databaseName, self.db_UserName, self.db_password)
        uri.setDataSource("cadastre", "cadastre_object", "geom_polygon")
        uri.uri()
        print uri.uri()

        rlayer = self.iface.addVectorLayer(uri.uri(), "Parcels", "postgres")
        self.iface.setActiveLayer(rlayer)

        rlayer.loadNamedStyle(self.plugin_dir + '/parcel.qml')
        #rlayer.layerModified.connect(self.captureFeatures)
        rlayer.featureAdded.connect(self.captureFeatures)
        rlayer.setEditForm(self.plugin_dir + os.sep + 'createForm.ui')
        #rlayer.setEditFormInit('.CreateFormDialog.formOpen')
        rlayer.startEditing()
Пример #47
0
 def __onDstOk(self):
     """
     When the Ok button in Duplicate Distance Dialog is pushed
     """
     self.__onDstPreview()
     self.__dstDlg.close()
     self.__canvas.scene().removeItem(self.__rubberBand)
     geometry = QgsGeometry(self.__newFeature)
     if not geometry.isGeosValid():
         self.__iface.messageBar().pushMessage(QCoreApplication.translate("VDLTools","Error"),
                                               QCoreApplication.translate("VDLTools","Geos geometry problem"),
                                               level=QgsMessageBar.CRITICAL)
     self.__rubberBand = None
     feature = QgsFeature(self.__layer.pendingFields())
     feature.setGeometry(geometry)
     primaryKey = QgsDataSourceURI(self.__layer.source()).keyColumn()
     for field in self.__selectedFeature.fields():
         if field.name() != primaryKey:
             feature.setAttribute(field.name(), self.__selectedFeature.attribute(field.name()))
     if len(self.__selectedFeature.fields()) > 0 and \
                     self.__layer.editFormConfig().suppress() != QgsEditFormConfig.SuppressOn:
         self.__iface.openFeatureForm(self.__layer, feature)
     else:
         self.__layer.addFeature(feature)
     self.__layer.updateExtents()
     self.__isEditing = 0
     self.__layer.removeSelection()
Пример #48
0
 def on_applyPushButton_clicked(self):
     try:
         QApplication.setOverrideCursor(QCursor(Qt.WaitCursor))
         dbName = self.dbComboBox.currentText()
         styleName = self.styleComboBox.currentText()
         lyrList = self.getLayers(dbName)
         abstractDb = self.getAbstractDb(dbName)
         dbVersion = abstractDb.getDatabaseVersion()
         stylesDict = abstractDb.getStyleDict(dbVersion)
         selectedStyle = stylesDict[styleName]
         localProgress = ProgressWidget(
             1,
             len(lyrList) - 1,
             self.tr('Loading style {0}').format(styleName),
             parent=self.iface.mapCanvas())
         for lyr in lyrList:
             try:
                 uri = QgsDataSourceURI(lyr.dataProvider().dataSourceUri())
                 fullPath = self.getStyle(abstractDb, selectedStyle,
                                          lyr.name())
                 if fullPath:
                     lyr.applyNamedStyle(fullPath)
             except:
                 pass
             localProgress.step()
         self.iface.mapCanvas().refreshAllLayers()
         QApplication.restoreOverrideCursor()
     except Exception as e:
         QgsMessageLog.logMessage(
             self.tr('Error setting style ') + styleName + ': ' +
             ':'.join(e.args), "DSG Tools Plugin", QgsMessageLog.CRITICAL)
         QApplication.restoreOverrideCursor()
Пример #49
0
 def checkLoaded(self, name, loadedLayers):
     """
     Checks if the layers is already loaded in the QGIS' TOC
     :param name: 
     :param loadedLayers: 
     :return:
     """
     loaded = None
     database = self.abstractDb.db.databaseName()
     for ll in loadedLayers:
         if ll.name() == name:
             candidateUri = QgsDataSourceURI(
                 ll.dataProvider().dataSourceUri())
             if database == candidateUri.database():
                 return ll
     return loaded
Пример #50
0
 def __onConfirmCopy(self):
     """
     When the Copy button in Move Confirm Dialog is pushed
     """
     geometry = QgsGeometry(self.__newFeature)
     if not geometry.isGeosValid():
         self.__iface.messageBar().pushMessage(QCoreApplication.translate(
             "VDLTools", "Geos geometry problem"),
                                               level=QgsMessageBar.CRITICAL,
                                               duration=0)
     feature = QgsFeature(self.__layer.pendingFields())
     feature.setGeometry(geometry)
     primaryKey = QgsDataSourceURI(self.__layer.source()).keyColumn()
     for field in self.__selectedFeature.fields():
         if field.name() != primaryKey:
             feature.setAttribute(
                 field.name(),
                 self.__selectedFeature.attribute(field.name()))
     if len(self.__selectedFeature.fields()) > 0 and self.__layer.editFormConfig().suppress() != \
             QgsEditFormConfig.SuppressOn:
         self.__iface.openFeatureForm(self.__layer, feature)
     else:
         self.__layer.addFeature(feature)
     self.__confDlg.accept()
     self.__cancel()
    def __init__(self, parent=None):
        """Constructor."""
        super(AirviroOfflineEdbDockWidget, self).__init__(parent)
        # Set up the user interface from Designer.
        # After setupUI you can access any designer object by doing
        # self.<objectname>, and you can use autoconnect slots - see
        # http://qt-project.org/doc/qt-4.8/designer-using-a-ui-file.html
        # #widgets-and-dialogs-with-auto-connect
        self.setupUi(self)

        self.create_db_lineedit.clear()
        self.create_db_browse_btn.clicked.connect(
            self.select_save_db_filename
        )

        self.open_db_lineedit.clear()
        self.open_db_browse_btn.clicked.connect(
            self.select_open_db_filename
        )

        self.open_edb_btn.clicked.connect(
            self.open_db
        )

        self.db_uri = QgsDataSourceURI()
        self.con = None
        self.cur = None
        self.epsg = None
        self.layers = {}
Пример #52
0
    def start(self):
        """
        To start the importation
        """
        if self.__ownSettings is None:
            self.__iface.messageBar().pushMessage(
                QCoreApplication.translate("VDLTools", "Error"),
                QCoreApplication.translate("VDLTools", "No settings given !!"),
                level=QgsMessageBar.CRITICAL)
            return
        if self.__ownSettings.configTable() is None:
            self.__iface.messageBar().pushMessage(
                QCoreApplication.translate("VDLTools", "Error"),
                QCoreApplication.translate("VDLTools",
                                           "No config table given !!"),
                level=QgsMessageBar.CRITICAL)
            return
        self.__configTable = self.__ownSettings.configTable()

        dataSource = QgsDataSourceURI(self.__layer.source())
        self.__db = DBConnector.setConnection(dataSource.database(),
                                              self.__iface)
        if self.__db:
            query = self.__db.exec_("""SELECT DISTINCT source FROM """ +
                                    self.__configTable +
                                    """ WHERE source NOT NULL""")
            while query.next():
                if self.__sourceTable == "":
                    self.__sourceTable = query.value(0)
                elif self.__sourceTable != query.value(0):
                    self.__iface.messageBar().pushMessage(
                        QCoreApplication.translate("VDLTools", "Error"),
                        QCoreApplication.translate(
                            "VDLTools",
                            "different sources in config table ?!?"),
                        level=QgsMessageBar.WARNING)
            query = self.__db.exec_("""SELECT DISTINCT job FROM """ +
                                    self.__sourceTable + """ WHERE
                traitement = 'non-traité'""")
            jobs = []
            while query.next():
                jobs.append(query.value(0))

            self.__jobsDlg = ImportJobsDialog(jobs)
            self.__jobsDlg.okButton().clicked.connect(self.__onOk)
            self.__jobsDlg.cancelButton().clicked.connect(self.__onCancel)
            self.__jobsDlg.show()
Пример #53
0
 def loadSpatialiteLayers(self):
     self.getSelectedItems()
     uri = QgsDataSourceURI()
     uri.setDatabase(self.filename)
     schema = ''
     geom_column = 'GEOMETRY'
     if len(self.selectedClasses)>0:
         try:
             for layer_name in self.selectedClasses:
                 uri.setDataSource(schema, layer_name, geom_column)
                 self.loadEDGVLayer(uri, layer_name, 'spatialite')
             self.restoreInitialState()
             self.close()
         except:
             self.bar.pushMessage(self.tr("Error!"), self.tr("Could not load the layer(s)!"), level=QgsMessageBar.CRITICAL)
     else:
         self.bar.pushMessage(self.tr("Warning!"), self.tr("Please select at least one layer!"), level=QgsMessageBar.WARNING)
Пример #54
0
 def checkLoaded(self, name, loadedLayers):
     """
     Checks if the layers is already loaded in the QGIS' TOC
     :param name:
     :param loadedLayers:
     :return:
     """
     loaded = None
     for ll in loadedLayers:
         if ll.name() == name:
             candidateUri = QgsDataSourceURI(
                 ll.dataProvider().dataSourceUri())
             if self.host == candidateUri.host(
             ) and self.database == candidateUri.database(
             ) and self.port == int(candidateUri.port()):
                 return ll
     return loaded
Пример #55
0
 def aoiExtent(cls):
     """Area of interest extent, which matches output aspect ratio"""
     uri = QgsDataSourceURI()
     uri.setDatabase(cls._PalFeaturesDb)
     uri.setDataSource('', 'aoi', 'geometry')
     aoilayer = QgsVectorLayer(uri.uri(), 'aoi', 'spatialite')
     return aoilayer.extent()
Пример #56
0
    def __load_sensor_to_qgis(self):
        # Create a vector layer loading data from freewat_sensor table (sqlite db)
        layer = QgsMapLayerRegistry.instance().mapLayersByName(
            config.oat_layer_name)

        db_path = self.db.get_db_path()

        if not db_path:
            return

        if len(layer) > 0:
            return

        uri = QgsDataSourceURI()
        uri.setDatabase(db_path)
        schema = ''
        table = 'freewat_sensors'
        geom_column = 'geom'
        uri.setDataSource(schema, table, geom_column)

        display_name = config.oat_layer_name

        # create QGIS layer
        self.sensor_layer = QgsVectorLayer(uri.uri(), display_name,
                                           'spatialite')
        QgsMapLayerRegistry.instance().addMapLayer(self.sensor_layer)
Пример #57
0
	def connect(self, parent=None):
		conn_name = self.connectionName()
		settings = QSettings()
		settings.beginGroup( u"/%s/%s" % (self.connectionSettingsKey(), conn_name) )

		if not settings.contains( "database" ): # non-existent entry?
			raise InvalidDataException( self.tr('There is no defined database connection "%s".') % conn_name )

		from qgis.core import QgsDataSourceURI
		uri = QgsDataSourceURI()

		settingsList = ["service", "host", "port", "database", "username", "password"]
		service, host, port, database, username, password = map(lambda x: settings.value(x), settingsList)

		# qgis1.5 use 'savePassword' instead of 'save' setting
		savedPassword = settings.value("save", False, type=bool) or settings.value("savePassword", False, type=bool)

		useEstimatedMetadata = settings.value("estimatedMetadata", False, type=bool)
		sslmode = settings.value("sslmode", QgsDataSourceURI.SSLprefer, type=int)

		settings.endGroup()

		if service:
			uri.setConnection(service, database, username, password, sslmode)
		else:
			uri.setConnection(host, port, database, username, password, sslmode)

		uri.setUseEstimatedMetadata(useEstimatedMetadata)

		err = u""
		try:
			return self.connectToUri(uri)
		except ConnectionError, e:
			err = str(e)
Пример #58
0
    def connect(self, parent=None):
        conn_name = self.connectionName()
        settings = QSettings()
        settings.beginGroup(u"/%s/%s" % (self.connectionSettingsKey(), conn_name))

        if not settings.contains("database"):  # non-existent entry?
            raise InvalidDataException(self.tr('There is no defined database connection "%s".') % conn_name)

        from qgis.core import QgsDataSourceURI

        uri = QgsDataSourceURI()

        settingsList = ["service", "host", "port", "database", "username", "password", "authcfg"]
        service, host, port, database, username, password, authcfg = [settings.value(x, "", type=str) for x in settingsList]

        useEstimatedMetadata = settings.value("estimatedMetadata", False, type=bool)
        sslmode = settings.value("sslmode", QgsDataSourceURI.SSLprefer, type=int)

        settings.endGroup()

        if service:
            uri.setConnection(service, database, username, password, sslmode, authcfg)
        else:
            uri.setConnection(host, port, database, username, password, sslmode, authcfg)

        uri.setUseEstimatedMetadata(useEstimatedMetadata)

        try:
            return self.connectToUri(uri)
        except ConnectionError:
            return False
Пример #59
0
def uri_from_name(conn_name):
    settings = QSettings()
    settings.beginGroup(u"/PostgreSQL/connections/%s" % conn_name)

    if not settings.contains("database"):  # non-existent entry?
        raise DbError('There is no defined database connection "%s".' % conn_name)

    uri = QgsDataSourceURI()

    settingsList = ["service", "host", "port", "database", "username", "password", "authcfg"]
    service, host, port, database, username, password, authcfg = [settings.value(x, "", type=str) for x in settingsList]

    useEstimatedMetadata = settings.value("estimatedMetadata", False, type=bool)
    sslmode = settings.value("sslmode", QgsDataSourceURI.SSLprefer, type=int)

    settings.endGroup()

    if service:
        uri.setConnection(service, database, username, password, sslmode, authcfg)
    else:
        uri.setConnection(host, port, database, username, password, sslmode, authcfg)

    uri.setUseEstimatedMetadata(useEstimatedMetadata)

    return uri
Пример #60
0
    def saveToSpatialite(self):
        fileFilter = self.output.tr('Spatialite files(*.sqlite)', 'OutputFile')

        settings = QSettings()
        if settings.contains('/Processing/LastOutputPath'):
            path = settings.value('/Processing/LastOutputPath')
        else:
            path = ProcessingConfig.getSetting(ProcessingConfig.OUTPUT_FOLDER)

        encoding = settings.value('/Processing/encoding', 'System')
        fileDialog = QgsEncodingFileDialog(self, self.tr('Save Spatialite'),
                                           path, fileFilter, encoding)
        fileDialog.setFileMode(QFileDialog.AnyFile)
        fileDialog.setAcceptMode(QFileDialog.AcceptSave)
        fileDialog.setConfirmOverwrite(False)

        if fileDialog.exec_() == QDialog.Accepted:
            files = fileDialog.selectedFiles()
            encoding = unicode(fileDialog.encoding())
            self.output.encoding = encoding
            fileName = unicode(files[0])
            selectedFileFilter = unicode(fileDialog.selectedNameFilter())
            if not fileName.lower().endswith(
                    tuple(re.findall("\*(\.[a-z]{1,10})", fileFilter))):
                ext = re.search("\*(\.[a-z]{1,10})", selectedFileFilter)
                if ext:
                    fileName += ext.group(1)
            settings.setValue('/Processing/LastOutputPath',
                              os.path.dirname(fileName))
            settings.setValue('/Processing/encoding', encoding)

            uri = QgsDataSourceURI()
            uri.setDatabase(fileName)
            uri.setDataSource('', self.output.name.lower(), 'the_geom')
            self.leText.setText("spatialite:" + uri.uri())