I am very new to QGIS development, but not GIS. My goal is to create a copy of an existing layer (created within the QGIS GUI) from one SpatiaLite file to another, then add new attributes and populate records to the copy.
I have successfully used the QgsVectorFileWriter.writeAsVectorFormatV2()
to create the copy, but checking the validity of the copy returns false and when adding to the map has a broken link in the TOC. The original layer is empty and in 4326 crs. I have done quite a bit of searching but can't track down what the issue is.
I have tried adding a transform in the map properties, I have digitized to a polygon in the copied layer and to see if creating an extent might help. I have checked the encoding. Just not sure where to go from here.
Here is the code:
uri = QgsDataSourceUri()
db_path = os.path.join(
"C:\\",
"Users",
getpass.getuser(),
"Documents",
"temp_gis_data",
"temp_gis_data.sqlite",
)
db_path2 = os.path.join(
"C:\\",
"Users",
getpass.getuser(),
"Documents",
"temp_gis_data",
"temp_gis_data2.sqlite",
)
uri.setDatabase(db_path)
schema = ""
table = "test_poly"
geom_column = "geom"
uri.setDataSource(schema, table, geom_column)
driverName = "SpatiaLite"
vlayer = QgsVectorLayer(uri.uri(), table, driverName)
print(vlayer.isValid()) --> True
QgsProject.instance().addMapLayer(vlayer)
options = QgsVectorFileWriter.SaveVectorOptions()
options.driverName = driverName
options.layerName = "test_poly"
if not os.path.exists(db_path2):
print("exists false")
options.actionOnExistingFile = QgsVectorFileWriter.CreateOrOverwriteFile
options.EditionCapability = QgsVectorFileWriter.CanAddNewLayer
else:
options.actionOnExistingFile = QgsVectorFileWriter.CreateOrOverwriteLayer
transform_context = QgsProject.instance().transformContext()
err = QgsVectorFileWriter.writeAsVectorFormatV2(
vlayer, db_path2,transform_context, options
)
print(err)
#update layer with data from db
uri = QgsDataSourceUri()
uri.setDatabase(db_path2)
print(uri.uri())
schema = ""
table = "test_poly"
geom_column = "geom"
uri.setDataSource(schema, table, geom_column)
vlayer2 = QgsVectorLayer(uri.uri(), table, driverName)
QgsProject.instance().addMapLayer(vlayer2) --> broken link to source, but can confirm a layer was created
print(vlayer2.isValid()) -->False