|
11 | 11 |
|
12 | 12 | import sqlparse |
13 | 13 |
|
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 | | - |
26 | 14 |
|
27 | 15 | def extract_definitions(token_list): |
28 | 16 | # assumes that token_list is a parenthesis |
29 | 17 | definitions = [] |
30 | 18 | 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) |
33 | 21 | while token and not token.match(sqlparse.tokens.Punctuation, ')'): |
34 | 22 | tmp.append(token) |
35 | | - idx = token_list.token_index(token) |
36 | 23 | # 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) |
38 | 25 | # split on ",", except when on end of statement |
39 | 26 | if token and token.match(sqlparse.tokens.Punctuation, ','): |
40 | 27 | definitions.append(tmp) |
41 | 28 | tmp = [] |
42 | | - idx = token_list.token_index(token) |
43 | | - token = token_list.token_next(idx) |
| 29 | + token = token_list.token_next(token) |
44 | 30 | if tmp and isinstance(tmp[0], sqlparse.sql.Identifier): |
45 | 31 | definitions.append(tmp) |
46 | 32 | return definitions |
47 | 33 |
|
48 | 34 |
|
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) |
50 | 46 |
|
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