]> git.phdru.name Git - sqlconvert.git/blob - mysql2sql/process_tokens.py
9e1e760a3e4e65461511457f1994275b0339c4e7
[sqlconvert.git] / mysql2sql / process_tokens.py
1
2 from sqlparse import parse
3 from sqlparse.compat import PY3
4 from sqlparse.tokens import Name, Error, Punctuation, Comment, Newline, \
5     Whitespace
6
7
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:
12             value = token.value
13             if (value[0] == "`") and (value[-1] == "`"):
14                 value = value[1:-1]
15             if value.islower():
16                 token.normalized = token.value = value
17             else:
18                 token.normalized = token.value = '"%s"' % value
19
20
21 def find_error(token_list):
22     """Find an error"""
23     for token in token_list.flatten():
24         if token.ttype is Error:
25             return True
26     return False
27
28
29 if PY3:
30     xrange = range
31
32
33 class StatementGrouper(object):
34     """Collect lines and reparse until the last statement is complete"""
35
36     def __init__(self):
37         self.lines = []
38         self.statements = []
39
40     def process_line(self, line):
41         self.lines.append(line)
42         self.process_lines()
43
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,
50                                Newline, Whitespace):
51                 continue
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
55             return
56         self.lines = []
57         self.statements = statements
58
59     def get_statements(self):
60         for stmt in self.statements:
61             yield stmt
62         self.statements = []
63
64     def close(self):
65         if not self.lines:
66             return
67         tokens = parse(''.join(self.lines))
68         for token in tokens:
69             if (token.ttype not in (Comment.Single, Comment.Multiline,
70                                     Newline, Whitespace)):
71                 raise ValueError("Incomplete SQL statement: %s" %
72                                  tokens)
73         return tokens