PyQGIS PostgreSQL – How to Delete QGIS Project Stored in PostgreSQL using PyQGIS

postgresqlpyqgisqgs

I would like to delete a .qgs project stored in PostgreSQL using PyQGIS.
This SQL code does the job into pgAdmin :

DELETE FROM test2.qgis_projects WHERE name = 'Project_name';

My attempt which doesn't work in PyQGIS is :

from PyQt5.QtSql import *
uri = QgsDataSourceUri()
uri.setConnection("localhost", "5432", "BDtest", "postgres", "password")

db = QSqlDatabase.addDatabase("BDtest");
db.setHostName(uri.host())
db.setDatabaseName(uri.database())
db.setPort(int(uri.port()))
db.setUserName(uri.username())
db.setPassword(uri.password())
db.open()
query = db.exec_("""DELETE FROM test2.qgis_projects WHERE name = 'Project_name';""")
query.next()
query.value(0)
print(query)

This last code doesn't work in PyQGIS, could someone correct it?

I think it misses uri.setDataSource() but I do not know how to use it, because the data I need to delete is a qgis_project (there is no geometry).

Best Answer

The recommended way of removing a QGIS project stored in a database is this:

  1. Build a proper uri

    For PostgreSQL, something like:

    'postgresql://user:password@localhost:5432?sslmode=disable&dbname=my_db&schema=my_schema&project=my_pg_project'
    

    Note the project=my_pg_project at the end of the uri.

  2. Get the corresponding project storage object

    storage = QgsApplication.projectStorageRegistry().projectStorageFromUri(uri)
    
  3. Remove the project

     storage.removeProject(uri)
    

Related: