Skip to content

Commit 665dfc8

Browse files
committed
[SqlAlchemy 1.4] compat sqlalchemy 1.4
1 parent 24e4e2f commit 665dfc8

37 files changed

+730
-678
lines changed

.github/workflows/pytest.yml

Lines changed: 0 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -26,10 +26,6 @@ jobs:
2626
fail-fast: false
2727
matrix:
2828
include:
29-
- name: "Debian 10"
30-
python-version: "3.7"
31-
postgres-version: 11
32-
postgis-version: 2.5
3329
- name: "Debian 11"
3430
python-version: "3.9"
3531
postgres-version: 13

backend/gn_module_monitoring/command/cmd.py

Lines changed: 13 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,7 @@
44

55
from pathlib import Path
66
from flask.cli import with_appcontext
7-
from sqlalchemy.sql import text
7+
from sqlalchemy.sql import text, select
88

99
from geonature.utils.env import DB, BACKEND_DIR
1010
from geonature.core.gn_synthese.models import TSources
@@ -15,7 +15,7 @@
1515
from ..monitoring.models import TMonitoringModules
1616
from ..config.repositories import get_config
1717
from ..config.utils import json_from_file, monitoring_module_config_path
18-
from ..modules.repositories import get_module, get_simple_module
18+
from ..modules.repositories import get_simple_module
1919

2020
from .utils import (
2121
process_export_csv,
@@ -145,15 +145,15 @@ def cmd_install_monitoring_module(module_code):
145145
if (module_config_dir_path / "synthese.sql").exists:
146146
click.secho("Execution du script synthese.sql")
147147
sql_script = module_config_dir_path / "synthese.sql"
148+
txt = (
149+
Path(sql_script)
150+
.read_text()
151+
.replace(":'module_code'", "'{}'".format(module_code))
152+
.replace(":module_code", "{}".format(module_code))
153+
)
148154
try:
149-
DB.engine.execute(
150-
text(
151-
open(sql_script, "r")
152-
.read()
153-
.replace(":'module_code'", "'{}'".format(module_code))
154-
.replace(":module_code", "{}".format(module_code))
155-
).execution_options(autocommit=True)
156-
)
155+
DB.session.execute(text(txt))
156+
DB.session.commit()
157157
except Exception as e:
158158
print(e)
159159
click.secho("Erreur dans le script synthese.sql", fg="red")
@@ -238,7 +238,9 @@ def synchronize_synthese(module_code, offset):
238238
Synchronise les données d'un module dans la synthese
239239
"""
240240
click.secho(f"Start synchronize data for module {module_code} ...", fg="green")
241-
module = TModules.query.filter_by(module_code=module_code).one()
241+
module = DB.session.execute(
242+
select(TModules).where(TModules.module_code == module_code)
243+
).scalar_one()
242244
table_name = "v_synthese_{}".format(module_code)
243245
import_from_table(
244246
"gn_monitoring",

backend/gn_module_monitoring/command/utils.py

Lines changed: 60 additions & 48 deletions
Original file line numberDiff line numberDiff line change
@@ -2,12 +2,19 @@
22
from pathlib import Path
33

44
from flask import current_app
5-
from sqlalchemy import and_, text
5+
from sqlalchemy import and_, text, delete, select
66
from sqlalchemy.exc import IntegrityError
77
from sqlalchemy.orm.exc import NoResultFound
88

9+
from sqlalchemy.dialects.postgresql import insert as pg_insert
10+
911
from geonature.utils.env import DB, BACKEND_DIR
10-
from geonature.core.gn_permissions.models import PermObject, PermissionAvailable, PermAction
12+
from geonature.core.gn_permissions.models import (
13+
PermObject,
14+
PermissionAvailable,
15+
PermAction,
16+
cor_object_module,
17+
)
1118
from geonature.core.gn_commons.models import TModules
1219

1320
from pypnnomenclature.models import TNomenclatures, BibNomenclaturesTypes
@@ -73,13 +80,10 @@ def process_export_csv(module_code=None):
7380
for f in files:
7481
if not f.endswith(".sql"):
7582
continue
76-
83+
txt = Path(Path(root) / Path(f)).read_text()
7784
try:
78-
DB.engine.execute(
79-
text(open(Path(root) / f, "r").read())
80-
.execution_options(autocommit=True)
81-
.bindparams(module_code=module_code)
82-
)
85+
DB.session.execute(text(txt).bindparams(module_code=module_code))
86+
DB.session.commit()
8387
print("{} - export csv file : {}".format(module_code, f))
8488

8589
except Exception as e:
@@ -119,37 +123,41 @@ def insert_module_available_permissions(module_code, perm_object_code, session):
119123
print(f"L'object {perm_object_code} n'est pas traité")
120124

121125
try:
122-
module = session.query(TModules).filter_by(module_code=module_code).one()
126+
module = session.scalars(select(TModules).where(TModules.module_code == module_code)).one()
123127
except NoResultFound:
124128
print(f"Le module {module_code} n'est pas présent")
125129
return
126130

127131
try:
128-
perm_object = session.query(PermObject).filter_by(code_object=perm_object_code).one()
132+
perm_object = session.execute(
133+
select(PermObject).where(PermObject.code_object == perm_object_code)
134+
).scalar_one_or_none()
129135
except NoResultFound:
130136
print(f"L'object de permission {perm_object_code} n'est pas présent")
131137
return
132138

133-
txt_cor_object_module = f"""
134-
INSERT INTO gn_permissions.cor_object_module(
135-
id_module,
136-
id_object
137-
)
138-
VALUES({module.id_module}, {perm_object.id_object})
139-
ON CONFLICT DO NOTHING
140-
"""
141-
session.execute(txt_cor_object_module)
139+
stmt = (
140+
pg_insert(cor_object_module)
141+
.values(id_module=module.id_module, id_object=perm_object.id_object)
142+
.on_conflict_do_nothing()
143+
)
144+
session.execute(stmt)
145+
session.commit()
142146

143147
# Création d'une permission disponible pour chaque action
144148
object_actions = PERMISSION_LABEL.get(perm_object_code)["actions"]
145149
for action in object_actions:
146-
permaction = session.query(PermAction).filter_by(code_action=action).one()
150+
permaction = session.execute(
151+
select(PermAction).where(PermAction.code_action == action)
152+
).scalar_one()
147153
try:
148-
perm = (
149-
session.query(PermissionAvailable)
150-
.filter_by(module=module, object=perm_object, action=permaction)
151-
.one()
152-
)
154+
perm = session.execute(
155+
select(PermissionAvailable).where(
156+
PermissionAvailable.module == module,
157+
PermissionAvailable.object == perm_object,
158+
PermissionAvailable.action == permaction,
159+
)
160+
).scalar_one()
153161
except NoResultFound:
154162
perm = PermissionAvailable(
155163
module=module,
@@ -171,13 +179,14 @@ def remove_monitoring_module(module_code):
171179
# remove module in db
172180
try:
173181
# suppression des permissions disponibles pour ce module
174-
txt = f"DELETE FROM gn_permissions.t_permissions_available WHERE id_module = {module.id_module}"
175-
DB.engine.execution_options(autocommit=True).execute(txt)
182+
# txt = f"DELETE FROM gn_permissions.t_permissions_available WHERE id_module = {module.id_module}"
183+
stmt = delete(PermissionAvailable).where(PermissionAvailable.id_module == module.id_module)
176184

177-
# HACK pour le moment suppresion avec un sql direct
178-
# Car il y a un soucis de delete cascade dans les modèles sqlalchemy
179-
txt = f"""DELETE FROM gn_commons.t_modules WHERE id_module ={module.id_module}"""
180-
DB.engine.execution_options(autocommit=True).execute(txt)
185+
DB.session.execute(stmt)
186+
187+
stmt = delete(TModules).where(TModules.id_module == module.id_module)
188+
DB.session.execute(stmt)
189+
DB.session.commit()
181190
except IntegrityError:
182191
print("Impossible de supprimer le module car il y a des données associées")
183192
return
@@ -214,11 +223,11 @@ def add_nomenclature(module_code):
214223
for data in nomenclature.get("types", []):
215224
nomenclature_type = None
216225
try:
217-
nomenclature_type = (
218-
DB.session.query(BibNomenclaturesTypes)
219-
.filter(data.get("mnemonique") == BibNomenclaturesTypes.mnemonique)
220-
.one()
221-
)
226+
nomenclature_type = DB.session.execute(
227+
select(BibNomenclaturesTypes).where(
228+
data.get("mnemonique") == BibNomenclaturesTypes.mnemonique
229+
)
230+
).scalar_one()
222231

223232
except Exception:
224233
pass
@@ -239,19 +248,18 @@ def add_nomenclature(module_code):
239248
for data in nomenclature["nomenclatures"]:
240249
nomenclature = None
241250
try:
242-
nomenclature = (
243-
DB.session.query(TNomenclatures)
251+
nomenclature = DB.session.execute(
252+
select(TNomenclatures)
244253
.join(
245254
BibNomenclaturesTypes, BibNomenclaturesTypes.id_type == TNomenclatures.id_type
246255
)
247-
.filter(
256+
.where(
248257
and_(
249258
data.get("cd_nomenclature") == TNomenclatures.cd_nomenclature,
250259
data.get("type") == BibNomenclaturesTypes.mnemonique,
251260
)
252261
)
253-
.one()
254-
)
262+
).scalar_one()
255263

256264
except Exception as e:
257265
pass
@@ -266,14 +274,13 @@ def add_nomenclature(module_code):
266274
continue
267275

268276
id_type = None
269-
270277
try:
271-
id_type = (
272-
DB.session.query(BibNomenclaturesTypes.id_type)
273-
.filter(BibNomenclaturesTypes.mnemonique == data["type"])
274-
.one()
275-
)[0]
276-
except Exception:
278+
id_type = DB.session.execute(
279+
select(BibNomenclaturesTypes.id_type).where(
280+
BibNomenclaturesTypes.mnemonique == data["type"]
281+
)
282+
).scalar_one()
283+
except Exception as e:
277284
pass
278285

279286
if not id_type:
@@ -295,6 +302,11 @@ def add_nomenclature(module_code):
295302
nomenclature = TNomenclatures(**data)
296303
DB.session.add(nomenclature)
297304
DB.session.commit()
305+
print(
306+
"nomenclature {} - {} added".format(
307+
nomenclature.cd_nomenclature, nomenclature.label_default
308+
)
309+
)
298310

299311

300312
def installed_modules(session=None):

backend/gn_module_monitoring/config/data_utils.py

Lines changed: 0 additions & 65 deletions
This file was deleted.

backend/gn_module_monitoring/config/repositories.py

Lines changed: 0 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -162,7 +162,6 @@ def get_config(module_code=None, force=False, customSpecConfig=None):
162162
return config
163163

164164
module = get_monitoring_module(module_code)
165-
166165
# derniere modification
167166
# fichiers
168167
# file_last_modif = get_directory_last_modif(monitoring_config_path())
@@ -193,7 +192,6 @@ def get_config(module_code=None, force=False, customSpecConfig=None):
193192
var_name = "__MODULE.{}".format(field_name.upper())
194193
config["custom"][var_name] = getattr(module, field_name)
195194
config["module"][field_name] = getattr(module, field_name)
196-
197195
config["custom"]["__MONITORINGS_PATH"] = get_monitorings_path()
198196

199197
config["default_display_field_names"].update(config.get("display_field_names", {}))

backend/gn_module_monitoring/config/utils.py

Lines changed: 12 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,8 @@
33
from pathlib import Path
44
import json
55

6-
from sqlalchemy import and_
6+
from sqlalchemy import and_, select
7+
from sqlalchemy.exc import NoResultFound
78

89
from geonature.core.gn_commons.models import BibTablesLocation, TModules
910
from geonature.utils.errors import GeoNatureError
@@ -35,21 +36,16 @@ def get_monitoring_module(module_code):
3536
if module_code == "generic":
3637
return None
3738

38-
res = (
39-
DB.session.query(TMonitoringModules)
40-
.filter(TMonitoringModules.module_code == module_code)
41-
.all()
42-
)
43-
44-
return res[0] if len(res) else None
39+
return DB.session.execute(
40+
select(TMonitoringModules).where(TMonitoringModules.module_code == module_code)
41+
).scalar_one_or_none()
4542

4643

4744
def get_monitorings_path():
48-
return (
49-
DB.session.query(TModules.module_path)
50-
.filter(TModules.module_code == "MONITORINGS")
51-
.one()[0]
52-
)
45+
module = DB.session.execute(
46+
select(TModules.module_path).where(TModules.module_code == "MONITORINGS")
47+
).scalar_one()
48+
return module
5349

5450

5551
def get_base_last_modif(module):
@@ -88,16 +84,14 @@ def get_id_table_location(object_type):
8884
id_table_location = None
8985

9086
try:
91-
id_table_location = (
92-
DB.session.query(BibTablesLocation.id_table_location)
93-
.filter(
87+
id_table_location = DB.session.execute(
88+
select(BibTablesLocation.id_table_location).where(
9489
and_(
9590
BibTablesLocation.schema_name == schema_name,
9691
BibTablesLocation.table_name == table_name,
9792
)
9893
)
99-
.one()
100-
)[0]
94+
).scalar_one()
10195
except Exception as e:
10296
print(schema_name, table_name, e)
10397
pass

0 commit comments

Comments
 (0)