diff --git a/qtribu/gui/db_form.py b/qtribu/gui/db_form.py new file mode 100644 index 00000000..680ceb8d --- /dev/null +++ b/qtribu/gui/db_form.py @@ -0,0 +1,63 @@ +""" + Form to let the end-user pick its options. +""" + +import logging + +from pg_background_tasks.core.utilities.db_tools import get_db_connections +from qgis.PyQt import uic +from qgis.PyQt.QtCore import pyqtSignal +from qgis.PyQt.QtGui import QIcon +from qgis.PyQt.QtWidgets import QDialog + +ico_postgis = QIcon(":/images/themes/default/mIconPostgis.svg") +ico_spatialite = QIcon(":/images/themes/default/mIconSpatialite.svg") + +logger = logging.getLogger(__name__) +logging.basicConfig(level=logging.DEBUG) + + +class DatabasePickerForm(QDialog): + """Form to select the database connection to use.""" + + closingPlugin = pyqtSignal() + + def __init__( + self, parent=None, db_connections: list = [], ui_filepath: str = "db_form.ui" + ): + """Constructor + + :param dbname: path to db + :type dbname: string + :param parent: Qt parent + :type parent: QtWidget + """ + super(DatabasePickerForm, self).__init__(parent) + uic.loadUi(uifile=ui_filepath.resolve(), baseinstance=self) + + # tuning + self.rad_db_type_postgis.setIcon(ico_postgis) + self.rad_db_type_spatialite.setIcon(ico_spatialite) + + # fill combobox + self.rad_db_type_postgis.toggled.connect(lambda: self._cbb_fill_connections()) + self.rad_db_type_spatialite.toggled.connect( + lambda: self._cbb_fill_connections() + ) + + # by default, trigger postgis + self._cbb_fill_connections() + + def _cbb_fill_connections(self): + self.cbb_db_connections.clear() + if self.rad_db_type_postgis.isChecked(): + for k, v in get_db_connections(db_type="postgres").items(): + logger.error(type(v)) + self.cbb_db_connections.addItem(k, v) + if self.rad_db_type_spatialite.isChecked(): + for k, v in get_db_connections(db_type="spatialite").items(): + self.cbb_db_connections.addItem(k, v) + + def closeEvent(self, event): + self.closingPlugin.emit() + event.accept() diff --git a/qtribu/gui/db_form.ui b/qtribu/gui/db_form.ui new file mode 100644 index 00000000..cda5a77f --- /dev/null +++ b/qtribu/gui/db_form.ui @@ -0,0 +1,213 @@ + + + dlg_form + + + + 0 + 0 + 438 + 174 + + + + + 0 + 0 + + + + + 400 + 150 + + + + + 450 + 180 + + + + Database Huge Processing + + + + :/plugins/pg_background_tasks/resources/logo_geotribu.png:/plugins/pg_background_tasks/resources/logo_geotribu.png + + + 0.900000000000000 + + + true + + + + + + true + + + + + + + + + + + Type: + + + true + + + + + + + + + + Connection: + + + true + + + + + + + + + + + + + + + + + SQL File: + + + + + + + + + + + + + + + + PostGIS + + + true + + + + + + + Qt::LeftToRight + + + true + + + + + + SpatiaLite + + + + + + + + + + + + + + Qt::Horizontal + + + QSizePolicy::Maximum + + + + 204 + 20 + + + + + + + + + + + Qt::Horizontal + + + QDialogButtonBox::Cancel|QDialogButtonBox::Ok + + + + + + + + QgsFileWidget + QWidget +
qgsfilewidget.h
+
+
+ + + + + + buttonBox + accepted() + dlg_form + accept() + + + 248 + 254 + + + 157 + 274 + + + + + buttonBox + rejected() + dlg_form + reject() + + + 316 + 260 + + + 286 + 274 + + + + +
diff --git a/qtribu/tasks/__init__.py b/qtribu/tasks/__init__.py new file mode 100644 index 00000000..e69de29b diff --git a/qtribu/tasks/execute_sql.py b/qtribu/tasks/execute_sql.py new file mode 100644 index 00000000..d97e95dd --- /dev/null +++ b/qtribu/tasks/execute_sql.py @@ -0,0 +1,38 @@ +import os + +import processing +from qgis.core import QgsMessageLog, QgsTask +from qgis.PyQt.QtCore import pyqtSignal + + +class SqlTask(QgsTask): + """SQL execution as QgsTask subclass""" + + terminated = pyqtSignal(str) + + def __init__(self, description, iface, layer, nb_label, model_path, extent=None): + super().__init__(description, QgsTask.CanCancel) + tmp_name = processing.getTempFilename() + ".tif" + self.param = { + "INPUT": layer.id(), + "OUTPUT": os.path.join(tmp_name), + "LABELS": nb_label, + "MODEL": model_path, + } + if extent: + self.param["EXTENT"] = extent + + def run(self): + out = processing.run( + "QDeepLandia:InferenceQDeepLandia", self.param, feedback=self.feedback + ) + if os.path.exists(out["OUTPUT"]): + self.terminated.emit(out["OUTPUT"]) + return True + + def cancel(self): + QgsMessageLog.logMessage( + 'Task "{name}" was canceled'.format(name=self.description()), "QDeeplandia" + ) + self.terminated.emit(None) + super().cancel() diff --git a/tests/dev/dev_connections_old.py b/tests/dev/dev_connections_old.py new file mode 100644 index 00000000..48901130 --- /dev/null +++ b/tests/dev/dev_connections_old.py @@ -0,0 +1,72 @@ +import pprint + +from qgis.core import QgsDataSourceUri +from qgis.PyQt.QtCore import QSettings +from qgis.PyQt.QtGui import QIcon +from qgis.PyQt.QtWidgets import QDialog, QComboBox + +# variables +db_types = { + "GeoPackage": QIcon(":/images/themes/default/mGeoPackage.svg"), + "PostgreSQL": QIcon(":/images/themes/default/mIconPostgis.svg"), + "SpatiaLite": QIcon(":/images/themes/default/mIconSpatialite.svg"), +} +dico_connections_for_combobox = {} +settings = QSettings() + +for db_type in db_types: + print(db_type) + # retrouver les connections du type de base de données + settings.beginGroup(f"/{db_type}/connections/") + connections = settings.childGroups() + settings.endGroup() + + selected_conn = settings.value(f"/{db_type}/connections/selected", "", type=str) + if selected_conn not in connections: + connections.append(selected_conn) + + for connection_name in connections: + print(connection_name) + uri = QgsDataSourceUri() + uri.setConnection( + aHost=settings.value(f"{db_type}/connections/{connection_name}/host"), + aPort=settings.value(f"{db_type}/connections/{connection_name}/port"), + aDatabase=settings.value( + f"{db_type}/connections/{connection_name}/database" + ), + aUsername="", + aPassword="", + ) + # selon le type d'authentification configuré, on s'adapte + if ( + settings.value(f"{db_type}/connections/{connection_name}/saveUsername") + == "true" + ): + uri.setUsername( + settings.value(f"{db_type}/connections/{connection_name}/username"), + ) + if ( + settings.value(f"{db_type}/connections/{connection_name}/savePassword") + == "true" + ): + uri.setPassword( + settings.value(f"{db_type}/connections/{connection_name}/password"), + ) + dico_connections_for_combobox[connection_name] = db_type, uri + + +# la fenêtre de dialogue pour accueillir notre liste déroulante +dd = QDialog(iface.mainWindow()) +dd.setWindowTitle("Connexions {}".format(" / ".join(db_types))) + +# on remplit la liste déroulante +cbb_db_connections = QComboBox(dd) +for k, v in dico_connections_for_combobox.items(): + cbb_db_connections.addItem(db_types.get(v[0]), k, v[1]) + +# un peu de tunning des dimensions +dd.resize(300, 30) +cbb_db_connections.resize(300, 30) + +# on affiche +dd.show() diff --git a/tests/dev/dev_db_connections_new.py b/tests/dev/dev_db_connections_new.py new file mode 100644 index 00000000..8ee0652b --- /dev/null +++ b/tests/dev/dev_db_connections_new.py @@ -0,0 +1,76 @@ +import pprint +from functools import partial + +from qgis.core import QgsApplication, QgsDataSourceUri, QgsProviderRegistry +from qgis.PyQt.QtGui import QIcon +from qgis.PyQt.QtWidgets import QComboBox, QDialog + +# variables + +# point de vigilance, les noms du type de base de données ne sont pas exactement les mêmes... +db_types = ("ogr", "postgres", "spatialite") +dico_connections_for_combobox = {} + +# un peu d'info +print( + "Liste des formats disponibles : ", + sorted(QgsProviderRegistry.instance().providerList()), +) +print( + "Liste des drivers de base de données disponibles : ", + QgsProviderRegistry.instance().databaseDrivers(), +) + +for db_type in db_types: + print("listing des connexions de type : ", db_type) + # retrouver les connections du type de base de données + connections = QgsProviderRegistry.instance().providerMetadata(db_type).connections() + + for connection_name in connections: + dico_connections_for_combobox[connection_name] = db_type, connections.get( + connection_name + ) + + +def popo(): + print("hey") + print(cbb_db_connections.currentText()) + conn = dico_connections_for_combobox[cbb_db_connections.currentText()][1] + print(conn.providerKey(), conn.icon()) + + selected = cbb_db_connections.itemData(cbb_db_connections.currentIndex()) + print(selected) + print(selected.uri()) + print(isinstance(selected.uri(), str)) +# print(QgsDataSourceUri(selected.uri()).database()) +# print(QgsDataSourceUri(selected.uri()).host()) +# print(selected.configuration()) + + # print(conn.uri.connectionInfo(True)) + + # lister les schémas +# if conn.providerKey().startswith("postgr"): +# print("Schémas : ", conn.schemas()) + + # lister les tables + # print("Tables : ", [(t.defaultName(), str(t.flags())) for t in conn.tables()[:10]]) + + +# la fenêtre de dialogue pour accueillir notre liste déroulante +dd = QDialog(iface.mainWindow()) +dd.setWindowTitle("Connexions {}".format(" / ".join(db_types))) + +# on remplit la liste déroulante +cbb_db_connections = QComboBox(dd) +for k, v in dico_connections_for_combobox.items(): + cbb_db_connections.addItem(v[1].icon(), k, v[1]) + +cbb_db_connections.activated.connect(partial(popo)) + +# un peu de tunning des dimensions +dd.resize(300, 30) +cbb_db_connections.resize(300, 30) + + +# on affiche +dd.show() diff --git a/tests/dev/docker-compose_postgis.yml b/tests/dev/docker-compose_postgis.yml new file mode 100644 index 00000000..8ae4a2b5 --- /dev/null +++ b/tests/dev/docker-compose_postgis.yml @@ -0,0 +1,9 @@ +version: "3" +services: + postgis: + image: postgis/postgis:13-3.0-alpine + ports: + - "5432:5432" + environment: + - POSTGRES_USER=geotribu + - POSTGRES_PASSWORD=geotribu