2 from sqlparse import parse
3 from sqlparse.tokens import Name, Error, Punctuation, Comment, Newline, \
7 def requote_names(token_list):
8 """Remove backticks, quote non-lowercase identifiers"""
9 for token in token_list.flatten():
10 if token.ttype is Name:
12 if (value[0] == "`") and (value[-1] == "`"):
15 token.normalized = token.value = value
17 token.normalized = token.value = '"%s"' % value
20 def find_error(token_list):
22 for token in token_list.flatten():
23 if token.ttype is Error:
28 class StatementGrouper(object):
29 """Collect lines and reparse until the last statement is complete"""
35 def process_line(self, line):
36 self.lines.append(line)
39 def process_lines(self):
40 statements = parse('\n'.join(self.lines))
41 last_stmt = statements[-1]
42 for i in xrange(len(last_stmt.tokens) - 1, 0, -1):
43 token = last_stmt.tokens[i]
44 if token.ttype in (Comment.Single, Comment.Multiline,
47 if token.ttype is Punctuation and token.value == ';':
48 break # The last statement is complete
49 # The last statement is still incomplete - wait for the next line
52 self.statements = statements
54 def get_statements(self):
55 for stmt in self.statements:
62 tokens = parse('\n'.join(self.lines))
64 if (token.ttype not in (Comment.Single, Comment.Multiline,
65 Newline, Whitespace)):
66 raise ValueError("Incomplete SQL statement: %s" %