-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathr_to_python_sql_template.py
More file actions
53 lines (39 loc) · 1.64 KB
/
r_to_python_sql_template.py
File metadata and controls
53 lines (39 loc) · 1.64 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 pathlib import Path
R_SQL_DIR = "./DataQualityDashboard/inst/sql/sql_server"
def repl_fn(full_clause):
template_var_ptn = "[\'\"]?@(\w+)[\'\"]?"
condition_clause = full_clause.group(1)
condition_clause = re.sub(template_var_ptn, lambda s: f"{s.group(1)}",
condition_clause)
condition_clause = re.sub('(\s+)(\&)(\s+)', r'\1and\3', condition_clause)
condition_clause = re.sub('(\s+)(\|)(\s+)', r'\1or\3', condition_clause)
condition_clause = re.sub('(\s+)(IN)(\s+)', r'\1in\3', condition_clause)
if_clause = full_clause.group(2)
else_clause = full_clause.group(3) if len(
full_clause.groups()) == 3 else None
if else_clause:
jinja_clause = \
f"""{{% if {condition_clause} %}}{if_clause}{{% else %}}{else_clause}{{% endif %}}
"""
else:
jinja_clause = \
f"""{{% if {condition_clause} %}}{if_clause}{{% endif %}}
"""
return jinja_clause
def main():
for fname in Path(R_SQL_DIR).glob("*.sql"):
with open(fname, 'r') as f:
script = f.read()
conditional_clause_ptn = "\{([^}]+)\}\s*\?\s*\{([^}]+)\}(?:\s*:\s*{([^}]+)\})?"
template_var_ptn = "@(\w+)"
script = re.sub(conditional_clause_ptn,
repl_fn,
script,
flags=re.S)
script = re.sub(template_var_ptn,
lambda s: f"{{{{{s.group(1)}}}}}", script)
with open(Path('sql') / Path(fname).name, 'w') as f:
f.write(script)
if __name__ == "__main__":
main()