2 from sqlparse import parse
3 from sqlparse.compat import PY3
4 from sqlparse.tokens import Name, Error, Punctuation, Comment, Newline, \
8 def requote_names(token_list):
9 """Remove backticks, quote non-lowercase identifiers"""
10 for token in token_list.flatten():
11 if token.ttype is Name:
13 if (value[0] == "`") and (value[-1] == "`"):
16 token.normalized = token.value = value
18 token.normalized = token.value = '"%s"' % value
21 def find_error(token_list):
23 for token in token_list.flatten():
24 if token.ttype is Error:
33 class StatementGrouper(object):
34 """Collect lines and reparse until the last statement is complete"""
40 def process_line(self, line):
41 self.lines.append(line)
44 def process_lines(self):
45 statements = parse(''.join(self.lines))
46 last_stmt = statements[-1]
47 for i in xrange(len(last_stmt.tokens) - 1, 0, -1):
48 token = last_stmt.tokens[i]
49 if token.ttype in (Comment.Single, Comment.Multiline,
52 if token.ttype is Punctuation and token.value == ';':
53 break # The last statement is complete
54 # The last statement is still incomplete - wait for the next line
57 self.statements = statements
59 def get_statements(self):
60 for stmt in self.statements:
67 tokens = parse(''.join(self.lines))
69 if (token.ttype not in (Comment.Single, Comment.Multiline,
70 Newline, Whitespace)):
71 raise ValueError("Incomplete SQL statement: %s" %