1

As I have a lot of layers, I am writing a plugin that will import layers through TaskManager. Script imports layers successfully into the project with some minor problems. When layers are loaded I can see pre-drawn objects that are in db, also can open attribute tables without a problem.

The problem that's happening is when adding new drawn object, I can't save changes into the database (diskette icon). If clicking on Toggle Editing and saving through dialog I've get empty error:

Could not commit changes to layer layer_name
Errors: ERROR: 1 feature(s) not added.
Provider errors: 

The interesting thing is that if I save a QGIS project and reopen it, then i can save changes (new drawn objects) and use layers normally.

I'm using QGIS 3.28.3 (also tested on 3.22 LTR and 3.26) and on a newly created MSSQL Express db (also tested on PostgreSQL 15). I don't have that problems if I load layers without using Task Manager. For this purpose I am attaching a script that you can run via the python console in QGIS.

# Example: Normal import
uri = QgsDataSourceUri()
uri.setSrid("3794")
uri.setWkbType(QgsWkbTypes.LineString)

uri.setConnection("path_to_db", "", "db_name", "usr_name", "usr_pw")
uri.setDataSource("dbo", "table_name", "geometry")
uri.setDriver("SQL Server Native Client 11.0")

vlayer = QgsVectorLayer(uri.uri(), "layer_name", "mssql")
crs = vlayer.crs()
crs.createFromId(3794)
vlayer.setCrs(crs)
QgsProject.instance().addMapLayer(vlayer, True)
# Example: Task Manager import:

import time
class MyTaskExample(QgsTask):
    def __init__(self, description):
        super().__init__(description)

    def run(self):
        time.sleep(2)
        uri = QgsDataSourceUri()
        uri.setSrid("3794")
        uri.setWkbType(QgsWkbTypes.LineString)
        
        # MSSQL
        uri.setConnection("path_to_db", "", "db_name", "usr_name", "usr_pw")
        uri.setDataSource("dbo", "table_name", "geometry")
        uri.setDriver("SQL Server Native Client 11.0")
        vlayer = QgsVectorLayer(uri.uri(), "layer_name", "mssql")
        
        # POSTGRESQL
        # uri.setConnection("localhost", "5432", "db_name", "usr_name", "usr_pw")
        # uri.setDataSource("public", "table_name", "geometry")
        # vlayer = QgsVectorLayer(uri.uri(), "layer_name", "postgres")
        
        crs = vlayer.crs()
        crs.createFromId(3794)
        vlayer.setCrs(crs)
        self.vlayer = vlayer
        return True

    def finished(self, result):
        if result:
            QgsProject.instance().addMapLayer(self.vlayer, True)
        
task = MyTaskExample('QgsTask Example')
QgsApplication.taskManager().addTask(task)
 

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.