def __init__(self, fileName, encoding, fields, geometryType, crs, options=None): self.fileName = fileName self.isMemory = False self.memLayer = None self.writer = None if encoding is None: settings = QSettings() encoding = settings.value('/Processing/encoding', 'System', type=str) if self.fileName.startswith(self.MEMORY_LAYER_PREFIX): self.isMemory = True uri = GEOM_TYPE_MAP[geometryType] + "?uuid=" + unicode( uuid.uuid4()) if crs.isValid(): uri += '&crs=' + crs.authid() fieldsdesc = [] for f in fields: qgsfield = _toQgsField(f) fieldsdesc.append( 'field=%s:%s' % (qgsfield.name(), TYPE_MAP_MEMORY_LAYER.get(qgsfield.type(), "string"))) if fieldsdesc: uri += '&' + '&'.join(fieldsdesc) self.memLayer = QgsVectorLayer(uri, self.fileName, 'memory') self.writer = self.memLayer.dataProvider() else: formats = QgsVectorFileWriter.supportedFiltersAndFormats() OGRCodes = {} for (key, value) in formats.items(): extension = unicode(key) extension = extension[extension.find('*.') + 2:] extension = extension[:extension.find(' ')] OGRCodes[extension] = value extension = self.fileName[self.fileName.rfind('.') + 1:] if extension not in OGRCodes: extension = 'shp' self.filename = self.filename + 'shp' qgsfields = QgsFields() for field in fields: qgsfields.append(_toQgsField(field)) self.writer = QgsVectorFileWriter(self.fileName, encoding, qgsfields, geometryType, crs, OGRCodes[extension])
def testSupportedFiltersAndFormat(self): # test with formats in recommended order formats = QgsVectorFileWriter.supportedFiltersAndFormats(QgsVectorFileWriter.SortRecommended) self.assertEqual(formats[0].filterString, 'GeoPackage (*.gpkg *.GPKG)') self.assertEqual(formats[0].driverName, 'GPKG') self.assertEqual(formats[1].filterString, 'ESRI Shapefile (*.shp *.SHP)') self.assertEqual(formats[1].driverName, 'ESRI Shapefile') self.assertTrue('ODS' in [f.driverName for f in formats]) # alphabetical sorting formats2 = QgsVectorFileWriter.supportedFiltersAndFormats(QgsVectorFileWriter.VectorFormatOptions()) self.assertTrue(formats2[0].driverName < formats2[1].driverName) self.assertCountEqual([f.driverName for f in formats], [f.driverName for f in formats2]) self.assertNotEqual(formats2[0].driverName, 'GeoPackage') # skip non-spatial formats = QgsVectorFileWriter.supportedFiltersAndFormats(QgsVectorFileWriter.SkipNonSpatialFormats) self.assertFalse('ODS' in [f.driverName for f in formats])
def testSupportedFiltersAndFormat(self): # test with formats in recommended order formats = QgsVectorFileWriter.supportedFiltersAndFormats(QgsVectorFileWriter.SortRecommended) self.assertEqual(formats[0].filterString, 'GeoPackage (*.gpkg *.GPKG)') self.assertEqual(formats[0].driverName, 'GPKG') self.assertEqual(formats[1].filterString, 'ESRI Shapefile (*.shp *.SHP)') self.assertEqual(formats[1].driverName, 'ESRI Shapefile') self.assertTrue('ODS' in [f.driverName for f in formats]) # alphabetical sorting formats2 = QgsVectorFileWriter.supportedFiltersAndFormats(QgsVectorFileWriter.VectorFormatOptions()) self.assertTrue(formats2[0].driverName < formats2[1].driverName) self.assertCountEqual([f.driverName for f in formats], [f.driverName for f in formats2]) self.assertNotEqual(formats2[0].driverName, 'GeoPackage') # skip non-spatial formats = QgsVectorFileWriter.supportedFiltersAndFormats(QgsVectorFileWriter.SkipNonSpatialFormats) self.assertFalse('ODS' in [f.driverName for f in formats])
def newVectorLayer(filename, fields, geometryType, crs, encoding="utf-8"): ''' Creates a new vector layer :param filename: The filename to store the file. The extensions determines the type of file. If extension is not among the supported ones, a shapefile will be created and the file will get an added '.shp' to its path. If the filename is None, a memory layer will be created :param fields: the fields to add to the layer. Accepts a QgsFields object or a list of tuples (field_name, field_type) Accepted field types are basic Python types str, float, int and bool :param geometryType: The type of geometry of the layer to create. :param crs: The crs of the layer to create. Accepts a QgsCoordinateSystem object or a string with the CRS authId. :param encoding: The layer encoding ''' if isinstance(crs, basestring): crs = QgsCoordinateReferenceSystem(crs) if filename is None: uri = GEOM_TYPE_MAP[geometryType] if crs.isValid(): uri += '?crs=' + crs.authid() + '&' fieldsdesc = ['field=' + f for f in fields] fieldsstring = '&'.join(fieldsdesc) uri += fieldsstring layer = QgsVectorLayer(uri, "mem_layer", 'memory') else: formats = QgsVectorFileWriter.supportedFiltersAndFormats() OGRCodes = {} for (key, value) in formats.items(): extension = unicode(key) extension = extension[extension.find('*.') + 2:] extension = extension[:extension.find(' ')] OGRCodes[extension] = value extension = os.path.splitext(filename)[1][1:] if extension not in OGRCodes: extension = 'shp' filename = filename + '.shp' if isinstance(fields, QgsFields): qgsfields = fields else: qgsfields = QgsFields() for field in fields: qgsfields.append(_toQgsField(field)) QgsVectorFileWriter(filename, encoding, qgsfields, geometryType, crs, OGRCodes[extension]) layer = QgsVectorLayer(filename, os.path.basename(filename), 'ogr') return layer
def getSupportedOutputVectorLayerExtensions(): formats = QgsVectorFileWriter.supportedFiltersAndFormats() exts = ['shp'] # shp is the default, should be the first for extension in list(formats.keys()): extension = str(extension) extension = extension[extension.find('*.') + 2:] extension = extension[:extension.find(' ')] if extension.lower() != 'shp': exts.append(extension) return exts
def getVectorDriverFromFileName(filename): ext = os.path.splitext(filename)[1] if ext == "": return "ESRI Shapefile" formats = QgsVectorFileWriter.supportedFiltersAndFormats() for k, v in list(formats.items()): if ext in k: return v return "ESRI Shapefile"
def getSupportedOutputVectorLayerExtensions(): formats = QgsVectorFileWriter.supportedFiltersAndFormats() exts = ['shp'] # shp is the default, should be the first for extension in formats.keys(): extension = unicode(extension) extension = extension[extension.find('*.') + 2:] extension = extension[:extension.find(' ')] if extension.lower() != 'shp': exts.append(extension) return exts
def getVectorDriverFromFileName(filename): ext = os.path.splitext(filename)[1] if ext == '': return 'ESRI Shapefile' formats = QgsVectorFileWriter.supportedFiltersAndFormats() for k, v in list(formats.items()): if ext in k: return v return 'ESRI Shapefile'
def getVectorDriverFromFileName(filename): ext = os.path.splitext(filename)[1] if ext == '': return 'ESRI Shapefile' formats = QgsVectorFileWriter.supportedFiltersAndFormats() for format in formats: if ext in format.filterString: return format.driverName return 'ESRI Shapefile'
def getVectorDriverFromFileName(filename): ext = os.path.splitext(filename)[1] if ext == '': return 'ESRI Shapefile' formats = QgsVectorFileWriter.supportedFiltersAndFormats() for format in formats: if ext in format.filterString: return format.driverName return 'ESRI Shapefile'
def getSupportedOutputVectorLayerExtensions(): formats = QgsVectorFileWriter.supportedFiltersAndFormats() exts = [] for extension in list(formats.keys()): extension = str(extension) extension = extension[extension.find('*.') + 2:] extension = extension[:extension.find(' ')] if extension.lower() != 'shp': exts.append(extension) exts.sort() exts.insert(0, 'shp') # shp is the default, should be the first return exts
def __init__(self, fileName, encoding, fields, geometryType, crs, options=None): self.fileName = fileName self.isMemory = False self.memLayer = None self.writer = None if encoding is None: settings = QSettings() encoding = settings.value('/Processing/encoding', 'System', type=str) if self.fileName.startswith(self.MEMORY_LAYER_PREFIX): self.isMemory = True uri = GEOM_TYPE_MAP[geometryType] + "?uuid=" + unicode(uuid.uuid4()) if crs.isValid(): uri += '&crs=' + crs.authid() fieldsdesc = [] for f in fields: qgsfield = _toQgsField(f) fieldsdesc.append('field=%s:%s' %(qgsfield.name(), TYPE_MAP_MEMORY_LAYER.get(qgsfield.type(), "string"))) if fieldsdesc: uri += '&' + '&'.join(fieldsdesc) self.memLayer = QgsVectorLayer(uri, self.fileName, 'memory') self.writer = self.memLayer.dataProvider() else: formats = QgsVectorFileWriter.supportedFiltersAndFormats() OGRCodes = {} for (key, value) in formats.items(): extension = unicode(key) extension = extension[extension.find('*.') + 2:] extension = extension[:extension.find(' ')] OGRCodes[extension] = value extension = self.fileName[self.fileName.rfind('.') + 1:] if extension not in OGRCodes: extension = 'shp' self.filename = self.filename + 'shp' qgsfields = QgsFields() for field in fields: qgsfields.append(_toQgsField(field)) self.writer = QgsVectorFileWriter( self.fileName, encoding, qgsfields, geometryType, crs, OGRCodes[extension])
def exportVectorLayer(self, layer, destinationFile, asLayer=False): options = QgsVectorFileWriter.SaveVectorOptions() options.driverName = self.settings['vectorFormat'] if 'vectorFormat' in self.settings else 'GPKG' options.fileEncoding = 'utf-8' if asLayer: options.actionOnExistingFile = QgsVectorFileWriter.CreateOrOverwriteLayer options.layerName = self.safeName(layer.name()) else: options.actionOnExistingFile = QgsVectorFileWriter.CreateOrOverwriteFile if os.path.splitext(destinationFile)[1] == '': formats = QgsVectorFileWriter.supportedFiltersAndFormats() for f in formats: if f.driverName == options.driverName and len(f.globs) > 0: destinationFile = '{}.{}'.format(destinationFile, f.globs[0][2:]) success = True error, msg = QgsVectorFileWriter.writeAsVectorFormat(layer, destinationFile, options) if error != QgsVectorFileWriter.NoError: QgsMessageLog.logMessage(self.tr('Failed to export layer "{layer}": {message}.'.format(layer=layer.name(), message=msg)), 'QConsolidate', Qgis.Warning) success = False return success, destinationFile
def supportedFiltersAndFormats(_, _2): """Returns a dictionary of supported vector formats with format filter string as key and OGR format key as value.""" return NetworkAPIResult(QgsVectorFileWriter.supportedFiltersAndFormats())
def __init__(self, destination, encoding, fields, geometryType, crs, options=None): self.destination = destination self.isNotFileBased = False self.layer = None self.writer = None if encoding is None: settings = QSettings() encoding = settings.value('/Processing/encoding', 'System', type=str) if self.destination.startswith(self.MEMORY_LAYER_PREFIX): self.isNotFileBased = True uri = GEOM_TYPE_MAP[geometryType] + "?uuid=" + unicode(uuid.uuid4()) if crs.isValid(): uri += '&crs=' + crs.authid() fieldsdesc = [] for f in fields: qgsfield = _toQgsField(f) fieldsdesc.append('field=%s:%s' % (qgsfield.name(), TYPE_MAP_MEMORY_LAYER.get(qgsfield.type(), "string"))) if fieldsdesc: uri += '&' + '&'.join(fieldsdesc) self.layer = QgsVectorLayer(uri, self.destination, 'memory') self.writer = self.layer.dataProvider() elif self.destination.startswith(self.POSTGIS_LAYER_PREFIX): self.isNotFileBased = True uri = QgsDataSourceURI(self.destination[len(self.POSTGIS_LAYER_PREFIX):]) connInfo = uri.connectionInfo() (success, user, passwd) = QgsCredentials.instance().get(connInfo, None, None) if success: QgsCredentials.instance().put(connInfo, user, passwd) else: raise GeoAlgorithmExecutionException("Couldn't connect to database") print uri.uri() try: db = postgis_utils.GeoDB(host=uri.host(), port=int(uri.port()), dbname=uri.database(), user=user, passwd=passwd) except postgis_utils.DbError as e: raise GeoAlgorithmExecutionException( "Couldn't connect to database:\n%s" % e.message) def _runSQL(sql): try: db._exec_sql_and_commit(unicode(sql)) except postgis_utils.DbError as e: raise GeoAlgorithmExecutionException( 'Error creating output PostGIS table:\n%s' % e.message) fields = [_toQgsField(f) for f in fields] fieldsdesc = ",".join('%s %s' % (f.name(), TYPE_MAP_POSTGIS_LAYER.get(f.type(), "VARCHAR")) for f in fields) _runSQL("CREATE TABLE %s.%s (%s)" % (uri.schema(), uri.table().lower(), fieldsdesc)) if geometryType != QGis.WKBNoGeometry: _runSQL("SELECT AddGeometryColumn('{schema}', '{table}', 'the_geom', {srid}, '{typmod}', 2)".format( table=uri.table().lower(), schema=uri.schema(), srid=crs.authid().split(":")[-1], typmod=GEOM_TYPE_MAP[geometryType].upper())) self.layer = QgsVectorLayer(uri.uri(), uri.table(), "postgres") self.writer = self.layer.dataProvider() elif self.destination.startswith(self.SPATIALITE_LAYER_PREFIX): self.isNotFileBased = True uri = QgsDataSourceURI(self.destination[len(self.SPATIALITE_LAYER_PREFIX):]) print uri.uri() try: db = spatialite_utils.GeoDB(uri=uri) except spatialite_utils.DbError as e: raise GeoAlgorithmExecutionException( "Couldn't connect to database:\n%s" % e.message) def _runSQL(sql): try: db._exec_sql_and_commit(unicode(sql)) except spatialite_utils.DbError as e: raise GeoAlgorithmExecutionException( 'Error creating output Spatialite table:\n%s' % unicode(e)) fields = [_toQgsField(f) for f in fields] fieldsdesc = ",".join('%s %s' % (f.name(), TYPE_MAP_SPATIALITE_LAYER.get(f.type(), "VARCHAR")) for f in fields) _runSQL("DROP TABLE IF EXISTS %s" % uri.table().lower()) _runSQL("CREATE TABLE %s (%s)" % (uri.table().lower(), fieldsdesc)) if geometryType != QGis.WKBNoGeometry: _runSQL("SELECT AddGeometryColumn('{table}', 'the_geom', {srid}, '{typmod}', 2)".format( table=uri.table().lower(), srid=crs.authid().split(":")[-1], typmod=GEOM_TYPE_MAP[geometryType].upper())) self.layer = QgsVectorLayer(uri.uri(), uri.table(), "spatialite") self.writer = self.layer.dataProvider() else: formats = QgsVectorFileWriter.supportedFiltersAndFormats() OGRCodes = {} for (key, value) in formats.items(): extension = unicode(key) extension = extension[extension.find('*.') + 2:] extension = extension[:extension.find(' ')] OGRCodes[extension] = value OGRCodes['dbf'] = "DBF file" extension = self.destination[self.destination.rfind('.') + 1:] if extension not in OGRCodes: extension = 'shp' self.destination = self.destination + '.shp' if geometryType == QGis.WKBNoGeometry: if extension == 'shp': extension = 'dbf' self.destination = self.destination[:self.destination.rfind('.')] + '.dbf' if extension not in self.nogeometry_extensions: raise GeoAlgorithmExecutionException( "Unsupported format for tables with no geometry") qgsfields = QgsFields() for field in fields: qgsfields.append(_toQgsField(field)) self.writer = QgsVectorFileWriter(self.destination, encoding, qgsfields, geometryType, crs, OGRCodes[extension])
def setup_actions(self): """ Connect menu, table and form actions to the proper slots """ # menu actions self.actionDeclustering.triggered.connect( lambda: self.stackedFormWidget.setCurrentIndex(0)) self.actionCompleteness.triggered.connect( lambda: self.stackedFormWidget.setCurrentIndex(1)) self.actionRecurrenceModel.triggered.connect( lambda: self.stackedFormWidget.setCurrentIndex(2)) self.actionMaximumMagnitude.triggered.connect( lambda: self.stackedFormWidget.setCurrentIndex(3)) self.actionSmoothedSeismicity.triggered.connect( lambda: self.stackedFormWidget.setCurrentIndex(4)) self.actionCatalogueAnalysis.triggered.connect( lambda: self.stackedFormWidget.setCurrentIndex(5)) self.actionEventsInspector.triggered.connect( lambda: self.stackedFormWidget.setCurrentIndex(6)) # menu import/export actions self.actionLoadCatalogue.triggered.connect(self.load_catalogue) self.actionSaveCatalogue.triggered.connect(self.save_catalogue) self.actionLoadSourceNRML.triggered.connect( lambda: self.load_fault_source( QtGui.QFileDialog.getOpenFileName( self, 'Open Source Model (NRML 4)', '.xml'))) filters_formats = QgsVectorFileWriter.supportedFiltersAndFormats() for flt, fmt in filters_formats.items(): action = QtGui.QAction(self) action.setText( QtGui.QApplication.translate( "HMTKWindow", fmt, None, QtGui.QApplication.UnicodeUTF8)) self.menuExport.addAction(action) action.triggered.connect(self.save_as(flt, fmt)) # Selection management self.actionDeleteUnselectedEvents.triggered.connect( self.remove_unselected_events) self.actionUndo.triggered.connect(self.undo) self.actionInvertSelection.triggered.connect( lambda: self.add_to_selection(0)) self.actionWithinPolygon.triggered.connect( lambda: self.add_to_selection(1)) self.actionWithinJoynerBooreSource.triggered.connect( lambda: self.add_to_selection(2)) self.actionWithinRuptureDistance.triggered.connect( lambda: self.add_to_selection(3)) self.actionWithinSquare.triggered.connect( lambda: self.add_to_selection(4)) self.actionWithinDistance.triggered.connect( lambda: self.add_to_selection(5)) self.actionTimeBetween.triggered.connect( lambda: self.add_to_selection(6)) self.actionFieldBetween.triggered.connect( lambda: self.add_to_selection(7)) self.actionSelectionEditor.triggered.connect( self.selection_editor.exec_) # Style actions self.actionCatalogueStyleByCluster.triggered.connect( lambda: self.catalogue_map.set_catalogue_style("cluster")) self.actionCatalogueStyleByDepthMagnitude.triggered.connect( lambda: self.catalogue_map.set_catalogue_style("depth-magnitude")) self.actionCatalogueStyleByCompleteness.triggered.connect( lambda: self.catalogue_map.set_catalogue_style("completeness")) self.actionLoadOSMBaseMap.triggered.connect( lambda: self.catalogue_map.set_osm())
def __init__(self, destination, encoding, fields, geometryType, crs, options=None): self.destination = destination self.isNotFileBased = False self.layer = None self.writer = None if encoding is None: settings = QSettings() encoding = settings.value('/Processing/encoding', 'System', type=str) if self.destination.startswith(self.MEMORY_LAYER_PREFIX): self.isNotFileBased = True uri = QgsWkbTypes.displayString(geometryType) + "?uuid=" + str( uuid.uuid4()) if crs.isValid(): uri += '&crs=' + crs.authid() fieldsdesc = [] for f in fields: qgsfield = _toQgsField(f) fieldsdesc.append( 'field=%s:%s' % (qgsfield.name(), TYPE_MAP_MEMORY_LAYER.get(qgsfield.type(), "string"))) if fieldsdesc: uri += '&' + '&'.join(fieldsdesc) self.layer = QgsVectorLayer(uri, self.destination, 'memory') self.writer = self.layer.dataProvider() elif self.destination.startswith(self.POSTGIS_LAYER_PREFIX): self.isNotFileBased = True uri = QgsDataSourceUri( self.destination[len(self.POSTGIS_LAYER_PREFIX):]) connInfo = uri.connectionInfo() (success, user, passwd) = QgsCredentials.instance().get(connInfo, None, None) if success: QgsCredentials.instance().put(connInfo, user, passwd) else: raise GeoAlgorithmExecutionException( "Couldn't connect to database") # fix_print_with_import print(uri.uri()) try: db = postgis.GeoDB(host=uri.host(), port=int(uri.port()), dbname=uri.database(), user=user, passwd=passwd) except postgis.DbError as e: raise GeoAlgorithmExecutionException( "Couldn't connect to database:\n%s" % e.message) def _runSQL(sql): try: db._exec_sql_and_commit(str(sql)) except postgis.DbError as e: raise GeoAlgorithmExecutionException( 'Error creating output PostGIS table:\n%s' % e.message) fields = [_toQgsField(f) for f in fields] fieldsdesc = ",".join( '%s %s' % (f.name(), TYPE_MAP_POSTGIS_LAYER.get(f.type(), "VARCHAR")) for f in fields) _runSQL("CREATE TABLE %s.%s (%s)" % (uri.schema(), uri.table().lower(), fieldsdesc)) if geometryType != QgsWkbTypes.NullGeometry: _runSQL( "SELECT AddGeometryColumn('{schema}', '{table}', 'the_geom', {srid}, '{typmod}', 2)" .format(table=uri.table().lower(), schema=uri.schema(), srid=crs.authid().split(":")[-1], typmod=QgsWkbTypes.displayString( geometryType).upper())) self.layer = QgsVectorLayer(uri.uri(), uri.table(), "postgres") self.writer = self.layer.dataProvider() elif self.destination.startswith(self.SPATIALITE_LAYER_PREFIX): self.isNotFileBased = True uri = QgsDataSourceUri( self.destination[len(self.SPATIALITE_LAYER_PREFIX):]) # fix_print_with_import print(uri.uri()) try: db = spatialite.GeoDB(uri=uri) except spatialite.DbError as e: raise GeoAlgorithmExecutionException( "Couldn't connect to database:\n%s" % e.message) def _runSQL(sql): try: db._exec_sql_and_commit(str(sql)) except spatialite.DbError as e: raise GeoAlgorithmExecutionException( 'Error creating output Spatialite table:\n%s' % str(e)) fields = [_toQgsField(f) for f in fields] fieldsdesc = ",".join( '%s %s' % (f.name(), TYPE_MAP_SPATIALITE_LAYER.get(f.type(), "VARCHAR")) for f in fields) _runSQL("DROP TABLE IF EXISTS %s" % uri.table().lower()) _runSQL("CREATE TABLE %s (%s)" % (uri.table().lower(), fieldsdesc)) if geometryType != QgsWkbTypes.NullGeometry: _runSQL( "SELECT AddGeometryColumn('{table}', 'the_geom', {srid}, '{typmod}', 2)" .format(table=uri.table().lower(), srid=crs.authid().split(":")[-1], typmod=QgsWkbTypes.displayString( geometryType).upper())) self.layer = QgsVectorLayer(uri.uri(), uri.table(), "spatialite") self.writer = self.layer.dataProvider() else: formats = QgsVectorFileWriter.supportedFiltersAndFormats() OGRCodes = {} for (key, value) in list(formats.items()): extension = str(key) extension = extension[extension.find('*.') + 2:] extension = extension[:extension.find(' ')] OGRCodes[extension] = value OGRCodes['dbf'] = "DBF file" extension = self.destination[self.destination.rfind('.') + 1:] if extension not in OGRCodes: extension = 'shp' self.destination = self.destination + '.shp' if geometryType == QgsWkbTypes.NoGeometry: if extension == 'shp': extension = 'dbf' self.destination = self.destination[:self.destination. rfind('.')] + '.dbf' if extension not in self.nogeometry_extensions: raise GeoAlgorithmExecutionException( "Unsupported format for tables with no geometry") qgsfields = QgsFields() for field in fields: qgsfields.append(_toQgsField(field)) # use default dataset/layer options dataset_options = QgsVectorFileWriter.defaultDatasetOptions( OGRCodes[extension]) layer_options = QgsVectorFileWriter.defaultLayerOptions( OGRCodes[extension]) self.writer = QgsVectorFileWriter(self.destination, encoding, qgsfields, geometryType, crs, OGRCodes[extension], dataset_options, layer_options)
def __init__(self, destination, encoding, fields, geometryType, crs, options=None): self.destination = destination self.isNotFileBased = False self.layer = None self.writer = None if encoding is None: settings = QSettings() encoding = settings.value("/Processing/encoding", "System", str) if self.destination.startswith(self.MEMORY_LAYER_PREFIX): self.isNotFileBased = True uri = QgsWkbTypes.displayString(geometryType) + "?uuid=" + str(uuid.uuid4()) if crs.isValid(): uri += "&crs=" + crs.authid() fieldsdesc = [] for f in fields: qgsfield = _toQgsField(f) fieldsdesc.append( "field=%s:%s" % (qgsfield.name(), TYPE_MAP_MEMORY_LAYER.get(qgsfield.type(), "string")) ) if fieldsdesc: uri += "&" + "&".join(fieldsdesc) self.layer = QgsVectorLayer(uri, self.destination, "memory") self.writer = self.layer.dataProvider() elif self.destination.startswith(self.POSTGIS_LAYER_PREFIX): self.isNotFileBased = True uri = QgsDataSourceUri(self.destination[len(self.POSTGIS_LAYER_PREFIX) :]) connInfo = uri.connectionInfo() (success, user, passwd) = QgsCredentials.instance().get(connInfo, None, None) if success: QgsCredentials.instance().put(connInfo, user, passwd) else: raise GeoAlgorithmExecutionException("Couldn't connect to database") try: db = postgis.GeoDB( host=uri.host(), port=int(uri.port()), dbname=uri.database(), user=user, passwd=passwd ) except postgis.DbError as e: raise GeoAlgorithmExecutionException("Couldn't connect to database:\n%s" % e.message) def _runSQL(sql): try: db._exec_sql_and_commit(str(sql)) except postgis.DbError as e: raise GeoAlgorithmExecutionException("Error creating output PostGIS table:\n%s" % e.message) fields = [_toQgsField(f) for f in fields] fieldsdesc = ",".join("%s %s" % (f.name(), TYPE_MAP_POSTGIS_LAYER.get(f.type(), "VARCHAR")) for f in fields) _runSQL("CREATE TABLE %s.%s (%s)" % (uri.schema(), uri.table().lower(), fieldsdesc)) if geometryType != QgsWkbTypes.NullGeometry: _runSQL( "SELECT AddGeometryColumn('{schema}', '{table}', 'the_geom', {srid}, '{typmod}', 2)".format( table=uri.table().lower(), schema=uri.schema(), srid=crs.authid().split(":")[-1], typmod=QgsWkbTypes.displayString(geometryType).upper(), ) ) self.layer = QgsVectorLayer(uri.uri(), uri.table(), "postgres") self.writer = self.layer.dataProvider() elif self.destination.startswith(self.SPATIALITE_LAYER_PREFIX): self.isNotFileBased = True uri = QgsDataSourceUri(self.destination[len(self.SPATIALITE_LAYER_PREFIX) :]) try: db = spatialite.GeoDB(uri=uri) except spatialite.DbError as e: raise GeoAlgorithmExecutionException("Couldn't connect to database:\n%s" % e.message) def _runSQL(sql): try: db._exec_sql_and_commit(str(sql)) except spatialite.DbError as e: raise GeoAlgorithmExecutionException("Error creating output Spatialite table:\n%s" % str(e)) fields = [_toQgsField(f) for f in fields] fieldsdesc = ",".join( "%s %s" % (f.name(), TYPE_MAP_SPATIALITE_LAYER.get(f.type(), "VARCHAR")) for f in fields ) _runSQL("DROP TABLE IF EXISTS %s" % uri.table().lower()) _runSQL("CREATE TABLE %s (%s)" % (uri.table().lower(), fieldsdesc)) if geometryType != QgsWkbTypes.NullGeometry: _runSQL( "SELECT AddGeometryColumn('{table}', 'the_geom', {srid}, '{typmod}', 2)".format( table=uri.table().lower(), srid=crs.authid().split(":")[-1], typmod=QgsWkbTypes.displayString(geometryType).upper(), ) ) self.layer = QgsVectorLayer(uri.uri(), uri.table(), "spatialite") self.writer = self.layer.dataProvider() else: formats = QgsVectorFileWriter.supportedFiltersAndFormats() OGRCodes = {} for (key, value) in list(formats.items()): extension = str(key) extension = extension[extension.find("*.") + 2 :] extension = extension[: extension.find(" ")] OGRCodes[extension] = value OGRCodes["dbf"] = "DBF file" extension = self.destination[self.destination.rfind(".") + 1 :] if extension not in OGRCodes: extension = "shp" self.destination = self.destination + ".shp" if geometryType == QgsWkbTypes.NoGeometry: if extension == "shp": extension = "dbf" self.destination = self.destination[: self.destination.rfind(".")] + ".dbf" if extension not in self.nogeometry_extensions: raise GeoAlgorithmExecutionException("Unsupported format for tables with no geometry") qgsfields = QgsFields() for field in fields: qgsfields.append(_toQgsField(field)) # use default dataset/layer options dataset_options = QgsVectorFileWriter.defaultDatasetOptions(OGRCodes[extension]) layer_options = QgsVectorFileWriter.defaultLayerOptions(OGRCodes[extension]) self.writer = QgsVectorFileWriter( self.destination, encoding, qgsfields, geometryType, crs, OGRCodes[extension], dataset_options, layer_options, )