Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fonctionnalité : sélecteur de connexions aux bases de données #96

Draft
wants to merge 5 commits into
base: main
Choose a base branch
from
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
63 changes: 63 additions & 0 deletions qtribu/gui/db_form.py
Original file line number Diff line number Diff line change
@@ -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()
213 changes: 213 additions & 0 deletions qtribu/gui/db_form.ui
Original file line number Diff line number Diff line change
@@ -0,0 +1,213 @@
<?xml version="1.0" encoding="UTF-8"?>
<ui version="4.0">
<class>dlg_form</class>
<widget class="QDialog" name="dlg_form">
<property name="geometry">
<rect>
<x>0</x>
<y>0</y>
<width>438</width>
<height>174</height>
</rect>
</property>
<property name="sizePolicy">
<sizepolicy hsizetype="MinimumExpanding" vsizetype="MinimumExpanding">
<horstretch>0</horstretch>
<verstretch>0</verstretch>
</sizepolicy>
</property>
<property name="minimumSize">
<size>
<width>400</width>
<height>150</height>
</size>
</property>
<property name="maximumSize">
<size>
<width>450</width>
<height>180</height>
</size>
</property>
<property name="windowTitle">
<string>Database Huge Processing</string>
</property>
<property name="windowIcon">
<iconset resource="../resources.qrc">
<normaloff>:/plugins/pg_background_tasks/resources/logo_geotribu.png</normaloff>:/plugins/pg_background_tasks/resources/logo_geotribu.png</iconset>
</property>
<property name="windowOpacity">
<double>0.900000000000000</double>
</property>
<property name="autoFillBackground">
<bool>true</bool>
</property>
<property name="locale">
<locale language="English" country="UnitedStates"/>
</property>
<property name="sizeGripEnabled">
<bool>true</bool>
</property>
<layout class="QGridLayout" name="gridLayout_2">
<item row="0" column="0" colspan="2">
<layout class="QFormLayout" name="formLayout">
<item row="0" column="0">
<widget class="QLabel" name="lbl_db_type">
<property name="locale">
<locale language="English" country="UnitedStates"/>
</property>
<property name="text">
<string>Type:</string>
</property>
<property name="scaledContents">
<bool>true</bool>
</property>
</widget>
</item>
<item row="4" column="0">
<widget class="QLabel" name="lbl_db_connections">
<property name="locale">
<locale language="English" country="UnitedStates"/>
</property>
<property name="text">
<string>Connection:</string>
</property>
<property name="scaledContents">
<bool>true</bool>
</property>
</widget>
</item>
<item row="4" column="1">
<widget class="QComboBox" name="cbb_db_connections">
<property name="locale">
<locale language="English" country="UnitedStates"/>
</property>
</widget>
</item>
<item row="7" column="0">
<widget class="QLabel" name="lbl_file_picker">
<property name="locale">
<locale language="English" country="UnitedStates"/>
</property>
<property name="text">
<string>SQL File:</string>
</property>
</widget>
</item>
<item row="7" column="1">
<widget class="QgsFileWidget" name="wdg_file_picker">
<property name="locale">
<locale language="English" country="UnitedStates"/>
</property>
</widget>
</item>
<item row="0" column="1">
<layout class="QHBoxLayout" name="horizontalLayout">
<item>
<widget class="QRadioButton" name="rad_db_type_postgis">
<property name="text">
<string>PostGIS</string>
</property>
<property name="checked">
<bool>true</bool>
</property>
</widget>
</item>
<item>
<widget class="QRadioButton" name="rad_db_type_spatialite">
<property name="layoutDirection">
<enum>Qt::LeftToRight</enum>
</property>
<property name="autoFillBackground">
<bool>true</bool>
</property>
<property name="locale">
<locale language="English" country="UnitedStates"/>
</property>
<property name="text">
<string>SpatiaLite</string>
</property>
</widget>
</item>
</layout>
</item>
</layout>
</item>
<item row="1" column="0">
<spacer name="horizontalSpacer">
<property name="locale">
<locale language="English" country="UnitedStates"/>
</property>
<property name="orientation">
<enum>Qt::Horizontal</enum>
</property>
<property name="sizeType">
<enum>QSizePolicy::Maximum</enum>
</property>
<property name="sizeHint" stdset="0">
<size>
<width>204</width>
<height>20</height>
</size>
</property>
</spacer>
</item>
<item row="1" column="1">
<widget class="QDialogButtonBox" name="buttonBox">
<property name="locale">
<locale language="English" country="UnitedStates"/>
</property>
<property name="orientation">
<enum>Qt::Horizontal</enum>
</property>
<property name="standardButtons">
<set>QDialogButtonBox::Cancel|QDialogButtonBox::Ok</set>
</property>
</widget>
</item>
</layout>
</widget>
<customwidgets>
<customwidget>
<class>QgsFileWidget</class>
<extends>QWidget</extends>
<header>qgsfilewidget.h</header>
</customwidget>
</customwidgets>
<resources>
<include location="../resources.qrc"/>
</resources>
<connections>
<connection>
<sender>buttonBox</sender>
<signal>accepted()</signal>
<receiver>dlg_form</receiver>
<slot>accept()</slot>
<hints>
<hint type="sourcelabel">
<x>248</x>
<y>254</y>
</hint>
<hint type="destinationlabel">
<x>157</x>
<y>274</y>
</hint>
</hints>
</connection>
<connection>
<sender>buttonBox</sender>
<signal>rejected()</signal>
<receiver>dlg_form</receiver>
<slot>reject()</slot>
<hints>
<hint type="sourcelabel">
<x>316</x>
<y>260</y>
</hint>
<hint type="destinationlabel">
<x>286</x>
<y>274</y>
</hint>
</hints>
</connection>
</connections>
</ui>
Empty file added qtribu/tasks/__init__.py
Empty file.
38 changes: 38 additions & 0 deletions qtribu/tasks/execute_sql.py
Original file line number Diff line number Diff line change
@@ -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()
72 changes: 72 additions & 0 deletions tests/dev/dev_connections_old.py
Original file line number Diff line number Diff line change
@@ -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()
Loading
Loading