2 from sqlparse import parse
3 from sqlparse.compat import PY3
4 from sqlparse.tokens import Error, Punctuation, Comment, Newline, Whitespace
7 def find_error(token_list):
9 for token in token_list.flatten():
10 if token.ttype is Error:
19 class StatementGrouper(object):
20 """Collect lines and reparse until the last statement is complete"""
22 def __init__(self, encoding=None):
25 self.encoding = encoding
27 def process_line(self, line):
28 self.lines.append(line)
31 def process_lines(self):
32 statements = parse(''.join(self.lines), encoding=self.encoding)
33 last_stmt = statements[-1]
34 for i in xrange(len(last_stmt.tokens) - 1, 0, -1):
35 token = last_stmt.tokens[i]
36 if token.ttype in (Comment.Single, Comment.Multiline,
39 if token.ttype is Punctuation and token.value == ';':
40 break # The last statement is complete
41 # The last statement is still incomplete - wait for the next line
44 self.statements = statements
46 def get_statements(self):
47 for stmt in self.statements:
54 tokens = parse(''.join(self.lines), encoding=self.encoding)
56 if (token.ttype not in (Comment.Single, Comment.Multiline,
57 Newline, Whitespace)):
58 raise ValueError("Incomplete SQL statement: %s" %