]> git.phdru.name Git - sqlconvert.git/blob - sqlconvert/process_tokens.py
Do not test statements in StatementGrouper
[sqlconvert.git] / sqlconvert / process_tokens.py
1
2 from sqlparse import parse
3 from sqlparse.compat import PY3
4 from sqlparse import tokens as T
5
6
7 def find_error(token_list):
8     """Find an error"""
9     for token in token_list.flatten():
10         if token.ttype is T.Error:
11             return True
12     return False
13
14
15 def is_newline_statement(statement):
16     for token in statement.tokens[:]:
17         if token.ttype is not T.Newline:
18             return False
19     return True
20
21
22 if PY3:
23     xrange = range
24
25
26 class StatementGrouper(object):
27     """Collect lines and reparse until the last statement is complete"""
28
29     def __init__(self, encoding=None):
30         self.lines = []
31         self.statements = []
32         self.encoding = encoding
33
34     def process_line(self, line):
35         self.lines.append(line)
36         self.process_lines()
37
38     def process_lines(self):
39         statements = parse(''.join(self.lines), encoding=self.encoding)
40         last_stmt = statements[-1]
41         for i in xrange(len(last_stmt.tokens) - 1, 0, -1):
42             token = last_stmt.tokens[i]
43             if token.ttype in (T.Comment.Single, T.Comment.Multiline,
44                                T.Newline, T.Whitespace):
45                 continue
46             if token.ttype is T.Punctuation and token.value == ';':
47                 break  # The last statement is complete
48             # The last statement is still incomplete - wait for the next line
49             return
50         self.lines = []
51         self.statements = statements
52
53     def get_statements(self):
54         for stmt in self.statements:
55             yield stmt
56         self.statements = []
57         raise StopIteration
58
59     def close(self):
60         if not self.lines:
61             return
62         tokens = parse(''.join(self.lines), encoding=self.encoding)
63         for token in tokens:
64             if (token.ttype not in (T.Comment.Single, T.Comment.Multiline,
65                                     T.Newline, T.Whitespace)):
66                 raise ValueError("Incomplete SQL statement: %s" %
67                                  tokens)
68         return tokens