2

I'm trying to export a simple PostGIS table loaded in QGIS to a geopackage file.

Here's an example:

options = QgsVectorFileWriter.SaveVectorOptions()
options.driverName = "GPKG"
options.layerName = "_".join(myLayer.name().split(' '))

geo_package = 'my_gpkg.gpkg'

if not os.path.exists(geo_package):
    options.actionOnExistingFile = QgsVectorFileWriter.CreateOrOverwriteFile
else:
    options.actionOnExistingFile = QgsVectorFileWriter.CreateOrOverwriteLayer

res, text = QgsVectorFileWriter.writeAsVectorFormatV2(myLayer, geo_package, QgsCoordinateTransformContext(), options)

if res == QgsVectorFileWriter.NoError:
     print("Successfull export of layer {}".format(myLayer))
else:
    print("Fail error {}:{}".format(res, text))

It works fine for Vector layers but for a simple PostGIS table, I get the Error code 8 with no Error message.

2
  • what do you mean by "simple PostGIS table"? one with no geometry?
    – Ian Turton
    Jul 17 '20 at 8:16
  • Yes, i need to save this table in the geopackage
    – aurel_nc
    Jul 17 '20 at 8:46
0

The simple PostGIS table is a table without geometry. Importing it as is was an error and the layer was not valid. I wrongly set the datasource in the uri:

uri = QgsDataSourceUri()
uri.setConnection("MyServerAdress", "5432", "myBase", "user", "pass")
uri.setDataSource(schema, table, "geom")
layer = QgsVectorLayer(uri.uri(False), table, "postgres")
QgsProject.instance().addMapLayer(couche)

Altough I should have done this:

uri = QgsDataSourceUri()
uri.setConnection("MyServerAdress", "5432", "myBase", "user", "pass")
uri.setDataSource(schema, table, None)
layer = QgsVectorLayer(uri.uri(False), table, "postgres")
QgsProject.instance().addMapLayer(couche)

I wrote a topic here:Import a table with no geometry

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.