|
| 1 | +#!/usr/bin/env python |
| 2 | + |
| 3 | +# Example for retrieving column definitions from a CREATE statement |
| 4 | +# using low-level functions. |
| 5 | + |
| 6 | +import sqlparse |
| 7 | + |
| 8 | +SQL = """CREATE TABLE foo ( |
| 9 | + id integer primary key, |
| 10 | + title varchar(200) not null, |
| 11 | + description text |
| 12 | +);""" |
| 13 | + |
| 14 | + |
| 15 | +parsed = sqlparse.parse(SQL)[0] |
| 16 | + |
| 17 | +# extract the parenthesis which holds column definitions |
| 18 | +par = parsed.token_next_by_instance(0, sqlparse.sql.Parenthesis) |
| 19 | + |
| 20 | + |
| 21 | +def extract_definitions(token_list): |
| 22 | + # assumes that token_list is a parenthesis |
| 23 | + definitions = [] |
| 24 | + # grab the first token, ignoring whitespace |
| 25 | + token = token_list.token_next(0) |
| 26 | + tmp = [] |
| 27 | + while token and not token.match(sqlparse.tokens.Punctuation, ')'): |
| 28 | + tmp.append(token) |
| 29 | + idx = token_list.token_index(token) |
| 30 | + # grab the next token, this times including whitespace |
| 31 | + token = token_list.token_next(idx, skip_ws=False) |
| 32 | + # split on "," |
| 33 | + if (token is not None # = end of statement |
| 34 | + and token.match(sqlparse.tokens.Punctuation, ',')): |
| 35 | + definitions.append(tmp) |
| 36 | + tmp = [] |
| 37 | + idx = token_list.token_index(token) |
| 38 | + token = token_list.token_next(idx) |
| 39 | + if tmp and isinstance(tmp[0], sqlparse.sql.Identifier): |
| 40 | + definitions.append(tmp) |
| 41 | + return definitions |
| 42 | + |
| 43 | + |
| 44 | +columns = extract_definitions(par) |
| 45 | + |
| 46 | +for column in columns: |
| 47 | + print 'NAME: %-12s DEFINITION: %s' % (column[0], |
| 48 | + ''.join(str(t) for t in column[1:])) |
0 commit comments