Skip to content

Commit 6914a82

Browse files
Andreas AlbrechtAndreas Albrecht
authored andcommitted
Refactored extract column defs example (fixes andialbrecht#439, andialbrecht#411, andialbrecht#526).
1 parent 55427d4 commit 6914a82

File tree

1 file changed

+20
-13
lines changed

1 file changed

+20
-13
lines changed

examples/column_defs_lowlevel.py

Lines changed: 20 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -17,18 +17,25 @@ def extract_definitions(token_list):
1717
# assumes that token_list is a parenthesis
1818
definitions = []
1919
tmp = []
20-
# grab the first token, ignoring whitespace. idx=1 to skip open (
21-
tidx, token = token_list.token_next(1)
22-
while token and not token.match(sqlparse.tokens.Punctuation, ')'):
23-
tmp.append(token)
24-
# grab the next token, this times including whitespace
25-
tidx, token = token_list.token_next(tidx, skip_ws=False)
26-
# split on ",", except when on end of statement
27-
if token and token.match(sqlparse.tokens.Punctuation, ','):
28-
definitions.append(tmp)
20+
par_level = 0
21+
for token in token_list.flatten():
22+
if token.is_whitespace:
23+
continue
24+
elif token.match(sqlparse.tokens.Punctuation, '('):
25+
par_level += 1
26+
continue
27+
if token.match(sqlparse.tokens.Punctuation, ')'):
28+
if par_level == 0:
29+
break
30+
else:
31+
par_level += 1
32+
elif token.match(sqlparse.tokens.Punctuation, ','):
33+
if tmp:
34+
definitions.append(tmp)
2935
tmp = []
30-
tidx, token = token_list.token_next(tidx)
31-
if tmp and isinstance(tmp[0], sqlparse.sql.Identifier):
36+
else:
37+
tmp.append(token)
38+
if tmp:
3239
definitions.append(tmp)
3340
return definitions
3441

@@ -46,5 +53,5 @@ def extract_definitions(token_list):
4653
columns = extract_definitions(par)
4754

4855
for column in columns:
49-
print('NAME: {name:10} DEFINITION: {definition}'.format(
50-
name=column[0], definition=''.join(str(t) for t in column[1:])))
56+
print('NAME: {name!s:12} DEFINITION: {definition}'.format(
57+
name=column[0], definition=' '.join(str(t) for t in column[1:])))

0 commit comments

Comments
 (0)