Skip to content

Commit 42fb1d0

Browse files
committed
Fix column_defs example
1 parent e331dcf commit 42fb1d0

File tree

1 file changed

+18
-22
lines changed

1 file changed

+18
-22
lines changed

examples/column_defs_lowlevel.py

Lines changed: 18 additions & 22 deletions
Original file line numberDiff line numberDiff line change
@@ -11,43 +11,39 @@
1111

1212
import sqlparse
1313

14-
SQL = """CREATE TABLE foo (
15-
id integer primary key,
16-
title varchar(200) not null,
17-
description text
18-
);"""
19-
20-
21-
parsed = sqlparse.parse(SQL)[0]
22-
23-
# extract the parenthesis which holds column definitions
24-
par = parsed.token_next_by(i=sqlparse.sql.Parenthesis)
25-
2614

2715
def extract_definitions(token_list):
2816
# assumes that token_list is a parenthesis
2917
definitions = []
3018
tmp = []
31-
# grab the first token, ignoring whitespace
32-
token = token_list.token_next(0)
19+
# grab the first token, ignoring whitespace. idx=1 to skip open (
20+
token = token_list.token_next(1)
3321
while token and not token.match(sqlparse.tokens.Punctuation, ')'):
3422
tmp.append(token)
35-
idx = token_list.token_index(token)
3623
# grab the next token, this times including whitespace
37-
token = token_list.token_next(idx, skip_ws=False)
24+
token = token_list.token_next(token, skip_ws=False)
3825
# split on ",", except when on end of statement
3926
if token and token.match(sqlparse.tokens.Punctuation, ','):
4027
definitions.append(tmp)
4128
tmp = []
42-
idx = token_list.token_index(token)
43-
token = token_list.token_next(idx)
29+
token = token_list.token_next(token)
4430
if tmp and isinstance(tmp[0], sqlparse.sql.Identifier):
4531
definitions.append(tmp)
4632
return definitions
4733

4834

49-
columns = extract_definitions(par)
35+
if __name__ == '__main__':
36+
SQL = """CREATE TABLE foo (
37+
id integer primary key,
38+
title varchar(200) not null,
39+
description text);"""
40+
41+
parsed = sqlparse.parse(SQL)[0]
42+
43+
# extract the parenthesis which holds column definitions
44+
par = parsed.token_next_by(i=sqlparse.sql.Parenthesis)
45+
columns = extract_definitions(par)
5046

51-
for column in columns:
52-
print('NAME: {name:10} DEFINITION: {definition}'.format(
53-
name=column[0], definition=''.join(str(t) for t in column[1:])))
47+
for column in columns:
48+
print('NAME: {name:10} DEFINITION: {definition}'.format(
49+
name=column[0], definition=''.join(str(t) for t in column[1:])))

0 commit comments

Comments
 (0)