-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathwrd_params.py
More file actions
53 lines (40 loc) · 1.73 KB
/
wrd_params.py
File metadata and controls
53 lines (40 loc) · 1.73 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
import re
from loguru import logger
from utils_logger import log_execution
# @log_execution()
# def load_params_from_config(config_path: str) -> dict:
# with open( config_path, "r", encoding="utf-8") as f:
# config = json.load(f)
# return config.get("params", {})
@log_execution()
def inject_report_params(sql: str, params: dict) -> str:
"""
Заменяет %Param! на значение из словаря marks.
Не заменяет параметры внутри однострочных SQL-комментариев (-- ...).
"""
try:
def replace_in_code(part: str) -> str:
def replacer(match: re.Match) -> str:
param_name = match.group(1)
if param_name not in params:
raise ValueError(f"Параметр '{param_name}' не найден в конфигурации")
value = params[param_name]
if isinstance(value, str):
safe_value = value.replace("'", "''")
return f"'{safe_value}'"
if value is None:
return "NULL"
return str(value)
return re.sub(r"%([A-Za-z0-9_]+)!", replacer, part)
result_lines = []
for line in sql.splitlines():
if "--" in line:
code_part, comment_part = line.split("--", 1)
code_part = replace_in_code(code_part)
result_lines.append(code_part + "--" + comment_part)
else:
result_lines.append(replace_in_code(line))
return "\n".join(result_lines)
except Exception:
logger.exception("Ошибка обработки параметров SQL")
raise