2
2
3
3
DEBUG = False
4
4
5
+ def _debug (* args , ** kwargs ):
6
+ if DEBUG :
7
+ print (* args , ** kwargs )
8
+
9
+
10
+ def _print (* args , end = '' , ** kwargs ):
11
+ if not DEBUG :
12
+ print (* args , end = end , ** kwargs )
13
+
14
+
5
15
def parse_tree (path , save_to = 'query.sql' , column_name = 'value' , src_table = 'my_table' , tab = 4 ):
6
16
OUT = sys .stdout
7
17
if not DEBUG :
@@ -15,8 +25,7 @@ def parse_tree(path, save_to='query.sql', column_name='value', src_table='my_tab
15
25
node_type = 'split'
16
26
stack = [0 ]
17
27
18
- if not DEBUG :
19
- print ('SELECT' , end = '' )
28
+ _print ('SELECT' )
20
29
21
30
for i , row in enumerate (rule ):
22
31
row = row .strip ()
@@ -32,13 +41,11 @@ def parse_tree(path, save_to='query.sql', column_name='value', src_table='my_tab
32
41
if depth < stack [- 1 ]:
33
42
stack .pop ()
34
43
while stack [- 1 ] != depth :
35
- if not DEBUG :
36
- text = '\n ' + ' ' * tab * stack [- 1 ] + 'END'
37
- print (text , end = '' )
44
+ text = f"\n { ' ' * tab * stack [- 1 ]} END"
45
+ _print (text )
38
46
stack .pop ()
39
47
40
- if DEBUG :
41
- print (row , stack )
48
+ _debug (row , stack )
42
49
43
50
# infer node type
44
51
node_type = 'leaf'
@@ -66,32 +73,29 @@ def parse_tree(path, save_to='query.sql', column_name='value', src_table='my_tab
66
73
after = '' # handle cases to put END
67
74
if i < len (rule ) - 1 :
68
75
if rule [i + 1 ].count ('|' ) <= stack [- 2 ]:
69
- after = ' \n ' + ' ' * spacing * (depth - 1 ) + ' END'
76
+ after = f" \n { ' ' * spacing * (depth - 1 )} END"
70
77
71
78
text = f" { text } { after } "
72
-
73
- if not DEBUG :
74
- print (text , end = '' )
75
- else :
76
- end , text = '' , ''
79
+ _print (text )
80
+ else : # split/internal node
81
+ text = ''
77
82
if else_flag :
78
- text = '\n ' + ' ' * indent + 'ELSE'
79
- if not DEBUG :
80
- print (text , end = '' )
83
+ text = f"\n { ' ' * indent } ELSE"
84
+ _print (text )
81
85
else :
82
86
start_idx = (spacing + 1 ) * depth + 1
83
87
text = row [start_idx :]
84
- text = f"\n { ' ' * indent } { end } CASE WHEN { text } THEN"
85
- if not DEBUG :
86
- print (text , end = '' )
88
+ text = f"\n { ' ' * indent } CASE WHEN { text } THEN"
89
+ _print (text )
87
90
88
- if DEBUG :
89
- print (stack )
90
- else :
91
- if stack [- 1 ] > 1 :
92
- text = '\n ' + ' ' * spacing * stack [- 1 ] + 'END'
93
- print (text , end = '' )
94
-
95
- print (f"\n { ' ' * spacing } END AS { column_name } " )
96
- print (f"FROM { src_table } " )
91
+ _debug (stack )
92
+
93
+ while stack [- 1 ] > 0 :
94
+ text = f"\n { ' ' * spacing * stack [- 1 ]} END"
95
+ if stack [- 1 ] == 1 :
96
+ text += f" AS { column_name } \n FROM { src_table } ;\n "
97
+
98
+ _print (text )
99
+ stack .pop ()
100
+
97
101
sys .stdout = OUT
0 commit comments