]> git.phdru.name Git - sqlconvert.git/blob - sqlconvert/process_tokens.py
Add MySQL-specific remove_directives() and process_statement()
[sqlconvert.git] / sqlconvert / process_tokens.py
1
2 from sqlparse import parse
3 from sqlparse.compat import PY3
4 from sqlparse.tokens import Error, Punctuation, Comment, Newline, Whitespace
5
6
7 def find_error(token_list):
8     """Find an error"""
9     for token in token_list.flatten():
10         if token.ttype is Error:
11             return True
12     return False
13
14
15 if PY3:
16     xrange = range
17
18
19 class StatementGrouper(object):
20     """Collect lines and reparse until the last statement is complete"""
21
22     def __init__(self, encoding=None):
23         self.lines = []
24         self.statements = []
25         self.encoding = encoding
26
27     def process_line(self, line):
28         self.lines.append(line)
29         self.process_lines()
30
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,
37                                Newline, Whitespace):
38                 continue
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
42             return
43         self.lines = []
44         self.statements = statements
45
46     def get_statements(self):
47         for stmt in self.statements:
48             yield stmt
49         self.statements = []
50
51     def close(self):
52         if not self.lines:
53             return
54         tokens = parse(''.join(self.lines), encoding=self.encoding)
55         for token in tokens:
56             if (token.ttype not in (Comment.Single, Comment.Multiline,
57                                     Newline, Whitespace)):
58                 raise ValueError("Incomplete SQL statement: %s" %
59                                  tokens)
60         return tokens