138
|
1 import pyparsing, re
|
|
2
|
|
3 sqlStyleComment = pyparsing.Literal("--") + pyparsing.ZeroOrMore(pyparsing.CharsNotIn("\n"))
|
|
4 keywords = {'order by': pyparsing.Keyword('order', caseless=True) +
|
|
5 pyparsing.Keyword('by', caseless=True),
|
|
6 'select': pyparsing.Keyword('select', caseless=True),
|
|
7 'from': pyparsing.Keyword('from', caseless=True),
|
|
8 'having': pyparsing.Keyword('having', caseless=True),
|
|
9 'update': pyparsing.Keyword('update', caseless=True),
|
|
10 'set': pyparsing.Keyword('set', caseless=True),
|
|
11 'delete': pyparsing.Keyword('delete', caseless=True),
|
|
12 'insert into': pyparsing.Keyword('insert', caseless=True) +
|
|
13 pyparsing.Keyword('into', caseless=True),
|
|
14 'values': pyparsing.Keyword('values', caseless=True),
|
|
15 'group by': pyparsing.Keyword('group', caseless=True) +
|
|
16 pyparsing.Keyword('by', caseless=True),
|
|
17 'where': pyparsing.Keyword('where', caseless=True)}
|
|
18 for (name, parser) in keywords.items():
|
|
19 parser.ignore(pyparsing.sglQuotedString)
|
|
20 parser.ignore(pyparsing.dblQuotedString)
|
|
21 parser.ignore(pyparsing.cStyleComment)
|
|
22 parser.ignore(sqlStyleComment)
|
|
23 parser.name = name
|
|
24
|
|
25 fromClauseFinder = re.compile(r".*(from|update)(.*)(where|set)",
|
|
26 re.IGNORECASE | re.DOTALL | re.MULTILINE)
|
|
27 oracleTerms = oracleTerms = re.compile(r"[A-Z$_#][0-9A-Z_$#]*", re.IGNORECASE)
|
|
28 def tableNamesFromFromClause(statement):
|
|
29 result = fromClauseFinder.search(statement)
|
|
30 if not result:
|
|
31 return []
|
|
32 result = oracleTerms.findall(result.group(2))
|
|
33 result = [r.upper() for r in result if r.upper() not in ('JOIN','ON')]
|
|
34 return result
|
|
35
|
|
36 def orderedParseResults(parsers, statement):
|
|
37 results = []
|
|
38 for parser in parsers:
|
|
39 results.extend(parser.scanString(statement))
|
|
40 results.sort(cmp=lambda x,y:cmp(x[1],y[1]))
|
|
41 return results
|
|
42
|
|
43 def whichSegment(statement):
|
|
44 results = orderedParseResults(keywords.values(), statement)
|
|
45 if results:
|
|
46 return ' '.join(results[-1][0])
|
|
47 else:
|
|
48 return None
|
|
49
|
|
50 oracleIdentifierCharacters = pyparsing.alphanums + '_#$'
|
|
51 def wordInProgress(statement):
|
|
52 result = []
|
|
53 letters = list(statement)
|
|
54 letters.reverse()
|
|
55 for letter in letters:
|
|
56 if letter not in oracleIdentifierCharacters:
|
|
57 result.reverse()
|
|
58 return ''.join(result)
|
|
59 result.append(letter)
|
|
60 result.reverse()
|
|
61 return ''.join(result)
|
|
62 |