From b1b7e1081fb56eb1712142d89843f9e00f7e7724 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Germ=C3=A1n=20Carrillo?= Date: Sat, 8 Jun 2024 19:05:28 -0500 Subject: [PATCH] [core] Add methods to handle QGIS service connections --- pg_service_parser/core/service_connections.py | 47 +++++++++++++++++++ 1 file changed, 47 insertions(+) create mode 100644 pg_service_parser/core/service_connections.py diff --git a/pg_service_parser/core/service_connections.py b/pg_service_parser/core/service_connections.py new file mode 100644 index 0000000..bc0f56d --- /dev/null +++ b/pg_service_parser/core/service_connections.py @@ -0,0 +1,47 @@ +from qgis.core import ( + QgsAbstractDatabaseProviderConnection, + QgsDataSourceUri, + QgsProviderRegistry, +) +from qgis.gui import QgsGui +from qgis.PyQt.QtCore import QSettings + + +def get_connections(service: str) -> dict[str, QgsAbstractDatabaseProviderConnection]: + res = {} + provider = QgsProviderRegistry.instance().providerMetadata("postgres") + conns = provider.connections() + for key, pg_conn in conns.items(): + if QgsDataSourceUri(pg_conn.uri()).service() == service: + res[key] = pg_conn + + return res + + +def create_connection(service: str, name: str) -> None: + config = {} + uri = f"service='{service}'" + provider = QgsProviderRegistry.instance().providerMetadata("postgres") + conn = provider.createConnection(uri, config) + provider.saveConnection(conn, name) + # conn.store(name) + + +def remove_connection(conn_name: str) -> None: + provider = QgsProviderRegistry.instance().providerMetadata("postgres") + provider.deleteConnection(conn_name) + + +def edit_connection(conn_name: str) -> None: + provider = QgsProviderRegistry.instance().providerMetadata("postgres") + + if conn_name in provider.dbConnections(): + pg = QgsGui.sourceSelectProviderRegistry().providerByName("postgres") + w = pg.createDataSourceWidget() + + settings = QSettings() + settings.value("PostgreSQL/connections/selected") + settings.setValue("PostgreSQL/connections/selected", conn_name) + + w.refresh() # To reflect the newly selected connection + w.btnEdit_clicked()