Using QGIS 3.8.0. Despite similar questions out there, I can't reproject a vector layer to a geopackage while specifying the original table name in a QGIS Python Processing script. FYI, all tablenames have underscores, so no spaces or invalid characters.
I see two options:
processing.run('native:reprojectlayer', alg_params....
QgsVectorFileWriter.writeAsVectorFormat(vlayer, geopP,'utf-8', crsObject, "gpkg")
Option 1: the native:reprojectlayer
, I can't see how to specify the table name in the alg_params
:
alg_params = {
'INPUT': parameters['inputlayer'],
'TARGET_CRS': parameters['selectcoordinatesystem'],
'OUTPUT': outData}
When I specify the tablename
for the geopackage in outData
, like c:/temp/geopackage.gpkg|layername=buildingData
it throws an error:
Could not create layer c:/temp/MyExport.gpkg|layername=buildingData.gpkg: Creation of data source failed (OGR error: sqlite3_open(c:/temp/MyExport.gpkg|layername=buildingData.gpkg) failed: unable to open database file)
So it looks like the 'native:reprojectlayer'
output is looking for a destination file ending '.gpkg' and has added that on the end of my table name. Does this algorithm support writing specific tablenames?
The only thing that works is only passing in the gpkg without the table and that repojects the dataset but exports the table with the same name as the geopackage file (c:/temp/MyExport.gpkg|layername=MyExport
).
Option 2: Trying QgsVectorFileWriter
I'm using vector layer objects taken from the selected layer in the QGIS project:
def initAlgorithm(..
self.addParameter(QgsProcessingParameterVectorLayer(self.selectdataV, 'selectdataV', types=[QgsProcessing.TypeVector], defaultValue=None))
def processAlgorithm(...
layerV = self.parameterAsVectorLayer(parameters, self.selectdataV, context)
layname = layerV.name()
When using SaveVectorOptions()
I want to specify layername
.
options = QgsVectorFileWriter.SaveVectorOptions()
options.actionOnExistingFile = QgsVectorFileWriter.CreateOrOverwriteLayer
options.layerName = layname
writer = QgsVectorFileWriter.writeAsVectorFormat(layer=layObj, fileName=geopP, layerOptions=options, fileEncoding='utf-8', destCRS=crsObject, driverName="gpkg")
I get the error:
TypeError: QgsVectorFileWriter.writeAsVectorFormat(): arguments did not match any overloaded call: overload 1: argument 'layerOptions' has unexpected type 'SaveVectorOptions' overload 2: 'layerOptions' is not a valid keyword argument
If I take out layerOptions
it will just create the same table name as the Geopackage name like in Option 1.
What am I doing wrong? Baring in mind, I need to specify the new CRS and table name.