]> git.phdru.name Git - sqlconvert.git/blob - sqlconvert/process_mysql.py
Do not test statements in StatementGrouper
[sqlconvert.git] / sqlconvert / process_mysql.py
1
2 from sqlparse.sql import Comment
3 from sqlparse import tokens as T
4
5
6 def _is_directive_token(token):
7     if isinstance(token, Comment):
8         subtokens = token.tokens
9         if subtokens:
10             comment = subtokens[0]
11             if comment.ttype is T.Comment.Multiline and \
12                     comment.value.startswith('/*!'):
13                 return True
14     return False
15
16
17 def is_directive_statement(statement):
18     tokens = statement.tokens
19     if not _is_directive_token(tokens[0]):
20         return False
21     if tokens[-1].ttype is not T.Punctuation or tokens[-1].value != ';':
22         return False
23     for token in tokens[1:-1]:
24         if token.ttype not in (T.Newline, T.Whitespace):
25             return False
26     return True
27
28
29 def remove_directive_tokens(statement):
30     """Remove /*! directives */ from the first-level"""
31     new_tokens = []
32     for token in statement.tokens:
33         if _is_directive_token(token):
34             continue
35         new_tokens.append(token)
36     statement.tokens = new_tokens
37
38
39 def requote_names(token_list):
40     """Remove backticks, quote non-lowercase identifiers"""
41     for token in token_list.flatten():
42         if token.ttype is T.Name:
43             value = token.value
44             if (value[0] == "`") and (value[-1] == "`"):
45                 value = value[1:-1]
46             if value.islower():
47                 token.normalized = token.value = value
48             else:
49                 token.normalized = token.value = '"%s"' % value
50
51
52 def unescape_strings(token_list):
53     """Unescape strings"""
54     for token in token_list.flatten():
55         if token.ttype is T.String.Single:
56             value = token.value
57             for orig, repl in (
58                 ('\\"', '"'),
59                 ("\\'", "''"),
60                 ('\\\032', '\032'),
61             ):
62                 value = value.replace(orig, repl)
63             token.normalized = token.value = value
64
65
66 def process_statement(statement):
67     remove_directive_tokens(statement)
68     requote_names(statement)
69     unescape_strings(statement)