querycraft 2.2.0__tar.gz → 2.4.0__tar.gz
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- {querycraft-2.2.0/querycraft.egg-info → querycraft-2.4.0}/PKG-INFO +1 -1
- {querycraft-2.2.0 → querycraft-2.4.0}/querycraft/LLM.py +6 -2
- {querycraft-2.2.0 → querycraft-2.4.0}/querycraft/SQLException.py +3 -3
- querycraft-2.4.0/querycraft/__init__.py +2 -0
- {querycraft-2.2.0 → querycraft-2.4.0}/querycraft/config/codemata.json +1 -1
- {querycraft-2.2.0 → querycraft-2.4.0}/querycraft/configmanager.py +12 -10
- querycraft-2.4.0/querycraft/database/__init__.py +228 -0
- {querycraft-2.2.0 → querycraft-2.4.0}/querycraft/database/base.py +3 -1
- {querycraft-2.2.0 → querycraft-2.4.0}/querycraft/exercicemanager.py +47 -0
- {querycraft-2.2.0 → querycraft-2.4.0}/querycraft/sql/SQLExecutionService.py +21 -10
- {querycraft-2.2.0 → querycraft-2.4.0}/querycraft/sql/SQLQueryService.py +17 -7
- {querycraft-2.2.0 → querycraft-2.4.0}/querycraft/sql/SQLStepByStepService.py +3 -3
- {querycraft-2.2.0 → querycraft-2.4.0}/querycraft/sqlsbs.py +9 -9
- {querycraft-2.2.0 → querycraft-2.4.0}/querycraft/templates/config.html +10 -6
- {querycraft-2.2.0 → querycraft-2.4.0}/querycraft/templates/index.html +3 -3
- {querycraft-2.2.0 → querycraft-2.4.0}/querycraft/web_sbs.py +35 -12
- {querycraft-2.2.0 → querycraft-2.4.0/querycraft.egg-info}/PKG-INFO +1 -1
- {querycraft-2.2.0 → querycraft-2.4.0}/test/testAnthropic.py +119 -68
- {querycraft-2.2.0 → querycraft-2.4.0}/test/test_exercicemanager.py +34 -0
- querycraft-2.2.0/querycraft/__init__.py +0 -2
- querycraft-2.2.0/querycraft/database/__init__.py +0 -87
- {querycraft-2.2.0 → querycraft-2.4.0}/AUTHORS +0 -0
- {querycraft-2.2.0 → querycraft-2.4.0}/LICENSE +0 -0
- {querycraft-2.2.0 → querycraft-2.4.0}/MANIFEST.in +0 -0
- {querycraft-2.2.0 → querycraft-2.4.0}/README.md +0 -0
- {querycraft-2.2.0 → querycraft-2.4.0}/querycraft/LLM_providers.py +0 -0
- {querycraft-2.2.0 → querycraft-2.4.0}/querycraft/LRS.py +0 -0
- {querycraft-2.2.0 → querycraft-2.4.0}/querycraft/PlantUML.py +0 -0
- {querycraft-2.2.0 → querycraft-2.4.0}/querycraft/cache/readme.txt +0 -0
- {querycraft-2.2.0 → querycraft-2.4.0}/querycraft/cachemanager.py +0 -0
- {querycraft-2.2.0 → querycraft-2.4.0}/querycraft/config/config-sbs-std.cfg +0 -0
- {querycraft-2.2.0 → querycraft-2.4.0}/querycraft/config/config-sbs.cfg +0 -0
- {querycraft-2.2.0 → querycraft-2.4.0}/querycraft/data/cinema.db +0 -0
- {querycraft-2.2.0 → querycraft-2.4.0}/querycraft/data/cours.db +0 -0
- {querycraft-2.2.0 → querycraft-2.4.0}/querycraft/data/em.db +0 -0
- {querycraft-2.2.0 → querycraft-2.4.0}/querycraft/data/entreprise.db +0 -0
- {querycraft-2.2.0 → querycraft-2.4.0}/querycraft/data/librairie.db +0 -0
- {querycraft-2.2.0 → querycraft-2.4.0}/querycraft/data/lutins.db +0 -0
- {querycraft-2.2.0 → querycraft-2.4.0}/querycraft/data/robots.db +0 -0
- {querycraft-2.2.0 → querycraft-2.4.0}/querycraft/data/vols.db +0 -0
- {querycraft-2.2.0 → querycraft-2.4.0}/querycraft/database/MYSQL.py +0 -0
- {querycraft-2.2.0 → querycraft-2.4.0}/querycraft/database/PGSQL.py +0 -0
- {querycraft-2.2.0 → querycraft-2.4.0}/querycraft/database/SQLITE.py +0 -0
- {querycraft-2.2.0 → querycraft-2.4.0}/querycraft/exceptions/OperationNotSupportedException.py +0 -0
- {querycraft-2.2.0 → querycraft-2.4.0}/querycraft/exceptions/__init__.py +0 -0
- {querycraft-2.2.0 → querycraft-2.4.0}/querycraft/exos/Didapro11.json +0 -0
- {querycraft-2.2.0 → querycraft-2.4.0}/querycraft/exos/OENU2026.json +0 -0
- {querycraft-2.2.0 → querycraft-2.4.0}/querycraft/exos/ex1.json +0 -0
- {querycraft-2.2.0 → querycraft-2.4.0}/querycraft/exos/exos1.json +0 -0
- {querycraft-2.2.0 → querycraft-2.4.0}/querycraft/exos/readme.txt +0 -0
- {querycraft-2.2.0 → querycraft-2.4.0}/querycraft/logger.py +0 -0
- {querycraft-2.2.0 → querycraft-2.4.0}/querycraft/logs/readme.txt +0 -0
- {querycraft-2.2.0 → querycraft-2.4.0}/querycraft/output/__init__.py +0 -0
- {querycraft-2.2.0 → querycraft-2.4.0}/querycraft/output/cli/CliOutputFactory.py +0 -0
- {querycraft-2.2.0 → querycraft-2.4.0}/querycraft/output/cli/__init__.py +0 -0
- {querycraft-2.2.0 → querycraft-2.4.0}/querycraft/output/cli/outputBuilder/CliCodeBuilder.py +0 -0
- {querycraft-2.2.0 → querycraft-2.4.0}/querycraft/output/cli/outputBuilder/CliListBuilder.py +0 -0
- {querycraft-2.2.0 → querycraft-2.4.0}/querycraft/output/cli/outputBuilder/CliParagraphBuilder.py +0 -0
- {querycraft-2.2.0 → querycraft-2.4.0}/querycraft/output/cli/outputBuilder/CliTableBuilder.py +0 -0
- {querycraft-2.2.0 → querycraft-2.4.0}/querycraft/output/cli/outputBuilder/CliTextBuilder.py +0 -0
- {querycraft-2.2.0 → querycraft-2.4.0}/querycraft/output/cli/outputBuilder/CliTitleBuilder.py +0 -0
- {querycraft-2.2.0 → querycraft-2.4.0}/querycraft/output/cli/outputBuilder/__init__.py +0 -0
- {querycraft-2.2.0 → querycraft-2.4.0}/querycraft/output/commons/OutputBuilder.py +0 -0
- {querycraft-2.2.0 → querycraft-2.4.0}/querycraft/output/commons/OutputCodeFactory.py +0 -0
- {querycraft-2.2.0 → querycraft-2.4.0}/querycraft/output/commons/OutputFactory.py +0 -0
- {querycraft-2.2.0 → querycraft-2.4.0}/querycraft/output/commons/OutputListBuilder.py +0 -0
- {querycraft-2.2.0 → querycraft-2.4.0}/querycraft/output/commons/OutputParagraphFactory.py +0 -0
- {querycraft-2.2.0 → querycraft-2.4.0}/querycraft/output/commons/OutputTableBuilder.py +0 -0
- {querycraft-2.2.0 → querycraft-2.4.0}/querycraft/output/commons/SimpleOutputBuilder.py +0 -0
- {querycraft-2.2.0 → querycraft-2.4.0}/querycraft/output/commons/__init__.py +0 -0
- {querycraft-2.2.0 → querycraft-2.4.0}/querycraft/output/commons/utils.py +0 -0
- {querycraft-2.2.0 → querycraft-2.4.0}/querycraft/output/html/HtmlOutputFactory.py +0 -0
- {querycraft-2.2.0 → querycraft-2.4.0}/querycraft/output/html/__init__.py +0 -0
- {querycraft-2.2.0 → querycraft-2.4.0}/querycraft/output/html/outputBuilder/HTMLCodeBuilder.py +0 -0
- {querycraft-2.2.0 → querycraft-2.4.0}/querycraft/output/html/outputBuilder/HTMLListBuilder.py +0 -0
- {querycraft-2.2.0 → querycraft-2.4.0}/querycraft/output/html/outputBuilder/HTMLParagraphBuilder.py +0 -0
- {querycraft-2.2.0 → querycraft-2.4.0}/querycraft/output/html/outputBuilder/HTMLTableBuilder.py +0 -0
- {querycraft-2.2.0 → querycraft-2.4.0}/querycraft/output/html/outputBuilder/HTMLTextBuilder.py +0 -0
- {querycraft-2.2.0 → querycraft-2.4.0}/querycraft/output/html/outputBuilder/HTMLTitleBuilder.py +0 -0
- {querycraft-2.2.0 → querycraft-2.4.0}/querycraft/output/html/outputBuilder/__init__.py +0 -0
- {querycraft-2.2.0 → querycraft-2.4.0}/querycraft/output/markdown/MarkdownOutputFactory.py +0 -0
- {querycraft-2.2.0 → querycraft-2.4.0}/querycraft/output/markdown/__init__.py +0 -0
- {querycraft-2.2.0 → querycraft-2.4.0}/querycraft/output/markdown/outputBuilder/MarkdownCodeBuilder.py +0 -0
- {querycraft-2.2.0 → querycraft-2.4.0}/querycraft/output/markdown/outputBuilder/MarkdownListBuilder.py +0 -0
- {querycraft-2.2.0 → querycraft-2.4.0}/querycraft/output/markdown/outputBuilder/MarkdownParagraphBuilder.py +0 -0
- {querycraft-2.2.0 → querycraft-2.4.0}/querycraft/output/markdown/outputBuilder/MarkdownTableBuilder.py +0 -0
- {querycraft-2.2.0 → querycraft-2.4.0}/querycraft/output/markdown/outputBuilder/MarkdownTextBuilder.py +0 -0
- {querycraft-2.2.0 → querycraft-2.4.0}/querycraft/output/markdown/outputBuilder/MarkdownTitleBuilder.py +0 -0
- {querycraft-2.2.0 → querycraft-2.4.0}/querycraft/output/markdown/outputBuilder/__init__.py +0 -0
- {querycraft-2.2.0 → querycraft-2.4.0}/querycraft/paths.py +0 -0
- {querycraft-2.2.0 → querycraft-2.4.0}/querycraft/security.py +0 -0
- {querycraft-2.2.0 → querycraft-2.4.0}/querycraft/sql/SQLContext.py +0 -0
- {querycraft-2.2.0 → querycraft-2.4.0}/querycraft/sql/SQLNormalizationService.py +0 -0
- {querycraft-2.2.0 → querycraft-2.4.0}/querycraft/sql/__init__.py +0 -0
- {querycraft-2.2.0 → querycraft-2.4.0}/querycraft/static/qc-0973b307dafc25e2b7a5f12be0f68d1786cedbf5ad0371c3f3d5f051fc00b626.puml +0 -0
- {querycraft-2.2.0 → querycraft-2.4.0}/querycraft/static/qc-18be2287f8920a2975f21fe98022750b27c222b85ac8d6de95a686835f147e9e.puml +0 -0
- {querycraft-2.2.0 → querycraft-2.4.0}/querycraft/static/qc-3d819e30e542ba328af562eb160d23140f2193d92354b0897289767e1c041e96.puml +0 -0
- {querycraft-2.2.0 → querycraft-2.4.0}/querycraft/static/qc-54c49d1ad35ea5cf736dfd64c3ed9c42ea90d7b82a5f3783f73f46de99bf0987.puml +0 -0
- {querycraft-2.2.0 → querycraft-2.4.0}/querycraft/static/qc-5b552498722250bebfe20f44257243a9f9e08d2f3865955c60f4469ff1c12fea.puml +0 -0
- {querycraft-2.2.0 → querycraft-2.4.0}/querycraft/static/qc-a70191192c2a1640bfec39afd281537d4ede20bb5c9e87ccb32b883e1e58bcab.puml +0 -0
- {querycraft-2.2.0 → querycraft-2.4.0}/querycraft/static/qc-d1881606867eea2d5f0cf600fa342f8e04e8d5cc388946a09cffb855052b22ad.puml +0 -0
- {querycraft-2.2.0 → querycraft-2.4.0}/querycraft/static/qc-eb48d0ac9258e52c7715e6313b6da064ed9ab2efab6ba7b3225b9568a3c2545e.puml +0 -0
- {querycraft-2.2.0 → querycraft-2.4.0}/querycraft/templates/admin_login.html +0 -0
- {querycraft-2.2.0 → querycraft-2.4.0}/querycraft/templates/base.html +0 -0
- {querycraft-2.2.0 → querycraft-2.4.0}/querycraft/templates/correction_prompt.md +0 -0
- {querycraft-2.2.0 → querycraft-2.4.0}/querycraft/templates/credits.html +0 -0
- {querycraft-2.2.0 → querycraft-2.4.0}/querycraft/templates/database_prompt.md +0 -0
- {querycraft-2.2.0 → querycraft-2.4.0}/querycraft/templates/didactique.md +0 -0
- {querycraft-2.2.0 → querycraft-2.4.0}/querycraft/templates/didapro11.html +0 -0
- {querycraft-2.2.0 → querycraft-2.4.0}/querycraft/templates/erreur_prompt.md +0 -0
- {querycraft-2.2.0 → querycraft-2.4.0}/querycraft/templates/exercices.html +0 -0
- {querycraft-2.2.0 → querycraft-2.4.0}/querycraft/templates/instance_error.html +0 -0
- {querycraft-2.2.0 → querycraft-2.4.0}/querycraft/templates/requete_prompt.md +0 -0
- {querycraft-2.2.0 → querycraft-2.4.0}/querycraft/templates/systeme_prompt.md +0 -0
- {querycraft-2.2.0 → querycraft-2.4.0}/querycraft/templates/systeme_prompt_factuel.md +0 -0
- {querycraft-2.2.0 → querycraft-2.4.0}/querycraft/templates/systeme_prompt_valideur.md +0 -0
- {querycraft-2.2.0 → querycraft-2.4.0}/querycraft/templates/valideur_prompt.md +0 -0
- {querycraft-2.2.0 → querycraft-2.4.0}/querycraft/tenantadmin.py +0 -0
- {querycraft-2.2.0 → querycraft-2.4.0}/querycraft/tenantlogging.py +0 -0
- {querycraft-2.2.0 → querycraft-2.4.0}/querycraft/tenantregistry.py +0 -0
- {querycraft-2.2.0 → querycraft-2.4.0}/querycraft/tools.py +0 -0
- {querycraft-2.2.0 → querycraft-2.4.0}/querycraft.egg-info/SOURCES.txt +0 -0
- {querycraft-2.2.0 → querycraft-2.4.0}/querycraft.egg-info/dependency_links.txt +0 -0
- {querycraft-2.2.0 → querycraft-2.4.0}/querycraft.egg-info/entry_points.txt +0 -0
- {querycraft-2.2.0 → querycraft-2.4.0}/querycraft.egg-info/requires.txt +0 -0
- {querycraft-2.2.0 → querycraft-2.4.0}/querycraft.egg-info/top_level.txt +0 -0
- {querycraft-2.2.0 → querycraft-2.4.0}/setup.cfg +0 -0
- {querycraft-2.2.0 → querycraft-2.4.0}/setup.py +0 -0
- {querycraft-2.2.0 → querycraft-2.4.0}/test/testLRS.py +0 -0
- {querycraft-2.2.0 → querycraft-2.4.0}/test/testOllama.py +0 -0
- {querycraft-2.2.0 → querycraft-2.4.0}/test/testParse.py +0 -0
- {querycraft-2.2.0 → querycraft-2.4.0}/test/test_litellm_provider.py +0 -0
|
@@ -80,6 +80,10 @@ class LLMService:
|
|
|
80
80
|
# Prompt système factuel (sans règles socratiques) : description du schéma
|
|
81
81
|
# et reformulation de l'objectif d'une requête
|
|
82
82
|
self.prompt_systeme_factuel = self.__build_prompt_contexte(bd, "systeme_prompt_factuel.md")
|
|
83
|
+
# Identifiant de la base cible, à préfixer aux clés de cache : deux bases
|
|
84
|
+
# différentes peuvent partager le même texte de requête/erreur soumis
|
|
85
|
+
# (cache_dir et cache_name sont communs à toute l'instance, pas par base).
|
|
86
|
+
self.db_key = f"{bd.getType()}-{bd.getDatabaseName()}"
|
|
83
87
|
|
|
84
88
|
def isAlive(self) -> bool:
|
|
85
89
|
"""Indique si le provider LLM est accessible."""
|
|
@@ -147,7 +151,7 @@ class LLMService:
|
|
|
147
151
|
requete=sql_attendu_escaped,
|
|
148
152
|
)
|
|
149
153
|
|
|
150
|
-
response: LLMResponse = self.__call_with_cache(prompt, f"{requete_soumise}{requete_attendue}", "err")
|
|
154
|
+
response: LLMResponse = self.__call_with_cache(prompt, f"{self.db_key}|{requete_soumise}{requete_attendue}", "err")
|
|
151
155
|
return self.format_ia(response, "Explication de l'erreur", self.typeOutput)
|
|
152
156
|
|
|
153
157
|
def analyse_requete(self, requete: str) -> OutputFactory:
|
|
@@ -158,7 +162,7 @@ class LLMService:
|
|
|
158
162
|
sql_attendu_escaped = escape_markdown(requete)
|
|
159
163
|
|
|
160
164
|
prompt = template.render(requete=sql_attendu_escaped)
|
|
161
|
-
response: LLMResponse = self.__call_with_cache(prompt, f"{requete}", "req", prompt_systeme=self.prompt_systeme_factuel)
|
|
165
|
+
response: LLMResponse = self.__call_with_cache(prompt, f"{self.db_key}|{requete}", "req", prompt_systeme=self.prompt_systeme_factuel)
|
|
162
166
|
return self.format_ia(response, "Explication et reformulation de la requête", self.typeOutput)
|
|
163
167
|
|
|
164
168
|
def analyse_exo_reponse(self, sql_soumis: str, sql_attendu: str, intention: str, question: Question,
|
|
@@ -41,12 +41,12 @@ class SQLQueryException(SQLException):
|
|
|
41
41
|
err: Message d'erreur
|
|
42
42
|
"""
|
|
43
43
|
|
|
44
|
-
def __init__(self,
|
|
44
|
+
def __init__(self, ia_demandee: bool, message: str, sqlhs: str, sqlok: str, sgbd: str, output: str = "text"):
|
|
45
45
|
"""
|
|
46
46
|
Initialise une exception de requête SQL avec message formaté.
|
|
47
47
|
|
|
48
48
|
Args:
|
|
49
|
-
|
|
49
|
+
ia_demandee: Aide de l'IA demandée par défaut pour cette instance.
|
|
50
50
|
message: Message d'erreur brut du SGBD
|
|
51
51
|
sqlhs: Requête SQL ayant provoqué l'erreur (str ou objet SQL)
|
|
52
52
|
sqlok: Requête SQL correcte de référence (ou None)
|
|
@@ -54,7 +54,7 @@ class SQLQueryException(SQLException):
|
|
|
54
54
|
output: Type de sortie pour le formatage ("text", "html", "md")
|
|
55
55
|
"""
|
|
56
56
|
super().__init__(message)
|
|
57
|
-
self.
|
|
57
|
+
self.ia_demandee = ia_demandee
|
|
58
58
|
self.sqlhs = sqlhs
|
|
59
59
|
self.sqlok = sqlok
|
|
60
60
|
if sqlok is None:
|
|
@@ -19,7 +19,7 @@ class Configuration:
|
|
|
19
19
|
def __init__(self, database: Database, llm_provider: LLMProvider, llm_validator, llm_service: LLMService,
|
|
20
20
|
normalization_service: SQLNormalizationService, execution_service: SQLExecutionService,
|
|
21
21
|
step_by_step_service: SQLStepByStepService, query_service: SQLQueryService, plant_uml: PlantUML,
|
|
22
|
-
lrs: LRS, type_output: TypeOutput, ia_mode: str, lrs_mode: str, debug: bool,
|
|
22
|
+
lrs: LRS, type_output: TypeOutput, ia_mode: str, lrs_mode: str, debug: bool, ia_demandee: bool,
|
|
23
23
|
cache: bool, duree_cache: int, exos: bool, aide: bool, max_rows: int,
|
|
24
24
|
exercice_service: ExerciceService, db_type: str = "", db_name: str = "", db_host: str = "",
|
|
25
25
|
db_port: str = "", db_username: str = "", db_password: str = "", ia_service: str = "",
|
|
@@ -46,7 +46,7 @@ class Configuration:
|
|
|
46
46
|
self.ia_mode = ia_mode
|
|
47
47
|
self.lrs_mode = lrs_mode
|
|
48
48
|
self.debug = debug
|
|
49
|
-
self.
|
|
49
|
+
self.ia_demandee = ia_demandee
|
|
50
50
|
self.cache = cache
|
|
51
51
|
self.duree_cache = duree_cache
|
|
52
52
|
self.exos = exos
|
|
@@ -124,7 +124,9 @@ class ConfigurationBuilder:
|
|
|
124
124
|
|
|
125
125
|
# [Autre]
|
|
126
126
|
self.debug: bool = raw.getboolean("Autre", "debug", fallback=False)
|
|
127
|
-
|
|
127
|
+
# La clé INI reste "verbose" (historique, CLI) ; l'attribut Python porte son
|
|
128
|
+
# vrai sens pour le reste du code : aide de l'IA demandée par défaut.
|
|
129
|
+
self.ia_demandee: bool = raw.getboolean("Autre", "verbose", fallback=True)
|
|
128
130
|
self.cache: bool = raw.get("Autre", "cache", fallback="on") == "on"
|
|
129
131
|
self.duree_cache: int = raw.getint("Autre", "duree-cache", fallback=60)
|
|
130
132
|
self.exos: bool = raw.get("Autre", "exos", fallback="off") == "on"
|
|
@@ -215,9 +217,9 @@ class ConfigurationBuilder:
|
|
|
215
217
|
self.debug = value
|
|
216
218
|
return self
|
|
217
219
|
|
|
218
|
-
def
|
|
220
|
+
def set_ia_demandee(self, value: bool | None) -> "ConfigurationBuilder":
|
|
219
221
|
if value is not None:
|
|
220
|
-
self.
|
|
222
|
+
self.ia_demandee = value
|
|
221
223
|
return self
|
|
222
224
|
|
|
223
225
|
def set_cache(self, value: bool | None) -> "ConfigurationBuilder":
|
|
@@ -311,16 +313,16 @@ class ConfigurationBuilder:
|
|
|
311
313
|
return SQLNormalizationService(db)
|
|
312
314
|
|
|
313
315
|
def buildSQLExecutionService(self, db: Database, normalizationService: SQLNormalizationService) -> SQLExecutionService:
|
|
314
|
-
return SQLExecutionService(db, normalizationService, self.
|
|
316
|
+
return SQLExecutionService(db, normalizationService, self.ia_demandee, self.debug, self.type_output)
|
|
315
317
|
|
|
316
318
|
def buildSQLStepByStepService(self, db: Database, executionService: SQLExecutionService, normalizationService: SQLNormalizationService) -> SQLStepByStepService:
|
|
317
|
-
return SQLStepByStepService(db, executionService, normalizationService, self.debug, self.
|
|
319
|
+
return SQLStepByStepService(db, executionService, normalizationService, self.debug, self.ia_demandee)
|
|
318
320
|
|
|
319
321
|
def buildSQLQueryService(self, db: Database, llm_service: LLMService, normalizer: SQLNormalizationService,
|
|
320
322
|
executionService: SQLExecutionService, stepByStepService: SQLStepByStepService,
|
|
321
323
|
exercice_service: ExerciceService) -> SQLQueryService:
|
|
322
324
|
return SQLQueryService(db, llm_service, normalizer, executionService, stepByStepService, exercice_service,
|
|
323
|
-
self.type_output, self.debug, self.
|
|
325
|
+
self.type_output, self.debug, self.ia_demandee, self.aide, self.ia_mode == "on")
|
|
324
326
|
|
|
325
327
|
def buildPlantUML(self, db: Database) -> PlantUML:
|
|
326
328
|
return PlantUML(db, images_dir=self._paths.images_dir)
|
|
@@ -398,7 +400,7 @@ class ConfigurationBuilder:
|
|
|
398
400
|
ia_mode=self.ia_mode,
|
|
399
401
|
lrs_mode=self.lrs_mode,
|
|
400
402
|
debug=self.debug,
|
|
401
|
-
|
|
403
|
+
ia_demandee=self.ia_demandee,
|
|
402
404
|
cache=self.cache,
|
|
403
405
|
duree_cache=self.duree_cache,
|
|
404
406
|
exos=self.exos,
|
|
@@ -540,7 +542,7 @@ class ConfigurationHelper:
|
|
|
540
542
|
},
|
|
541
543
|
"Autre": {
|
|
542
544
|
"debug": str(c.debug),
|
|
543
|
-
"verbose": str(c.
|
|
545
|
+
"verbose": str(c.ia_demandee),
|
|
544
546
|
"cache": "on" if c.cache else "off",
|
|
545
547
|
"duree-cache": str(c.duree_cache),
|
|
546
548
|
"exos": "on" if c.exos else "off",
|
|
@@ -0,0 +1,228 @@
|
|
|
1
|
+
from concurrent.futures import ThreadPoolExecutor
|
|
2
|
+
from configparser import ConfigParser
|
|
3
|
+
from typing import Literal
|
|
4
|
+
|
|
5
|
+
import mysql.connector
|
|
6
|
+
import psycopg2
|
|
7
|
+
|
|
8
|
+
from .base import Database
|
|
9
|
+
from .MYSQL import MYSQL
|
|
10
|
+
from .PGSQL import PGSQL
|
|
11
|
+
from .SQLITE import SQLITE
|
|
12
|
+
|
|
13
|
+
TypeDatabase = Literal["pgsql", "mysql", "sqlite"]
|
|
14
|
+
|
|
15
|
+
DEFAULT_HOST = "localhost"
|
|
16
|
+
DEFAULT_PORTS: dict[TypeDatabase, int] = {"pgsql": 5432, "mysql": 3306}
|
|
17
|
+
|
|
18
|
+
# Base d'amorçage utilisée pour lister les bases PostgreSQL disponibles sur un
|
|
19
|
+
# serveur (il faut être connecté à une base existante pour interroger pg_database).
|
|
20
|
+
_PGSQL_BOOTSTRAP_DB = "postgres"
|
|
21
|
+
_MYSQL_SYSTEM_SCHEMAS = {"information_schema", "performance_schema", "mysql", "sys"}
|
|
22
|
+
_PROBE_CONNECT_TIMEOUT = 3
|
|
23
|
+
_PROBE_MAX_WORKERS = 8
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
def _listDatabasesPgsql(dbhost: str, dbport: int, dbuser: str, dbpassword: str) -> dict:
|
|
27
|
+
"""Liste les bases PostgreSQL réellement accessibles à ``dbuser``.
|
|
28
|
+
|
|
29
|
+
Une connexion à ``pg_database`` ne donne que la liste brute des bases existantes,
|
|
30
|
+
pas celles auxquelles l'utilisateur peut réellement se connecter (privilège CONNECT
|
|
31
|
+
accordé à PUBLIC par défaut, pg_hba.conf restrictif par base, etc.). On teste donc
|
|
32
|
+
une connexion réelle à chaque base candidate, en parallèle.
|
|
33
|
+
"""
|
|
34
|
+
try:
|
|
35
|
+
bootstrap = psycopg2.connect(
|
|
36
|
+
dbname=_PGSQL_BOOTSTRAP_DB, user=dbuser, password=dbpassword,
|
|
37
|
+
host=dbhost, port=dbport, connect_timeout=_PROBE_CONNECT_TIMEOUT,
|
|
38
|
+
)
|
|
39
|
+
except psycopg2.Error as e:
|
|
40
|
+
return {"status": "error", "databases": [], "message": f"Connexion au serveur impossible : {e}"}
|
|
41
|
+
|
|
42
|
+
try:
|
|
43
|
+
with bootstrap.cursor() as cursor:
|
|
44
|
+
cursor.execute("SELECT datname FROM pg_database WHERE datistemplate = false ORDER BY datname")
|
|
45
|
+
candidates = [row[0] for row in cursor.fetchall()]
|
|
46
|
+
finally:
|
|
47
|
+
bootstrap.close()
|
|
48
|
+
|
|
49
|
+
def probe(name: str) -> tuple[str, bool]:
|
|
50
|
+
try:
|
|
51
|
+
conn = psycopg2.connect(
|
|
52
|
+
dbname=name, user=dbuser, password=dbpassword,
|
|
53
|
+
host=dbhost, port=dbport, connect_timeout=_PROBE_CONNECT_TIMEOUT,
|
|
54
|
+
)
|
|
55
|
+
conn.close()
|
|
56
|
+
return name, True
|
|
57
|
+
except psycopg2.Error:
|
|
58
|
+
return name, False
|
|
59
|
+
|
|
60
|
+
accessible = []
|
|
61
|
+
if candidates:
|
|
62
|
+
with ThreadPoolExecutor(max_workers=min(_PROBE_MAX_WORKERS, len(candidates))) as executor:
|
|
63
|
+
for name, ok in executor.map(probe, candidates):
|
|
64
|
+
if ok:
|
|
65
|
+
accessible.append(name)
|
|
66
|
+
|
|
67
|
+
return {
|
|
68
|
+
"status": "ok",
|
|
69
|
+
"databases": sorted(accessible),
|
|
70
|
+
"message": "" if accessible else "Connexion au serveur réussie, mais aucune base accessible.",
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
|
|
74
|
+
def _listDatabasesMysql(dbhost: str, dbport: int, dbuser: str, dbpassword: str) -> dict:
|
|
75
|
+
"""Liste les bases MySQL réellement accessibles à ``dbuser``.
|
|
76
|
+
|
|
77
|
+
SHOW DATABASES ne garantit pas que l'utilisateur puisse s'y connecter : un
|
|
78
|
+
privilège global (SHOW DATABASES, PROCESS, un SELECT large...) fait apparaître
|
|
79
|
+
des bases sans droit de connexion réel dessus. On teste donc, comme pour
|
|
80
|
+
PostgreSQL, une connexion réelle à chaque base candidate, en parallèle.
|
|
81
|
+
"""
|
|
82
|
+
try:
|
|
83
|
+
bootstrap = mysql.connector.connect(
|
|
84
|
+
user=dbuser, password=dbpassword, host=dbhost, port=dbport,
|
|
85
|
+
connection_timeout=_PROBE_CONNECT_TIMEOUT,
|
|
86
|
+
)
|
|
87
|
+
except mysql.connector.Error as e:
|
|
88
|
+
return {"status": "error", "databases": [], "message": f"Connexion au serveur impossible : {e}"}
|
|
89
|
+
|
|
90
|
+
try:
|
|
91
|
+
cursor = bootstrap.cursor()
|
|
92
|
+
cursor.execute("SHOW DATABASES")
|
|
93
|
+
candidates = [row[0] for row in cursor.fetchall() if row[0] not in _MYSQL_SYSTEM_SCHEMAS]
|
|
94
|
+
cursor.close()
|
|
95
|
+
finally:
|
|
96
|
+
bootstrap.close()
|
|
97
|
+
|
|
98
|
+
def probe(name: str) -> tuple[str, bool]:
|
|
99
|
+
try:
|
|
100
|
+
conn = mysql.connector.connect(
|
|
101
|
+
database=name, user=dbuser, password=dbpassword,
|
|
102
|
+
host=dbhost, port=dbport, connection_timeout=_PROBE_CONNECT_TIMEOUT,
|
|
103
|
+
)
|
|
104
|
+
conn.close()
|
|
105
|
+
return name, True
|
|
106
|
+
except mysql.connector.Error:
|
|
107
|
+
return name, False
|
|
108
|
+
|
|
109
|
+
accessible = []
|
|
110
|
+
if candidates:
|
|
111
|
+
with ThreadPoolExecutor(max_workers=min(_PROBE_MAX_WORKERS, len(candidates))) as executor:
|
|
112
|
+
for name, ok in executor.map(probe, candidates):
|
|
113
|
+
if ok:
|
|
114
|
+
accessible.append(name)
|
|
115
|
+
|
|
116
|
+
return {
|
|
117
|
+
"status": "ok",
|
|
118
|
+
"databases": sorted(accessible),
|
|
119
|
+
"message": "" if accessible else "Connexion au serveur réussie, mais aucune base accessible.",
|
|
120
|
+
}
|
|
121
|
+
|
|
122
|
+
|
|
123
|
+
class DatabaseProvider:
|
|
124
|
+
"""
|
|
125
|
+
Provider pour obtenir une instance de Database selon le type de SGBD.
|
|
126
|
+
"""
|
|
127
|
+
|
|
128
|
+
@staticmethod
|
|
129
|
+
def get(
|
|
130
|
+
type: TypeDatabase,
|
|
131
|
+
dbname: str,
|
|
132
|
+
dbhost: str = "",
|
|
133
|
+
dbport: int = 0,
|
|
134
|
+
dbuser: str = "",
|
|
135
|
+
dbpassword: str = "",
|
|
136
|
+
data_dir=None,
|
|
137
|
+
) -> Database:
|
|
138
|
+
"""
|
|
139
|
+
Retourne une instance de Database selon le type de SGBD.
|
|
140
|
+
|
|
141
|
+
Arguments:
|
|
142
|
+
type: Type de base de données ('pgsql', 'mysql' ou 'sqlite').
|
|
143
|
+
dbname: Nom de la base de données (ou chemin du fichier pour SQLite).
|
|
144
|
+
dbhost: Adresse de l'hôte (ignoré pour SQLite).
|
|
145
|
+
dbport: Port de connexion (ignoré pour SQLite).
|
|
146
|
+
dbuser: Nom d'utilisateur (ignoré pour SQLite).
|
|
147
|
+
dbpassword: Mot de passe (ignoré pour SQLite).
|
|
148
|
+
data_dir: Répertoire de données de l'instance (SQLite uniquement) où
|
|
149
|
+
chercher ``dbname`` s'il ne désigne pas déjà un fichier existant.
|
|
150
|
+
|
|
151
|
+
Returns:
|
|
152
|
+
Une instance de Database correspondant au type demandé.
|
|
153
|
+
|
|
154
|
+
Raises:
|
|
155
|
+
ValueError: Si le type de base de données n'est pas reconnu.
|
|
156
|
+
"""
|
|
157
|
+
match type:
|
|
158
|
+
case "pgsql" | "mysql":
|
|
159
|
+
effective_host = dbhost or DEFAULT_HOST
|
|
160
|
+
effective_port = dbport or DEFAULT_PORTS[type]
|
|
161
|
+
cls = PGSQL if type == "pgsql" else MYSQL
|
|
162
|
+
return cls(dbname, effective_host, effective_port, dbuser, dbpassword)
|
|
163
|
+
case "sqlite":
|
|
164
|
+
return SQLITE(dbname, data_dir)
|
|
165
|
+
case _:
|
|
166
|
+
raise ValueError(f"Type de base de données non reconnu : {type}")
|
|
167
|
+
|
|
168
|
+
@staticmethod
|
|
169
|
+
def listDatabases(
|
|
170
|
+
type: TypeDatabase,
|
|
171
|
+
dbhost: str = "",
|
|
172
|
+
dbport: int = 0,
|
|
173
|
+
dbuser: str = "",
|
|
174
|
+
dbpassword: str = "",
|
|
175
|
+
) -> dict:
|
|
176
|
+
"""
|
|
177
|
+
Sonde un serveur PostgreSQL ou MySQL et renvoie les bases réellement
|
|
178
|
+
accessibles avec les identifiants fournis.
|
|
179
|
+
|
|
180
|
+
Arguments:
|
|
181
|
+
type: Type de base de données ('pgsql' ou 'mysql' ; 'sqlite' n'est pas
|
|
182
|
+
concerné, les bases SQLite étant listées via le répertoire de l'instance).
|
|
183
|
+
dbhost: Adresse de l'hôte.
|
|
184
|
+
dbport: Port de connexion (0 pour utiliser le port par défaut du type).
|
|
185
|
+
dbuser: Nom d'utilisateur pour l'authentification.
|
|
186
|
+
dbpassword: Mot de passe pour l'authentification.
|
|
187
|
+
|
|
188
|
+
Returns:
|
|
189
|
+
Un dict {"status": "ok"|"missing_params"|"error", "databases": [...], "message": str}.
|
|
190
|
+
"""
|
|
191
|
+
if type not in ("pgsql", "mysql"):
|
|
192
|
+
return {"status": "error", "databases": [], "message": "Non applicable pour ce type de base."}
|
|
193
|
+
if not dbhost or not dbuser:
|
|
194
|
+
return {"status": "missing_params", "databases": [], "message": "Hôte et utilisateur requis."}
|
|
195
|
+
|
|
196
|
+
effective_port = dbport or DEFAULT_PORTS[type]
|
|
197
|
+
if type == "pgsql":
|
|
198
|
+
return _listDatabasesPgsql(dbhost, effective_port, dbuser, dbpassword)
|
|
199
|
+
return _listDatabasesMysql(dbhost, effective_port, dbuser, dbpassword)
|
|
200
|
+
|
|
201
|
+
@staticmethod
|
|
202
|
+
def getFromConfig(config: ConfigParser) -> Database:
|
|
203
|
+
"""
|
|
204
|
+
Retourne une instance de Database décrite dans la section [Database] de la config.
|
|
205
|
+
|
|
206
|
+
Arguments:
|
|
207
|
+
config: Instance de ConfigParser contenant une section [Database] avec les
|
|
208
|
+
clés : type, database, host, port, username, password.
|
|
209
|
+
|
|
210
|
+
Returns:
|
|
211
|
+
Une instance de Database correspondant à la configuration.
|
|
212
|
+
|
|
213
|
+
Raises:
|
|
214
|
+
ValueError: Si le type de base de données n'est pas reconnu.
|
|
215
|
+
"""
|
|
216
|
+
section = config["Database"]
|
|
217
|
+
|
|
218
|
+
return DatabaseProvider.get(
|
|
219
|
+
type=section.get("type", "sqlite").lower(),
|
|
220
|
+
dbname=section.get("database", ""),
|
|
221
|
+
dbhost=section.get("host", ""),
|
|
222
|
+
dbport=section.getint("port", 0),
|
|
223
|
+
dbuser=section.get("username", ""),
|
|
224
|
+
dbpassword=section.get("password", ""),
|
|
225
|
+
)
|
|
226
|
+
|
|
227
|
+
|
|
228
|
+
__all__ = ["Database", "TypeDatabase", "DatabaseProvider"]
|
|
@@ -138,7 +138,9 @@ class Database(AbstractContextManager):
|
|
|
138
138
|
if cursor.description is None:
|
|
139
139
|
cursor.close()
|
|
140
140
|
return []
|
|
141
|
-
description
|
|
141
|
+
# cursor.description[i][0] est le nom de colonne (seul champ utilisé) ; l'arité du
|
|
142
|
+
# reste du tuple varie selon le driver (7 éléments en PEP 249, 9 avec mysql-connector-python).
|
|
143
|
+
description = [col[0] for col in cursor.description]
|
|
142
144
|
results = cursor.fetchall()
|
|
143
145
|
cursor.close()
|
|
144
146
|
return list([description]) + [list(ligne) for ligne in results]
|
|
@@ -4,6 +4,10 @@ import re
|
|
|
4
4
|
from dataclasses import dataclass
|
|
5
5
|
from pathlib import Path
|
|
6
6
|
|
|
7
|
+
import sqlglot
|
|
8
|
+
from sqlglot import errors as sqlglot_errors
|
|
9
|
+
|
|
10
|
+
from querycraft.logger import get_logger
|
|
7
11
|
from querycraft.paths import InstancePaths
|
|
8
12
|
|
|
9
13
|
# Codes d'exercice autorisés : le code devient un nom de fichier, donc ni séparateur
|
|
@@ -11,6 +15,10 @@ from querycraft.paths import InstancePaths
|
|
|
11
15
|
# code fourni par l'utilisateur).
|
|
12
16
|
_CODE_RE = re.compile(r"^[A-Za-z0-9_-]{1,64}$")
|
|
13
17
|
|
|
18
|
+
# Correspondance entre le type de base QueryCraft (``TypeDatabase``) et le nom
|
|
19
|
+
# de dialecte attendu par sqlglot pour la transpilation des requêtes.
|
|
20
|
+
_SQLGLOT_DIALECT = {"pgsql": "postgres", "mysql": "mysql", "sqlite": "sqlite"}
|
|
21
|
+
|
|
14
22
|
|
|
15
23
|
@dataclass
|
|
16
24
|
class DatabaseRef:
|
|
@@ -69,6 +77,8 @@ class ExerciceService:
|
|
|
69
77
|
Format d'une question : [requete, intention, comment, type, instructions]
|
|
70
78
|
"""
|
|
71
79
|
|
|
80
|
+
_logger = get_logger(__name__)
|
|
81
|
+
|
|
72
82
|
def __init__(self, exos_dir: str | Path | None = None):
|
|
73
83
|
"""Initialise le service sur un répertoire d'exercices.
|
|
74
84
|
|
|
@@ -177,15 +187,52 @@ class ExerciceService:
|
|
|
177
187
|
def set_database(self, code: str, db: DatabaseRef | None) -> bool:
|
|
178
188
|
"""Associe une base à un exercice (ou la retire avec ``None``).
|
|
179
189
|
|
|
190
|
+
Si le type de SGBD change (ex. sqlite → pgsql), les requêtes des
|
|
191
|
+
questions sont automatiquement transposées vers le nouveau dialecte
|
|
192
|
+
(via sqlglot) pour rester exécutables sans intervention manuelle.
|
|
193
|
+
Une requête qui ne peut pas être transposée est laissée telle quelle.
|
|
194
|
+
|
|
180
195
|
Retourne False si l'exercice n'existe pas.
|
|
181
196
|
"""
|
|
182
197
|
data = self._load(code)
|
|
183
198
|
if data is None:
|
|
184
199
|
return False
|
|
200
|
+
old_ref = DatabaseRef.from_dict(data.get("database"))
|
|
201
|
+
if db is not None and old_ref is not None and old_ref.type != db.type:
|
|
202
|
+
data["questions"] = self._transpile_questions(
|
|
203
|
+
data.get("questions", {}), old_ref.type, db.type
|
|
204
|
+
)
|
|
185
205
|
data["database"] = db.to_dict() if db is not None else None
|
|
186
206
|
self._save(code, data)
|
|
187
207
|
return True
|
|
188
208
|
|
|
209
|
+
@classmethod
|
|
210
|
+
def _transpile_questions(cls, questions: dict, old_type: str, new_type: str) -> dict:
|
|
211
|
+
"""Transpose le SQL des requêtes de ``old_type`` vers ``new_type``.
|
|
212
|
+
|
|
213
|
+
Args:
|
|
214
|
+
questions: Dict brut {code_q: [requete, intention, comment, type, instructions]}.
|
|
215
|
+
old_type: Ancien type de SGBD (``TypeDatabase``).
|
|
216
|
+
new_type: Nouveau type de SGBD (``TypeDatabase``).
|
|
217
|
+
"""
|
|
218
|
+
read_dialect = _SQLGLOT_DIALECT.get(old_type)
|
|
219
|
+
write_dialect = _SQLGLOT_DIALECT.get(new_type)
|
|
220
|
+
if read_dialect is None or write_dialect is None or read_dialect == write_dialect:
|
|
221
|
+
return questions
|
|
222
|
+
|
|
223
|
+
result = {}
|
|
224
|
+
for code_q, values in questions.items():
|
|
225
|
+
values = list(values)
|
|
226
|
+
try:
|
|
227
|
+
values[0] = sqlglot.transpile(values[0], read=read_dialect, write=write_dialect)[0]
|
|
228
|
+
except sqlglot_errors.SqlglotError:
|
|
229
|
+
cls._logger.warning(
|
|
230
|
+
"Transposition %s→%s impossible pour la question '%s' : requête inchangée.",
|
|
231
|
+
old_type, new_type, code_q,
|
|
232
|
+
)
|
|
233
|
+
result[code_q] = values
|
|
234
|
+
return result
|
|
235
|
+
|
|
189
236
|
def create_exercice(self, code: str, db: DatabaseRef | None = None) -> bool:
|
|
190
237
|
"""Crée un exercice vide. Retourne False si le code existe déjà.
|
|
191
238
|
|
|
@@ -34,7 +34,7 @@ class SQLExecutionService:
|
|
|
34
34
|
self,
|
|
35
35
|
db: Database,
|
|
36
36
|
norm: SQLNormalizationService,
|
|
37
|
-
|
|
37
|
+
ia_demandee: bool = False,
|
|
38
38
|
debug: bool = False,
|
|
39
39
|
output: TypeOutput = "text",
|
|
40
40
|
):
|
|
@@ -42,13 +42,13 @@ class SQLExecutionService:
|
|
|
42
42
|
Args:
|
|
43
43
|
db: Instance de la base de données.
|
|
44
44
|
norm: Service de normalisation des noms.
|
|
45
|
-
|
|
45
|
+
ia_demandee: Aide de l'IA demandée par défaut pour cette instance.
|
|
46
46
|
debug: Mode debug.
|
|
47
47
|
output: Type de sortie pour le formatage des erreurs.
|
|
48
48
|
"""
|
|
49
49
|
self._db = db
|
|
50
50
|
self._norm = norm
|
|
51
|
-
self.
|
|
51
|
+
self.ia_demandee = ia_demandee
|
|
52
52
|
self.debug = debug
|
|
53
53
|
self._output = output
|
|
54
54
|
|
|
@@ -77,7 +77,7 @@ class SQLExecutionService:
|
|
|
77
77
|
f"{err.get('end_context', '')}"
|
|
78
78
|
) if err else str(e)
|
|
79
79
|
raise SQLQueryException(
|
|
80
|
-
self.
|
|
80
|
+
self.ia_demandee,
|
|
81
81
|
f"Erreur de syntaxe lors de l'analyse de la requête SQL (ParseError) :\n {msg}",
|
|
82
82
|
ctx.sql_request,
|
|
83
83
|
None,
|
|
@@ -86,7 +86,7 @@ class SQLExecutionService:
|
|
|
86
86
|
)
|
|
87
87
|
except errors.TokenError as e:
|
|
88
88
|
raise SQLQueryException(
|
|
89
|
-
self.
|
|
89
|
+
self.ia_demandee,
|
|
90
90
|
f"Erreur de syntaxe lors de l'analyse de la requête SQL (TokenError) :\n {e}",
|
|
91
91
|
ctx.sql_request,
|
|
92
92
|
None,
|
|
@@ -95,7 +95,7 @@ class SQLExecutionService:
|
|
|
95
95
|
)
|
|
96
96
|
except Exception as e:
|
|
97
97
|
raise SQLQueryException(
|
|
98
|
-
self.
|
|
98
|
+
self.ia_demandee,
|
|
99
99
|
f"Erreur de syntaxe lors de l'analyse de la requête SQL :\n {e}",
|
|
100
100
|
ctx.sql_request,
|
|
101
101
|
None,
|
|
@@ -110,6 +110,17 @@ class SQLExecutionService:
|
|
|
110
110
|
|
|
111
111
|
ctx.sql_tables = []
|
|
112
112
|
ctx.from_all = [stmt.find(From)]
|
|
113
|
+
if ctx.from_all[0] is None:
|
|
114
|
+
raise SQLQueryException(
|
|
115
|
+
self.ia_demandee,
|
|
116
|
+
"Erreur de syntaxe lors de l'analyse de la requête SQL :\n "
|
|
117
|
+
"aucune clause 'FROM' valide n'a été trouvée (vérifiez les espaces "
|
|
118
|
+
"autour des mots-clés SQL).",
|
|
119
|
+
ctx.sql_request,
|
|
120
|
+
None,
|
|
121
|
+
self._db.getType(),
|
|
122
|
+
self._output,
|
|
123
|
+
)
|
|
113
124
|
for t in ctx.from_all[0].find_all(exp.Table):
|
|
114
125
|
if t.alias:
|
|
115
126
|
ctx.sql_tables.append((t.this.this, str(t.alias)))
|
|
@@ -235,7 +246,7 @@ class SQLExecutionService:
|
|
|
235
246
|
|
|
236
247
|
if erreurs:
|
|
237
248
|
raise SQLQueryException(
|
|
238
|
-
self.
|
|
249
|
+
self.ia_demandee,
|
|
239
250
|
"Erreurs de validation lors de l'analyse de la requête SQL :\n- " + "\n- ".join(erreurs),
|
|
240
251
|
ctx.sql_request,
|
|
241
252
|
None,
|
|
@@ -246,7 +257,7 @@ class SQLExecutionService:
|
|
|
246
257
|
return True
|
|
247
258
|
except errors.TokenError as e:
|
|
248
259
|
raise SQLQueryException(
|
|
249
|
-
self.
|
|
260
|
+
self.ia_demandee,
|
|
250
261
|
f"Erreur de syntaxe lors de l'analyse de la requête SQL (TokenError) :\n {e}",
|
|
251
262
|
ctx.sql_request,
|
|
252
263
|
None,
|
|
@@ -255,7 +266,7 @@ class SQLExecutionService:
|
|
|
255
266
|
)
|
|
256
267
|
except errors.ParseError as e:
|
|
257
268
|
raise SQLQueryException(
|
|
258
|
-
self.
|
|
269
|
+
self.ia_demandee,
|
|
259
270
|
f"Erreur de syntaxe SQL: {e}",
|
|
260
271
|
ctx.sql_request,
|
|
261
272
|
None,
|
|
@@ -287,7 +298,7 @@ class SQLExecutionService:
|
|
|
287
298
|
ctx.sql_results = self._db.execute(ctx.sql_request)
|
|
288
299
|
except Exception as e:
|
|
289
300
|
raise SQLQueryException(
|
|
290
|
-
self.
|
|
301
|
+
self.ia_demandee,
|
|
291
302
|
f"Erreur lors de l'exécution de la requête SQL :\n {e}",
|
|
292
303
|
ctx.sql_request,
|
|
293
304
|
None,
|
|
@@ -35,7 +35,7 @@ class SQLQueryService:
|
|
|
35
35
|
exercice_service: ExerciceService,
|
|
36
36
|
output: TypeOutput,
|
|
37
37
|
debug: bool = False,
|
|
38
|
-
|
|
38
|
+
ia_demandee: bool = False,
|
|
39
39
|
aide: bool = False,
|
|
40
40
|
ia_mode: bool = False):
|
|
41
41
|
"""
|
|
@@ -48,7 +48,7 @@ class SQLQueryService:
|
|
|
48
48
|
exercice_service: Service de gestion des exercices.
|
|
49
49
|
output: Type de sortie pour le formatage.
|
|
50
50
|
debug: Mode debug.
|
|
51
|
-
|
|
51
|
+
ia_demandee: Aide de l'IA demandée par défaut pour cette instance.
|
|
52
52
|
aide: Afficher le commentaire d'aide lors de la correction.
|
|
53
53
|
ia_mode: Active le mode IA.
|
|
54
54
|
"""
|
|
@@ -59,7 +59,7 @@ class SQLQueryService:
|
|
|
59
59
|
self._step_by_step_service = sbs_service
|
|
60
60
|
self._exercice_service = exercice_service
|
|
61
61
|
self.debug = debug
|
|
62
|
-
self.
|
|
62
|
+
self.ia_demandee = ia_demandee
|
|
63
63
|
self._output = output
|
|
64
64
|
self._aide = aide
|
|
65
65
|
self._ia_mode = ia_mode
|
|
@@ -304,6 +304,7 @@ class SQLQueryService:
|
|
|
304
304
|
ctx: SQLContext,
|
|
305
305
|
code_ex: str | None,
|
|
306
306
|
code_q: str | None,
|
|
307
|
+
ia_demandee: bool | None = None,
|
|
307
308
|
) -> OutputFactory | None:
|
|
308
309
|
"""
|
|
309
310
|
Charge la solution d'un exercice et construit le bloc de correction.
|
|
@@ -312,10 +313,15 @@ class SQLQueryService:
|
|
|
312
313
|
ctx: Contexte de la requête proposée.
|
|
313
314
|
code_ex: Code de l'exercice (ou None si pas d'exercice).
|
|
314
315
|
code_q: Code de la question (ou None si pas d'exercice).
|
|
316
|
+
ia_demandee: Aide de l'IA demandée pour cette requête (case à cocher).
|
|
317
|
+
Si None, retombe sur le réglage par défaut de l'instance (self.ia_demandee).
|
|
315
318
|
|
|
316
319
|
Returns:
|
|
317
320
|
OutputFactory contenant le bloc correction, ou None si pas de solution.
|
|
318
321
|
"""
|
|
322
|
+
if ia_demandee is None:
|
|
323
|
+
ia_demandee = self.ia_demandee
|
|
324
|
+
|
|
319
325
|
if code_ex is None or code_q is None:
|
|
320
326
|
return None
|
|
321
327
|
|
|
@@ -342,7 +348,7 @@ class SQLQueryService:
|
|
|
342
348
|
)
|
|
343
349
|
output.addBlock(correction_output)
|
|
344
350
|
|
|
345
|
-
if
|
|
351
|
+
if ia_demandee and self._ia_mode and self._llm_service and sol_ctx.question:
|
|
346
352
|
analysis = self._llm_service.analyse_exo_reponse(
|
|
347
353
|
sql_soumis=ctx.sql_request,
|
|
348
354
|
sql_attendu=sol_ctx.sql_request,
|
|
@@ -357,17 +363,21 @@ class SQLQueryService:
|
|
|
357
363
|
return output
|
|
358
364
|
|
|
359
365
|
def build_error_output(
|
|
360
|
-
self, exc: SQLQueryException
|
|
366
|
+
self, exc: SQLQueryException, ia_demandee: bool | None = None
|
|
361
367
|
) -> OutputFactory:
|
|
362
368
|
"""
|
|
363
369
|
Construit et formate un message d'erreur structuré pour l'affichage dans différents styles de sortie.
|
|
364
370
|
|
|
365
371
|
Args:
|
|
366
|
-
|
|
372
|
+
exc: Exception SQL à décrire.
|
|
373
|
+
ia_demandee: Aide de l'IA demandée pour cette requête (case à cocher).
|
|
374
|
+
Si None, retombe sur le réglage par défaut de l'instance (self.ia_demandee).
|
|
367
375
|
|
|
368
376
|
Returns:
|
|
369
377
|
str: Message d'erreur formaté correspondant au type de sortie spécifié.
|
|
370
378
|
"""
|
|
379
|
+
if ia_demandee is None:
|
|
380
|
+
ia_demandee = self.ia_demandee
|
|
371
381
|
|
|
372
382
|
# Définir les couleurs (l'objet Couleur gère les trois formats simultanément)
|
|
373
383
|
style_titre2 = Style(
|
|
@@ -410,7 +420,7 @@ class SQLQueryService:
|
|
|
410
420
|
.setStyle(style_error))
|
|
411
421
|
error_factory.addLineSeparator()
|
|
412
422
|
|
|
413
|
-
if self._ia_mode:
|
|
423
|
+
if ia_demandee and self._ia_mode:
|
|
414
424
|
with Spinner("Construction de l'explication avec l'IA générative"):
|
|
415
425
|
error_factory.addBlock(self._llm_service.analyse_error(exc.message, exc.sqlhs, exc.sqlok))
|
|
416
426
|
clear_line()
|