outils de rename pour bd psql

This commit is contained in:
Tom LAVEILLE 2025-02-12 17:28:52 +01:00
parent a90a45a0b9
commit e2e062ed12
8 changed files with 532 additions and 5 deletions

View File

@ -21,6 +21,7 @@ from .tools.resources import (
)
from .postgis_editor import Postgis_Editor
from .postgis_creator import Postgis_Creator
from .postgis_rename import Postgis_Rename
from .about_form import AboutDialog
from PyQt5.QtCore import *
@ -30,6 +31,7 @@ class PgPostgis:
""" Constructor. """
self.action_editor = None
self.action_creator = None
self.action_rename = None
# self.issues = None
self.provider = None
self.locator_filter = None
@ -58,6 +60,7 @@ class PgPostgis:
icon = QIcon(resources_path('icons', 'page_new.png'))
icon2 = QIcon(resources_path('icons', 'page_ajout.png'))
icon3 = QIcon(resources_path('icons', 'page_rename.png'))
# Open the online help
self.help_action = QAction(icon, "CenRa_Postgis", iface.mainWindow())
@ -75,6 +78,21 @@ class PgPostgis:
self.postgis_editor = QAction(icon2, 'dossier_editor',None)
self.toolBar.addAction(self.postgis_editor)
self.postgis_editor.triggered.connect(self.open_editor)
if not self.action_rename:
self.action_rename = Postgis_Rename()
self.postgis_rename = QAction(icon3, 'dossier_rename',None)
self.toolBar.addAction(self.postgis_rename)
self.postgis_rename.triggered.connect(self.open_rename)
if os.environ['USERNAME'] == 'tlaveille' or os.environ['USERNAME'] == 'lpoulin' or os.environ['USERNAME'] == 'rclement':
self.action_rename.setEnabled(True)
self.postgis_rename.setEnabled(True)
self.postgis_rename.setVisible(1)
else:
self.action_rename.setEnabled(False)
self.postgis_rename.setEnabled(False)
self.postgis_rename.setVisible(0)
def open_about_dialog(self):
"""
@ -94,12 +112,18 @@ class PgPostgis:
self.action_creator.show()
self.action_creator.raise_()
def open_rename(self):
self.action_rename.show()
self.action_rename.raise_()
def unload(self):
""" Unload the plugin. """
if self.action_editor:
iface.removePluginMenu('CenRa_Postgis',self.postgis_editor)
if self.action_creator:
iface.removePluginMenu('CenRa_Postgis',self.postgis_creator)
if self.action_rename:
iface.removePluginMenu('CenRa_Postgis',self.postgis_rename)
if self.provider:
QgsApplication.processingRegistry().removeProvider(self.provider)

View File

@ -12,7 +12,7 @@
name=CenRa_POSTGIS
qgisMinimumVersion=3.0
description=Permet de crée un dossier dans la base PostGis
version=2.5
version=2.6
author=Conservatoire d'Espaces Naturels de Rhône-Alpes
email=si_besoin@cen-rhonealpes.fr
@ -21,7 +21,7 @@ email=si_besoin@cen-rhonealpes.fr
# Optional items:
# Uncomment the following line and add your changelog entries:
changelog=<h2>CenRa_POSTGIS:</h2></br><p><h3>04/02/2025 - Version 2.5: </h3> - Correctif bug création de couche.</p></br><p><h3>23/01/2025 - Version 2.4: </h3> - Correctif sur les pkey.</p></br><p><h3>22/01/2025 - Version 2.3: </h3> - Correctif sur la creation de projet.</p></br><p><h3>21/01/2025 - Version 2.2: </h3> - Correctif sur la longeur des nom.</p></br><p><h3>07/01/2025 - Version 2.1: </h3> - ByPass du certif ssl ci erreur.</p></br><p><h3>22/10/2024 - Version 2.0:</h3>- Refont du code.</p>
changelog=<h2>CenRa_POSTGIS:</h2></br><p><h3>12/02/2025 - Version 2.6: </h3> - InDev:renomé les schema et table.</p></br><p><h3>04/02/2025 - Version 2.5: </h3> - Correctif bug création de couche.</p></br><p><h3>23/01/2025 - Version 2.4: </h3> - Correctif sur les pkey.</p></br><p><h3>22/01/2025 - Version 2.3: </h3> - Correctif sur la creation de projet.</p></br><p><h3>21/01/2025 - Version 2.2: </h3> - Correctif sur la longeur des nom.</p></br><p><h3>07/01/2025 - Version 2.1: </h3> - ByPass du certif ssl ci erreur.</p></br><p><h3>22/10/2024 - Version 2.0:</h3>- Refont du code.</p>
# tags are comma separated with spaces allowed
tags=cenra, postgis, database

View File

@ -50,6 +50,7 @@ class Postgis_Creator(QDialog, EDITOR_CLASS):
# run method that performs all the real work
def raise_(self):
self.activateWindow()
# show the dialog
self.show()
# Run the dialog event loop

View File

@ -50,6 +50,7 @@ class Postgis_Editor(QDialog, EDITOR_CLASS):
### Outil Ajout de nouvelles couche a un dossier
def raise_(self):
self.activateWindow()
first_conn = psycopg2.connect("host=" + host + " port=" + port + " dbname="+dbname+" user=first_cnx password=" + password)
first_cur = first_conn.cursor(cursor_factory = psycopg2.extras.DictCursor)
first_cur.execute("SELECT mdp_w, login_w FROM pg_catalog.pg_user t1, admin_sig.vm_users_sig t2 WHERE t2.oid = t1.usesysid AND (login_w = '" + os_user + "' OR login_w = '" + os_user + "')")

View File

@ -0,0 +1,187 @@
# -*- coding: utf-8 -*-
from __future__ import absolute_import
# Import the PyQt and QGIS libraries
from builtins import next
from builtins import str
from builtins import object
import qgis
from qgis.PyQt.QtCore import QSettings
from qgis.PyQt.QtWidgets import QAction, QMenu, QDialog, QMessageBox
from qgis.PyQt.QtGui import QIcon
from PyQt5.QtCore import *
from PyQt5.QtGui import *
from PyQt5 import QtGui
from qgis.core import *
from qgis.core import QgsDataSourceUri
from .tools.PythonSQL import *
from .tools.resources import (
load_ui,
resources_path,
login_base,
send_issues,
create_vierge,
create_contour,
create_travaux,
create_habita
)
from .issues import CenRa_Issues
import os.path
import webbrowser, os
import psycopg2
import psycopg2.extras
import base64
from qgis.utils import iface
EDITOR_CLASS = load_ui('CenRa_PostgisRename_base.ui')
first_conn = psycopg2.connect("host=" + host + " port=" + port + " dbname="+dbname+" user=first_cnx password=" + password)
first_cur = first_conn.cursor(cursor_factory = psycopg2.extras.DictCursor)
first_cur.execute("SELECT mdp_w, login_w FROM pg_catalog.pg_user t1, admin_sig.vm_users_sig t2 WHERE t2.oid = t1.usesysid AND (login_w = '" + os_user + "' OR login_w = '" + os_user + "')")
res_ident = first_cur.fetchone()
mdp = base64.b64decode(str(res_ident[0])).decode('utf-8')
user = res_ident[1]
con = psycopg2.connect("host=" + host + " port=" + port + " dbname="+dbname+" user=" + user + " password=" + mdp)
cur = con.cursor(cursor_factory = psycopg2.extras.DictCursor)
first_conn.close()
class Postgis_Rename(QDialog, EDITOR_CLASS):
def __init__(self, parent=None):
_ = parent
super().__init__()
self.setupUi(self)
self.settings = QgsSettings()
self.s = QSettings()
self.setWindowIcon(QtGui.QIcon(resources_path('icons','icon.png')))
self.iface = iface
self.schema.currentIndexChanged.connect(self.Test)
self.buttonBox.accepted.connect(self.msgBox)
### Outil Ajout de nouvelles couche a un dossier
def raise_(self):
self.activateWindow()
self.groupBox_2.hide()
GET_ALL_SCHEMA = """SELECT DISTINCT table_schema FROM information_schema.tables WHERE table_schema LIKE '_form_%' OR table_schema LIKE '_01_%' OR table_schema LIKE '_07_%' OR table_schema LIKE '_26_%' OR table_schema LIKE '_42_%' OR table_schema LIKE '_69_%' ORDER BY table_schema;"""
cur.execute(GET_ALL_SCHEMA)
AllSchema = cur.fetchall()
last_value_schema = self.schema.currentText()
last_value_departement = self.departement.currentText()
self.schema.clear()
self.departement.clear()
self.schema.addItems([''])
for Schema in AllSchema:
self.schema.addItems(Schema)
self.departement.addItems(['','01','07','26','42','69','form'])
if last_value_schema != '':
self.schema.setCurrentIndex(self.schema.findText(last_value_schema))
if last_value_departement != '':
self.departement.setCurrentIndex(self.departement.findText(last_value_departement))
def Test(self):
if self.schema.currentText() != '':
self.loadValue()
else:
self.old_name.setText('')
def loadValue(self):
oldSchema = self.schema.currentText()
if oldSchema[:6] == '_form_':
oldSchema = self.schema.currentText()[6:]
prefixSchema = self.schema.currentText()[1:5]
else:
oldSchema = self.schema.currentText()[4:]
prefixSchema = self.schema.currentText()[1:3]
if oldSchema[:3] == 'at_':
oldSchema = oldSchema[3:]
self.animation.setChecked(1)
else:
self.animation.setChecked(0)
self.old_name.setText(oldSchema)
self.departement.setCurrentIndex(self.departement.findText(prefixSchema))
def updateName(self):
if self.departement.currentText() != '':
oldTableName = self.old_name.text()
newTableName = ((self.new_name.text()).lower()).replace(' ','_')
newPrefixSchema = '_'+self.departement.currentText()+'_'
if self.schema.currentText()[:6] == '_form_':
oldPrefixSchema = self.schema.currentText()[:6]
if (self.schema.currentText()[6:9]) == "at_":
oldPrefixSchema=oldPrefixSchema+'at_'
else:
oldPrefixSchema = self.schema.currentText()[:4]
if (self.schema.currentText()[4:7]) == 'at_':
oldPrefixSchema=oldPrefixSchema+'at_'
if self.animation.isChecked():
newPrefixSchema=newPrefixSchema+'at_'
oldSchemaName = oldPrefixSchema+oldTableName
newSchemaName = newPrefixSchema+newTableName
if oldSchemaName != newSchemaName:
global AllSQLrun
allSQLrun=''
SQL_UPDATE = """UPDATE public.layer_styles SET f_table_schema = '"""+newSchemaName+"""',f_table_name = replace(replace(f_table_name,'"""+oldTableName+"""','"""+newTableName+"""'),'"""+oldPrefixSchema+"""','"""+newPrefixSchema+"""') WHERE f_table_schema LIKE '"""+oldSchemaName+"""';"""
allSQLrun = allSQLrun+SQL_UPDATE
cur.execute(SQL_UPDATE)
SQL_GET_TABLE_RENAME = """SELECT table_name,replace(replace(table_name,'"""+oldTableName+"""','"""+newTableName+"""'),'"""+oldPrefixSchema+"""','"""+newPrefixSchema+"""') from information_schema.tables WHERE table_schema LIKE '"""+oldSchemaName+"""';"""
cur.execute(SQL_GET_TABLE_RENAME)
allTableRename = cur.fetchall()
allTableList = []
for TableRename in allTableRename:
oldTable = TableRename[0]
newTable = TableRename[1]
allTableList.append([oldTable,newSchemaName,newTable])
SQL_RENAME_TABLE = """ALTER TABLE """+oldSchemaName+'.'+oldTable+""" RENAME TO """+newTable+""";"""
allSQLrun = allSQLrun+SQL_RENAME_TABLE
cur.execute(SQL_RENAME_TABLE)
SQL_RENAME_SCHEMA = 'ALTER SCHEMA '+oldSchemaName+' RENAME TO '+newSchemaName
allSQLrun = allSQLrun+SQL_RENAME_SCHEMA
cur.execute(SQL_RENAME_SCHEMA)
#print(allSQLrun)
con.commit()
for LayerOpen in allTableList:
self.UnloadLoadLayers(LayerOpen[0],LayerOpen[1],LayerOpen[2])
def UnloadLoadLayers(self,OldName,NewSchema,NewTable):
allLayers = (QgsProject.instance().mapLayers().values())
listLayers = []
listLayersName = []
for layer in allLayers:
listLayers.append(layer)
listLayersName.append(layer.name())
if OldName in listLayersName:
layer = (listLayers[listLayersName.index(OldName)])
provider = layer.dataProvider()
dbname = (QgsDataSourceUri(provider.dataSourceUri()).database())
user = QgsDataSourceUri(provider.dataSourceUri()).username()
mdp = QgsDataSourceUri(provider.dataSourceUri()).password()
host = QgsDataSourceUri(provider.dataSourceUri()).host()
port = QgsDataSourceUri(provider.dataSourceUri()).port()
### Affichage de la table
uri = QgsDataSourceUri()
# set host name, port, database name, username and password
uri.setConnection(host ,port ,dbname ,user ,mdp)
# set database schema, table name, geometry column and optionaly subset (WHERE clause)
uri.setDataSource(NewSchema, NewTable, 'geom')
QgsProject.instance().removeMapLayer(layer.id())
layer = self.iface.addVectorLayer(uri.uri(), NewTable, "postgres")
def msgBox(self):
self.QMBquestion = QMessageBox()
self.QMBquestion.setWindowTitle(u"Attention !")
self.QMBquestion.setIcon(QMessageBox.Warning)
self.QMBquestion.setText("Attention, le renommage de dossier PostGIS peut engendrer des pertes de liaisons avec des projets QGIS !")
self.QMBquestion.setStandardButtons(QMessageBox.Yes|QMessageBox.No)
self.QMBquestion = self.QMBquestion.exec()
if self.QMBquestion == QMessageBox.Yes:
self.updateName()

Binary file not shown.

After

Width:  |  Height:  |  Size: 4.8 KiB

View File

@ -0,0 +1,314 @@
<?xml version="1.0" encoding="UTF-8"?>
<ui version="4.0">
<class>table_postgis</class>
<widget class="QDialog" name="table_postgis">
<property name="geometry">
<rect>
<x>0</x>
<y>0</y>
<width>533</width>
<height>364</height>
</rect>
</property>
<property name="windowTitle">
<string>Ajout d'une table</string>
</property>
<widget class="QDialogButtonBox" name="buttonBox">
<property name="geometry">
<rect>
<x>360</x>
<y>330</y>
<width>161</width>
<height>32</height>
</rect>
</property>
<property name="orientation">
<enum>Qt::Horizontal</enum>
</property>
<property name="standardButtons">
<set>QDialogButtonBox::Cancel|QDialogButtonBox::Ok</set>
</property>
</widget>
<widget class="QLabel" name="Titre">
<property name="geometry">
<rect>
<x>170</x>
<y>0</y>
<width>171</width>
<height>31</height>
</rect>
</property>
<property name="font">
<font>
<pointsize>14</pointsize>
<weight>75</weight>
<bold>true</bold>
</font>
</property>
<property name="text">
<string>Création de table</string>
</property>
</widget>
<widget class="QGroupBox" name="groupBox_2">
<property name="geometry">
<rect>
<x>10</x>
<y>80</y>
<width>511</width>
<height>101</height>
</rect>
</property>
<property name="font">
<font>
<weight>75</weight>
<bold>true</bold>
</font>
</property>
<property name="title">
<string>Tester mon eligibilite :</string>
</property>
<property name="alignment">
<set>Qt::AlignCenter</set>
</property>
<widget class="QWidget" name="gridLayoutWidget">
<property name="geometry">
<rect>
<x>10</x>
<y>19</y>
<width>491</width>
<height>71</height>
</rect>
</property>
<layout class="QGridLayout" name="gridLayout">
<item row="0" column="0">
<spacer name="horizontalSpacer">
<property name="orientation">
<enum>Qt::Horizontal</enum>
</property>
<property name="sizeHint" stdset="0">
<size>
<width>40</width>
<height>20</height>
</size>
</property>
</spacer>
</item>
<item row="0" column="1">
<widget class="QCheckBox" name="checkBox">
<property name="enabled">
<bool>false</bool>
</property>
<property name="text">
<string>Compte</string>
</property>
</widget>
</item>
<item row="0" column="2">
<spacer name="horizontalSpacer_2">
<property name="orientation">
<enum>Qt::Horizontal</enum>
</property>
<property name="sizeHint" stdset="0">
<size>
<width>40</width>
<height>20</height>
</size>
</property>
</spacer>
</item>
<item row="1" column="1">
<widget class="QCheckBox" name="checkBox_2">
<property name="enabled">
<bool>false</bool>
</property>
<property name="text">
<string>Couche</string>
</property>
</widget>
</item>
</layout>
</widget>
</widget>
<widget class="QWidget" name="horizontalLayoutWidget">
<property name="geometry">
<rect>
<x>10</x>
<y>40</y>
<width>511</width>
<height>31</height>
</rect>
</property>
<layout class="QHBoxLayout" name="horizontalLayout">
<item>
<widget class="QLabel" name="schema_label">
<property name="maximumSize">
<size>
<width>90</width>
<height>16777215</height>
</size>
</property>
<property name="text">
<string>Code analytique :</string>
</property>
</widget>
</item>
<item>
<widget class="QComboBox" name="schema"/>
</item>
</layout>
</widget>
<widget class="QGroupBox" name="groupBox_3">
<property name="geometry">
<rect>
<x>10</x>
<y>180</y>
<width>511</width>
<height>151</height>
</rect>
</property>
<property name="font">
<font>
<weight>75</weight>
<bold>true</bold>
</font>
</property>
<property name="title">
<string>Les changement :</string>
</property>
<property name="alignment">
<set>Qt::AlignCenter</set>
</property>
<widget class="QWidget" name="gridLayoutWidget_2">
<property name="geometry">
<rect>
<x>10</x>
<y>20</y>
<width>491</width>
<height>61</height>
</rect>
</property>
<layout class="QGridLayout" name="gridLayout_2">
<item row="1" column="0">
<widget class="QLabel" name="label_2">
<property name="font">
<font>
<weight>50</weight>
<bold>false</bold>
</font>
</property>
<property name="text">
<string>Nouvau nom :</string>
</property>
</widget>
</item>
<item row="0" column="0">
<widget class="QLabel" name="label">
<property name="font">
<font>
<weight>50</weight>
<bold>false</bold>
</font>
</property>
<property name="text">
<string>Partie renome :</string>
</property>
</widget>
</item>
<item row="0" column="1">
<widget class="QLineEdit" name="old_name">
<property name="enabled">
<bool>false</bool>
</property>
<property name="font">
<font>
<weight>75</weight>
<italic>true</italic>
<bold>true</bold>
</font>
</property>
</widget>
</item>
<item row="1" column="1">
<widget class="QLineEdit" name="new_name"/>
</item>
</layout>
</widget>
<widget class="QWidget" name="gridLayoutWidget_3">
<property name="geometry">
<rect>
<x>10</x>
<y>80</y>
<width>491</width>
<height>61</height>
</rect>
</property>
<layout class="QGridLayout" name="gridLayout_3">
<item row="0" column="0">
<widget class="QLabel" name="label_3">
<property name="maximumSize">
<size>
<width>130</width>
<height>16777215</height>
</size>
</property>
<property name="font">
<font>
<weight>50</weight>
<bold>false</bold>
</font>
</property>
<property name="text">
<string>Département/Animation :</string>
</property>
</widget>
</item>
<item row="0" column="2">
<widget class="QRadioButton" name="animation">
<property name="text">
<string>Animation territoriale</string>
</property>
</widget>
</item>
<item row="0" column="1">
<widget class="QComboBox" name="departement"/>
</item>
</layout>
</widget>
</widget>
</widget>
<resources/>
<connections>
<connection>
<sender>buttonBox</sender>
<signal>accepted()</signal>
<receiver>table_postgis</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>table_postgis</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>

View File

@ -1,8 +1,8 @@
<?xml version = '1.0' encoding = 'UTF-8'?>
<plugins>
<pyqgis_plugin name="CenRa_POSTGIS" version="2.5">
<pyqgis_plugin name="CenRa_POSTGIS" version="2.6">
<description><![CDATA[Dépôt pour les extensiont QGIS du CEN Rhone-Alpes, sur GitHub.]]></description>
<version>2.5</version>
<version>2.6</version>
<qgis_minimum_version>3.16</qgis_minimum_version>
<homepage>https://plateformesig.cenra-outils.org/</homepage>
<file_name>CenRa_POSTGIS.zip</file_name>
@ -11,7 +11,7 @@
<download_url>https://gitea.cenra-outils.org/CEN-RA/Plugin_QGIS/releases/download/latest/CenRa_POSTGIS.zip</download_url>
<uploaded_by>CEN-Rhone-Alpes</uploaded_by>
<create_date>2024-02-06</create_date>
<update_date>2025-02-04</update_date>
<update_date>2025-02-12</update_date>
<experimental>False</experimental>
<deprecated>False</deprecated>
<tags>cenra,postgis</tags>