本文整理汇总了Python中qgis.core.QgsDataSourceUri.table方法的典型用法代码示例。如果您正苦于以下问题:Python QgsDataSourceUri.table方法的具体用法?Python QgsDataSourceUri.table怎么用?Python QgsDataSourceUri.table使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类qgis.core.QgsDataSourceUri
的用法示例。
在下文中一共展示了QgsDataSourceUri.table方法的12个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: onUpdateSqlLayer
# 需要导入模块: from qgis.core import QgsDataSourceUri [as 别名]
# 或者: from qgis.core.QgsDataSourceUri import table [as 别名]
def onUpdateSqlLayer(self):
l = self.iface.activeLayer()
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)
示例2: onUpdateSqlLayer
# 需要导入模块: from qgis.core import QgsDataSourceUri [as 别名]
# 或者: from qgis.core.QgsDataSourceUri import table [as 别名]
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)
示例3: getConnectionParameterFromDbLayer
# 需要导入模块: from qgis.core import QgsDataSourceUri [as 别名]
# 或者: from qgis.core.QgsDataSourceUri import table [as 别名]
def getConnectionParameterFromDbLayer(layer: QgsMapLayer) -> Dict[str,str]:
'''
Get connection parameters
from the layer datasource
'''
connectionParams = None
if layer.providerType() == 'postgres':
dbType = 'postgis'
else:
dbType = 'spatialite'
src = layer.source()
try:
uri = QgsDataSourceUri(src)
except:
uri = QgsDataSourceURI(src)
# TODO Use immutable namedtuple
connectionParams = {
'service' : uri.service(),
'dbname' : uri.database(),
'host' : uri.host(),
'port': uri.port(),
'user' : uri.username(),
'password': uri.password(),
'sslmode' : uri.sslMode(),
'key': uri.keyColumn(),
'estimatedmetadata' : str(uri.useEstimatedMetadata()),
'checkPrimaryKeyUnicity' : '',
'srid' : uri.srid(),
'type': uri.wkbType(),
'schema': uri.schema(),
'table' : uri.table(),
'geocol' : uri.geometryColumn(),
'sql' : uri.sql(),
'dbType': dbType
}
return connectionParams
示例4: ogrConnectionStringAndFormatFromLayer
# 需要导入模块: from qgis.core import QgsDataSourceUri [as 别名]
# 或者: from qgis.core.QgsDataSourceUri import table [as 别名]
def ogrConnectionStringAndFormatFromLayer(layer):
provider = layer.dataProvider().name()
if provider == 'spatialite':
# dbname='/geodata/osm_ch.sqlite' table="places" (Geometry) sql=
regex = re.compile("dbname='(.+)'")
r = regex.search(str(layer.source()))
ogrstr = r.groups()[0]
format = 'SQLite'
elif provider == 'postgres':
# dbname='ktryjh_iuuqef' host=spacialdb.com port=9999
# user='ktryjh_iuuqef' password='xyqwer' sslmode=disable
# key='gid' estimatedmetadata=true srid=4326 type=MULTIPOLYGON
# table="t4" (geom) sql=
dsUri = QgsDataSourceUri(layer.dataProvider().dataSourceUri())
conninfo = dsUri.connectionInfo()
conn = None
ok = False
while not conn:
try:
conn = psycopg2.connect(dsUri.connectionInfo())
except psycopg2.OperationalError:
(ok, user, passwd) = QgsCredentials.instance().get(conninfo, dsUri.username(), dsUri.password())
if not ok:
break
dsUri.setUsername(user)
dsUri.setPassword(passwd)
if not conn:
raise RuntimeError('Could not connect to PostgreSQL database - check connection info')
if ok:
QgsCredentials.instance().put(conninfo, user, passwd)
ogrstr = "PG:%s" % dsUri.connectionInfo()
format = 'PostgreSQL'
elif provider == 'mssql':
#'dbname=\'db_name\' host=myHost estimatedmetadata=true
# srid=27700 type=MultiPolygon table="dbo"."my_table"
# #(Shape) sql='
dsUri = layer.dataProvider().uri()
ogrstr = 'MSSQL:'
ogrstr += 'database={0};'.format(dsUri.database())
ogrstr += 'server={0};'.format(dsUri.host())
if dsUri.username() != "":
ogrstr += 'uid={0};'.format(dsUri.username())
else:
ogrstr += 'trusted_connection=yes;'
if dsUri.password() != '':
ogrstr += 'pwd={0};'.format(dsUri.password())
ogrstr += 'tables={0}'.format(dsUri.table())
format = 'MSSQL'
elif provider == "oracle":
# OCI:user/[email protected]:port/service:table
dsUri = QgsDataSourceUri(layer.dataProvider().dataSourceUri())
ogrstr = "OCI:"
if dsUri.username() != "":
ogrstr += dsUri.username()
if dsUri.password() != "":
ogrstr += "/" + dsUri.password()
delim = "@"
if dsUri.host() != "":
ogrstr += delim + dsUri.host()
delim = ""
if dsUri.port() != "" and dsUri.port() != '1521':
ogrstr += ":" + dsUri.port()
ogrstr += "/"
if dsUri.database() != "":
ogrstr += dsUri.database()
elif dsUri.database() != "":
ogrstr += delim + dsUri.database()
if ogrstr == "OCI:":
raise RuntimeError('Invalid oracle data source - check connection info')
ogrstr += ":"
if dsUri.schema() != "":
ogrstr += dsUri.schema() + "."
ogrstr += dsUri.table()
format = 'OCI'
else:
ogrstr = str(layer.source()).split("|")[0]
path, ext = os.path.splitext(ogrstr)
format = QgsVectorFileWriter.driverForExtension(ext)
return ogrstr, '"' + format + '"'
示例5: ogrConnectionStringAndFormat
# 需要导入模块: from qgis.core import QgsDataSourceUri [as 别名]
# 或者: from qgis.core.QgsDataSourceUri import table [as 别名]
def ogrConnectionStringAndFormat(uri, context):
"""Generates OGR connection string and format string from layer source
Returned values are a tuple of the connection string and format string
"""
ogrstr = None
format = None
layer = QgsProcessingUtils.mapLayerFromString(uri, context, False)
if layer is None:
path, ext = os.path.splitext(uri)
format = QgsVectorFileWriter.driverForExtension(ext)
return '"' + uri + '"', '"' + format + '"'
provider = layer.dataProvider().name()
if provider == 'spatialite':
# dbname='/geodata/osm_ch.sqlite' table="places" (Geometry) sql=
regex = re.compile("dbname='(.+)'")
r = regex.search(str(layer.source()))
ogrstr = r.groups()[0]
format = 'SQLite'
elif provider == 'postgres':
# dbname='ktryjh_iuuqef' host=spacialdb.com port=9999
# user='ktryjh_iuuqef' password='xyqwer' sslmode=disable
# key='gid' estimatedmetadata=true srid=4326 type=MULTIPOLYGON
# table="t4" (geom) sql=
dsUri = QgsDataSourceUri(layer.dataProvider().dataSourceUri())
conninfo = dsUri.connectionInfo()
conn = None
ok = False
while not conn:
try:
conn = psycopg2.connect(dsUri.connectionInfo())
except psycopg2.OperationalError:
(ok, user, passwd) = QgsCredentials.instance().get(conninfo, dsUri.username(), dsUri.password())
if not ok:
break
dsUri.setUsername(user)
dsUri.setPassword(passwd)
if not conn:
raise RuntimeError('Could not connect to PostgreSQL database - check connection info')
if ok:
QgsCredentials.instance().put(conninfo, user, passwd)
ogrstr = "PG:%s" % dsUri.connectionInfo()
format = 'PostgreSQL'
elif provider == "oracle":
# OCI:user/[email protected]:port/service:table
dsUri = QgsDataSourceUri(layer.dataProvider().dataSourceUri())
ogrstr = "OCI:"
if dsUri.username() != "":
ogrstr += dsUri.username()
if dsUri.password() != "":
ogrstr += "/" + dsUri.password()
delim = "@"
if dsUri.host() != "":
ogrstr += delim + dsUri.host()
delim = ""
if dsUri.port() != "" and dsUri.port() != '1521':
ogrstr += ":" + dsUri.port()
ogrstr += "/"
if dsUri.database() != "":
ogrstr += dsUri.database()
elif dsUri.database() != "":
ogrstr += delim + dsUri.database()
if ogrstr == "OCI:":
raise RuntimeError('Invalid oracle data source - check connection info')
ogrstr += ":"
if dsUri.schema() != "":
ogrstr += dsUri.schema() + "."
ogrstr += dsUri.table()
format = 'OCI'
else:
ogrstr = str(layer.source()).split("|")[0]
path, ext = os.path.splitext(ogrstr)
format = QgsVectorFileWriter.driverForExtension(ext)
return '"' + ogrstr + '"', '"' + format + '"'
示例6: __init__
# 需要导入模块: from qgis.core import QgsDataSourceUri [as 别名]
# 或者: from qgis.core.QgsDataSourceUri import table [as 别名]
def __init__(self, iface, layer, parent=None):
QWidget.__init__(self, parent)
self.iface = iface
self.layer = layer
uri = QgsDataSourceUri(layer.source())
dbplugin = None
db = None
if layer.dataProvider().name() == 'postgres':
dbplugin = createDbPlugin('postgis', 'postgres')
elif layer.dataProvider().name() == 'spatialite':
dbplugin = createDbPlugin('spatialite', 'spatialite')
elif layer.dataProvider().name() == 'oracle':
dbplugin = createDbPlugin('oracle', 'oracle')
elif layer.dataProvider().name() == 'virtual':
dbplugin = createDbPlugin('vlayers', 'virtual')
elif layer.dataProvider().name() == 'ogr':
dbplugin = createDbPlugin('gpkg', 'gpkg')
if dbplugin:
dbplugin.connectToUri(uri)
db = dbplugin.db
self.dbplugin = dbplugin
self.db = db
self.filter = ""
self.allowMultiColumnPk = isinstance(db, PGDatabase) # at the moment only PostgreSQL allows a primary key to span multiple columns, spatialite doesn't
self.aliasSubQuery = isinstance(db, PGDatabase) # only PostgreSQL requires subqueries to be aliases
self.setupUi(self)
self.setWindowTitle(
u"%s - %s [%s]" % (self.windowTitle(), db.connection().connectionName(), db.connection().typeNameString()))
self.defaultLayerName = 'QueryLayer'
if self.allowMultiColumnPk:
self.uniqueColumnCheck.setText(self.tr("Column(s) with unique values"))
else:
self.uniqueColumnCheck.setText(self.tr("Column with unique values"))
self.editSql.setFocus()
self.editSql.setVerticalScrollBarPolicy(Qt.ScrollBarAsNeeded)
self.editSql.setMarginVisible(True)
self.initCompleter()
# allow copying results
copyAction = QAction("copy", self)
self.viewResult.addAction(copyAction)
copyAction.setShortcuts(QKeySequence.Copy)
copyAction.triggered.connect(self.copySelectedResults)
self.btnExecute.clicked.connect(self.executeSql)
self.btnSetFilter.clicked.connect(self.setFilter)
self.btnClear.clicked.connect(self.clearSql)
self.presetStore.clicked.connect(self.storePreset)
self.presetDelete.clicked.connect(self.deletePreset)
self.presetCombo.activated[str].connect(self.loadPreset)
self.presetCombo.activated[str].connect(self.presetName.setText)
self.updatePresetsCombobox()
self.geomCombo.setEditable(True)
self.geomCombo.lineEdit().setReadOnly(True)
self.uniqueCombo.setEditable(True)
self.uniqueCombo.lineEdit().setReadOnly(True)
self.uniqueModel = QStandardItemModel(self.uniqueCombo)
self.uniqueCombo.setModel(self.uniqueModel)
if self.allowMultiColumnPk:
self.uniqueCombo.setItemDelegate(QStyledItemDelegate())
self.uniqueModel.itemChanged.connect(self.uniqueChanged) # react to the (un)checking of an item
self.uniqueCombo.lineEdit().textChanged.connect(self.uniqueTextChanged) # there are other events that change the displayed text and some of them can not be caught directly
self.layerTypeWidget.hide() # show if load as raster is supported
#self.loadLayerBtn.clicked.connect(self.loadSqlLayer)
self.updateLayerBtn.clicked.connect(self.updateSqlLayer)
self.getColumnsBtn.clicked.connect(self.fillColumnCombos)
self.queryBuilderFirst = True
self.queryBuilderBtn.setIcon(QIcon(":/db_manager/icons/sql.gif"))
self.queryBuilderBtn.clicked.connect(self.displayQueryBuilder)
self.presetName.textChanged.connect(self.nameChanged)
# Update from layer
# Fisrtly the SQL from QgsDataSourceUri table
sql = uri.table()
if uri.keyColumn() == '_uid_':
match = re.search('^\(SELECT .+ AS _uid_,\* FROM \((.*)\) AS _subq_.+_\s*\)$', sql, re.S)
if match:
sql = match.group(1)
else:
match = re.search('^\((SELECT .+ FROM .+)\)$', sql, re.S)
if match:
sql = match.group(1)
self.editSql.setText(sql)
self.executeSql()
# Then the columns
self.geomCombo.setCurrentIndex(self.geomCombo.findText(uri.geometryColumn(), Qt.MatchExactly))
#.........这里部分代码省略.........
示例7: onLayerWasAdded
# 需要导入模块: from qgis.core import QgsDataSourceUri [as 别名]
# 或者: from qgis.core.QgsDataSourceUri import table [as 别名]
def onLayerWasAdded(self, aMapLayer):
if hasattr(aMapLayer, 'dataProvider') and aMapLayer.dataProvider().name() in ['postgres', 'spatialite', 'oracle']:
uri = QgsDataSourceUri(aMapLayer.source())
if re.search('^\(SELECT .+ FROM .+\)$', uri.table(), re.S):
self.addCustomActionForLayer(self.layerAction, aMapLayer)
示例8: ogrConnectionString
# 需要导入模块: from qgis.core import QgsDataSourceUri [as 别名]
# 或者: from qgis.core.QgsDataSourceUri import table [as 别名]
def ogrConnectionString(uri):
"""Generates OGR connection sting from layer source
"""
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(str(layer.source()))
ogrstr = r.groups()[0]
elif provider == "postgres":
# dbname='ktryjh_iuuqef' host=spacialdb.com port=9999
# user='ktryjh_iuuqef' password='xyqwer' sslmode=disable
# key='gid' estimatedmetadata=true srid=4326 type=MULTIPOLYGON
# table="t4" (geom) sql=
dsUri = QgsDataSourceUri(layer.dataProvider().dataSourceUri())
conninfo = dsUri.connectionInfo()
conn = None
ok = False
while not conn:
try:
conn = psycopg2.connect(dsUri.connectionInfo())
except psycopg2.OperationalError:
(ok, user, passwd) = QgsCredentials.instance().get(conninfo, dsUri.username(), dsUri.password())
if not ok:
break
dsUri.setUsername(user)
dsUri.setPassword(passwd)
if not conn:
raise RuntimeError("Could not connect to PostgreSQL database - check connection info")
if ok:
QgsCredentials.instance().put(conninfo, user, passwd)
ogrstr = "PG:%s" % dsUri.connectionInfo()
elif provider == "oracle":
# OCI:user/[email protected]:port/service:table
dsUri = QgsDataSourceUri(layer.dataProvider().dataSourceUri())
ogrstr = "OCI:"
if dsUri.username() != "":
ogrstr += dsUri.username()
if dsUri.password() != "":
ogrstr += "/" + dsUri.password()
delim = "@"
if dsUri.host() != "":
ogrstr += delim + dsUri.host()
delim = ""
if dsUri.port() != "" and dsUri.port() != "1521":
ogrstr += ":" + dsUri.port()
ogrstr += "/"
if dsUri.database() != "":
ogrstr += dsUri.database()
elif dsUri.database() != "":
ogrstr += delim + dsUri.database()
if ogrstr == "OCI:":
raise RuntimeError("Invalid oracle data source - check connection info")
ogrstr += ":"
if dsUri.schema() != "":
ogrstr += dsUri.schema() + "."
ogrstr += dsUri.table()
else:
ogrstr = str(layer.source()).split("|")[0]
return '"' + ogrstr + '"'
示例9: onLayerWasAdded
# 需要导入模块: from qgis.core import QgsDataSourceUri [as 别名]
# 或者: from qgis.core.QgsDataSourceUri import table [as 别名]
def onLayerWasAdded(self, aMapLayer):
if hasattr(aMapLayer, 'dataProvider') and aMapLayer.dataProvider().name() in ['postgres', 'spatialite', 'oracle']:
uri = QgsDataSourceUri(aMapLayer.source())
table = uri.table()
if table.startswith('(') and table.endswith(')'):
self.addCustomActionForLayer(self.layerAction, aMapLayer)
示例10: onLayerWasAdded
# 需要导入模块: from qgis.core import QgsDataSourceUri [as 别名]
# 或者: from qgis.core.QgsDataSourceUri import table [as 别名]
def onLayerWasAdded(self, aMapLayer):
if aMapLayer.dataProvider().name() in ["postgres", "spatialite", "oracle"]:
uri = QgsDataSourceUri(aMapLayer.source())
if re.search("^\(SELECT .+ FROM .+\)$", uri.table(), re.S):
self.iface.legendInterface().addLegendLayerActionForLayer(self.layerAction, aMapLayer)
示例11: load_layer
# 需要导入模块: from qgis.core import QgsDataSourceUri [as 别名]
# 或者: from qgis.core.QgsDataSourceUri import table [as 别名]
def load_layer(full_layer_uri_string, name=None, provider=None):
"""Helper to load and return a single QGIS layer based on our layer URI.
:param provider: The provider name to use if known to open the layer.
Default to None, we will try to guess it, but it's much better if you
can provide it.
:type provider:
:param name: The name of the layer. If not provided, it will be computed
based on the URI.
:type name: basestring
:param full_layer_uri_string: Layer URI, with provider type.
:type full_layer_uri_string: str
:returns: tuple containing layer and its layer_purpose.
:rtype: (QgsMapLayer, str)
"""
if provider:
# Cool !
layer_path = full_layer_uri_string
else:
# Let's check if the driver is included in the path
layer_path, provider = decode_full_layer_uri(full_layer_uri_string)
if not provider:
# Let's try to check if it's file based and look for a extension
if '|' in layer_path:
clean_uri = layer_path.split('|')[0]
else:
clean_uri = layer_path
is_file_based = os.path.exists(clean_uri)
if is_file_based:
# Extract basename and absolute path
file_name = os.path.split(layer_path)[
-1] # If path was absolute
extension = os.path.splitext(file_name)[1]
if extension in OGR_EXTENSIONS:
provider = 'ogr'
elif extension in GDAL_EXTENSIONS:
provider = 'gdal'
else:
provider = None
if not provider:
layer = load_layer_without_provider(layer_path)
else:
layer = load_layer_with_provider(layer_path, provider)
if not layer or not layer.isValid():
message = 'Layer "%s" is not valid' % layer_path
LOGGER.debug(message)
raise InvalidLayerError(message)
# Define the name
if not name:
source = layer.source()
if '|' in source:
clean_uri = source.split('|')[0]
else:
clean_uri = source
is_file_based = os.path.exists(clean_uri)
if is_file_based:
# Extract basename and absolute path
file_name = os.path.split(layer_path)[-1] # If path was absolute
name = os.path.splitext(file_name)[0]
else:
# Might be a DB, take the DB name
source = QgsDataSourceUri(source)
name = source.table()
if not name:
name = 'default'
if qgis_version() >= 21800:
layer.setName(name)
else:
layer.setLayerName(name)
# update the layer keywords
monkey_patch_keywords(layer)
layer_purpose = layer.keywords.get('layer_purpose')
return layer, layer_purpose
示例12: _onPointClicked
# 需要导入模块: from qgis.core import QgsDataSourceUri [as 别名]
# 或者: from qgis.core.QgsDataSourceUri import table [as 别名]
def _onPointClicked(self, ps_layer, point):
# get the id of the point feature under the mouse click
from .MapTools import FeatureFinder
fid = FeatureFinder.findAtPoint(ps_layer, point, canvas=self.iface.mapCanvas(), onlyTheClosestOne=True, onlyIds=True)
if fid is None:
return
# get the attribute map of the selected feature
feat = QgsFeature()
feats = ps_layer.getFeatures( QgsFeatureRequest(fid) )
feats.nextFeature(feat)
attrs = feat.attributes()
x, y = [], [] # lists containg x,y values
infoFields = {} # hold the index->name of the fields containing info to be displayed
ps_source = ps_layer.source()
ps_fields = ps_layer.dataProvider().fields()
providerType = ps_layer.providerType()
uri = ps_source
subset = ""
if providerType == 'ogr' and ps_source.lower().endswith( ".shp" ):
# Shapefile
for idx, fld in enumerate(ps_fields):
if QRegExp( "D\\d{8}", Qt.CaseInsensitive ).indexIn( fld.name() ) < 0:
# info fields are all except those containing dates
infoFields[ idx ] = fld
else:
x.append( QDate.fromString( fld.name()[1:], "yyyyMMdd" ).toPyDate() )
y.append( float(attrs[ idx ]) )
elif providerType == 'ogr' and (ps_source.upper().startswith("OCI:") or ps_source.lower().endswith(".vrt")): # Oracle Spatial
# fields containing values
dateField = "data_misura"
valueField = "spost_rel_mm"
infoFields = dict(enumerate(ps_fields))
# search for the id_dataset and code_target fields needed to join
# PS and TS tables
idDataset = codeTarget = None
for idx, fld in enumerate(ps_fields):
if fld.name().lower() == "id_dataset":
idDataset = attrs[ idx ]
if fld.name().lower() == "code_target":
codeTarget = attrs[ idx ]
if idDataset is None or codeTarget is None:
QgsMessageLog.logMessage( "idDataset is %s, codeTarget is %s. Exiting" % (idDataset, codeTarget), "PSTimeSeriesViewer" )
return
subset = "id_dataset='%s' AND code_target='%s'" % (idDataset, codeTarget)
# create the uri
if ps_source.upper().startswith( "OCI:" ):
default_tbl_name = "RISKNAT.RNAT_TARGET_SSTO"
elif ps_source.lower().endswith(".vrt"):
default_tbl_name = "rnat_target_sso.vrt"
else:
default_tbl_name = ""
if not self._askTStablename( ps_layer, default_tbl_name ):
return
if ps_source.upper().startswith( "OCI:" ):
# uri is like OCI:userid/[email protected]:table
pos = uri.indexOf(':', 4)
if pos >= 0:
uri = uri[0:pos]
uri = "%s:%s" % (uri, self.ts_tablename)
else:
# it's a VRT file
uri = "%s/%s" % (QFileInfo(ps_source).path(), self.ts_tablename)
uri = QDir.toNativeSeparators( uri )
# load the layer containing time series
ts_layer = self._createTSlayer( uri, providerType, subset )
if ts_layer is None:
return
# get time series X and Y values
try:
x, y = self._getXYvalues( ts_layer, dateField, valueField )
finally:
ts_layer.deleteLater()
del ts_layer
elif providerType in ['postgres', 'spatialite']:# either PostGIS or SpatiaLite
# fields containing values
dateField = "dataripresa"
valueField = "valore"
infoFields = dict(enumerate(ps_fields))
# search for the id_dataset and code_target fields needed to join
# PS and TS tables
code = None
for idx, fld in enumerate( ps_fields ):
if fld.name().lower() == "code":
code = attrs[ idx ]
#.........这里部分代码省略.........