Write a layer to a GeoPackage
The easiest way to save a vector layer to GeoPackage is to use the "Save vector features to file" algorithm, available from QGIS 3.16 on.
import processing
params = {'INPUT': existing_layer,
'OUTPUT': '/tmp/new_gpkg.gpkg',
'LAYER_NAME': 'new_layer_name'}
processing.run("native:savefeatures", params)
Note that you can pass additional GDAL/OGR options by passing DATASOURCE_OPTIONS
and LAYER_OPTIONS
parameters.
Warning: If you pass a path to an existing GeoPackage as OUTPUT
parameter, this algorithm will replace your GeoPackage by a new one!!!
Adding an additional layer to an existing GeoPackage
Option 1
If you want to add a layer to an existing GeoPackage (and still preserve other existing layers!), you can use the GDAL's "Convert format" algorithm in this way:
import processing
params = {'INPUT': existing_layer,
'OPTIONS':'-update -nln my_new_layer_name',
'OUTPUT':'/tmp/existing_db.gpkg'}
processing.run("gdal:convertformat", params)
Where -update indicates the existing GeoPackage shouldn't be overwritten but updated, and -nln (optional) indicates the layer name you want your existing_layer
to have when created into the existing GeoPackage.
Option 2
You could also use the "Package layers" algorithm, which allows you to add several layers at once, in this way:
import processing
params = {'LAYERS': [layer1, layer2],
'OUTPUT': '/tmp/existing_db.gpkg',
'OVERWRITE': False, # Important!
'SAVE_STYLES': False,
'SAVE_METADATA': False,
'SELECTED_FEATURES_ONLY': False}
processing.run("native:package", params)
Note: Set the rest of parameters as you like, but the OVERWRITE
one should be set to False
if you want to update the existing GeoPackage.