Debian Codegraph @

gavo/adql/grammar.py

raw
1 """
2 A parser for ADQL.
3
4 The grammar follows the official BNF grammar quite closely, except where
5 pyparsing makes a different approach desirable; the names should mostly
6 match except for the obvious underscore to camel case map.
7
8 The grammar given in the spec has some nasty rules when you're parsing
9 without backtracking and by recursive descent (which is what pyparsing
10 does). I need some reformulations. The more interesting of those
11 include:
12
13 TableReference
14 --------------
15
16 Trouble is that table_reference is left-recursive in the following rules::
17
18 <table_reference> ::=
19 <table_name> [ <correlation_specification> ]
20 | <derived_table> <correlation_specification>
21 | <joined_table>
22
23 <joined_table> ::=
24 <qualified_join>
25 | <left_paren> <joined_table> <right_paren>
26
27 <qualified_join> ::=
28 <table_reference> [ NATURAL ] [ <join_type> ] JOIN
29 <table_reference> [ <join_specification> ]
30
31 We fix this by adding rules::
32
33 <sub_join> ::= '(' <joinedTable> ')'
34 <join_opener> ::=
35 <table_name> [ <correlation_specification> ]
36 | <derived_table> <correlation_specification>
37 | <sub_join>
38
39 and then writing::
40
41 <qualified_join> ::=
42 <join_opener> [ NATURAL ] [ <join_type> ] JOIN
43 <table_reference> [ <join_specification> ]
44
45
46
47 statement
48 ---------
49
50 I can't have StringEnd appended to querySpecification since it's used
51 in subqueries, but I need to have it to keep pyparsing from just matching
52 parts of the input. Thus, the top-level production is for "statement".
53
54
55 trig_function, math_function, system_defined_function
56 -----------------------------------------------------
57
58 I think it's a bit funny to have the arity of functions in the syntax, but
59 there you go. Anyway, I don't want to have the function names in separate
60 symbols since they are expensive but go for a Regex (trig1ArgFunctionName).
61 The only exception is ATAN since it has a different arity from the rest of the
62 lot.
63
64 Similarly, for math_function I group symbols by arity.
65
66 The system defined functions are also regrouped to keep the number of
67 symbols reasonable.
68
69 column_reference and below
70 --------------------------
71
72 Here the lack of backtracking hurts badly, since once, say, schema name
73 is matched with a dot that's it, even if the dot should really have separated
74 schema and table.
75
76 Hence, we don't assign semantic labels in the grammar but leave that to
77 whatever interprets the tokens.
78
79 The important rules here are::
80
81 <column_name> ::= <identifier>
82 <correlation_name> ::= <identifier>
83 <catalog_name> ::= <identifier>
84 <unqualified_schema name> ::= <identifier>
85 <schema_name> ::= [ <catalog_name> <period> ] <unqualified_schema name>
86 <table_name> ::= [ <schema_name> <period> ] <identifier>
87 <qualifier> ::= <table_name> | <correlation_name>
88 <column_reference> ::= [ <qualifier> <period> ] <column_name>
89
90 By substitution, one has::
91
92 <schema_name> ::= [ <identifier> <period> ] <identifier>
93
94 hence::
95
96 <table_name> ::= [[ <identifier> <period> ] <identifier> <period> ]
97 <identifier>
98
99 hence::
100
101 <qualifier> ::= [[ <identifier> <period> ] <identifier> <period> ]
102 <identifier>
103
104 (which matches both table_name and correlation_name) and thus::
105
106 <column_reference> ::= [[[ <identifier> <period> ] <identifier> <period> ]
107 <identifier> <period> ] <identifier>
108
109 We need the table_name, qualifier, and column_reference productions.
110
111
112 generalLiterals in unsigngedLiterals
113 ------------------------------------
114
115 One point I'm deviating from the published grammar is that I disallow
116 generalLiterals in unsignedLiterals. Allowing them would let pyparsing
117 match a string literal as a numericValueLiteral, which messes up
118 string expressions. I'm not sure why generalLiterals are allowed
119 in there anyway. If this bites at some point, we'll face a major rewrite
120 of the grammar (or we need to dump pyparsing).
121
122 To make the whole thing work, I added the generalLiteral to the
123 characterPrimary production.
124 """
125
126 #c Copyright 2008-2025, the GAVO project <[email protected]>
127 #c
128 #c This program is free software, covered by the GNU GPL. See the
129 #c COPYING file in the source distribution.
130
131
132 import functools
133
134 from gavo.utils.parsetricks import (
135 Word, Literal, Optional, alphas, CaselessKeyword,
136 ZeroOrMore, OneOrMore, StringEnd,
137 Forward,
138 MatchFirstWithSaneError, # temporary hack, see parsetricks
139 CaselessLiteral, ParseException, ParseFatalException,
140 Regex, sglQuotedString, alphanums,
141 White,
142 ParseExpression,
143 Suppress, pyparsingWhitechars)
144 from gavo.utils.parsetricks import ParseSyntaxException #noflake: exported name
145
146 from gavo import utils
147 from gavo import stc
148 from gavo.adql import bindinggrammar
149
150 __docformat__ = "restructuredtext en"
151
152 import sys
153
154 # all SQL and ADQL reserved words are expected in uppercase by this and
155 # other modules.
156 ADQL_RESERVED_WORDS = set([ "ABS", "ACOS", "AREA", "ASIN", "ATAN", "ATAN2",
157 "CEILING", "CENTROID", "CIRCLE", "CONTAINS", "COS", "DEGREES", "DISTANCE",
158 "EXP", "FLOOR", "INTERSECTS", "LATITUDE", "LOG", "LOG10", "COORD1",
159 "COORD2", "COORDSYS", "BOX",
160 "MOD", "PI", "POINT", "POLYGON", "POWER", "RADIANS", "REGION",
161 "RAND", "ROUND", "SIN", "SQUARE", "SQRT", "TOP", "TAN", "TRUNCATE",
162 "OFFSET", "BITWISE_AND", "BITWISE_OR", "BITWISE_XOR", "BITWISE_NOT",
163 "MOC", "STDDEV"])
164
165 SQL_RESERVED_WORDS = set([
166 "ABSOLUTE", "ACTION", "ADD", "ALL", "ALLOCATE", "ALTER", "AND", "ANY",
167 "ARE", "AS", "ASC", "ASSERTION", "AT", "AUTHORIZATION", "AVG", "BEGIN",
168 "BETWEEN", "BIT", "BIT_LENGTH", "BOTH", "BY", "CASCADE", "CASCADED",
169 "CASE", "CAST", "CATALOG", "CHAR", "CHARACTER", "CHAR_LENGTH",
170 "CHARACTER_LENGTH", "CHECK", "CLOSE", "COALESCE", "COLLATE",
171 "COLLATION", "COLUMN", "COMMIT", "CONNECT", "CONNECTION", "CONSTRAINT",
172 "CONSTRAINTS", "CONTINUE", "CONVERT", "CORRESPONDING", "COUNT",
173 "CREATE", "CROSS", "CURRENT", "CURRENT_DATE", "CURRENT_TIME",
174 "CURRENT_TIMESTAMP", "CURRENT_USER", "CURSOR", "DATE", "DAY",
175 "DEALLOCATE", "DECIMAL", "DECLARE", "DEFAULT", "DEFERRABLE", "DEFERRED",
176 "DELETE", "DESC", "DESCRIBE", "DESCRIPTOR", "DIAGNOSTICS", "DISCONNECT",
177 "DISTINCT", "DOMAIN", "DOUBLE", "DROP", "ELSE", "END", "END-EXEC",
178 "ESCAPE", "EXCEPT", "EXCEPTION", "EXEC", "EXECUTE", "EXISTS",
179 "EXTERNAL", "EXTRACT", "FALSE", "FETCH", "FIRST", "FLOAT", "FOR",
180 "FOREIGN", "FOUND", "FROM", "FULL", "GET", "GLOBAL", "GO", "GOTO",
181 "GRANT", "GROUP", "HAVING", "HOUR", "IDENTITY", "IMMEDIATE", "IN",
182 "INDICATOR", "INITIALLY", "INNER", "INPUT", "INSENSITIVE", "INSERT",
183 "INT", "INTEGER", "INTERSECT", "INTERVAL", "INTO", "IS", "ISOLATION",
184 "JOIN", "KEY", "LANGUAGE", "LAST", "LEADING", "LEFT", "LEVEL", "LIKE",
185 "LOCAL", "LOWER", "MATCH", "MAX", "MIN", "MINUTE", "MODULE", "MONTH",
186 "NAMES", "NATIONAL", "NATURAL", "NCHAR", "NEXT", "NO", "NOT", "NULL",
187 "NULLIF", "NUMERIC", "OCTET_LENGTH", "OF", "ON", "ONLY", "OPEN",
188 "OPTION", "OR", "ORDER", "OUTER", "OUTPUT", "OVERLAPS", "PAD",
189 "PARTIAL", "POSITION", "PRECISION", "PREPARE", "PRESERVE", "PRIMARY",
190 "PRIOR", "PRIVILEGES", "PROCEDURE", "PUBLIC", "READ", "REAL",
191 "REFERENCES", "RELATIVE", "RESTRICT", "REVOKE", "RIGHT", "ROLLBACK",
192 "ROWS", "SCHEMA", "SCROLL", "SECOND", "SECTION", "SELECT", "SESSION",
193 "SESSION_USER", "SET", "SIZE", "SMALLINT", "SOME", "SPACE", "SQL",
194 "SQLCODE", "SQLERROR", "SQLSTATE", "SUBSTRING", "SUM", "SYSTEM_USER",
195 "TABLE", "TEMPORARY", "THEN", "TIME", "TIMESTAMP", "TIMEZONE_HOUR",
196 "TIMEZONE_MINUTE", "TO", "TRAILING", "TRANSACTION", "TRANSLATE",
197 "TRANSLATION", "TRIM", "TRUE", "UNION", "UNIQUE", "UNKNOWN", "UPDATE",
198 "UPPER", "USAGE", "USER", "USING", "VALUE", "VALUES", "VARCHAR",
199 "VARYING", "VIEW", "WHEN", "WHENEVER", "WHERE", "WITH", "WORK", "WRITE",
200 "YEAR", "ZONE", "TABLESAMPLE"])
201
202 ALL_RESERVED_WORDS = ADQL_RESERVED_WORDS | SQL_RESERVED_WORDS
203
204
205 # A regular expression for prefixes of user defined functions
206 userFunctionPrefix = "(gavo|ivo)"
207
208
209 def _makeQuotedName(s, p, t):
210 # Parse action for delimitedIdentifer. No longer necessary when we can
211 # rely on working pyparsing QuotedString
212 return utils.QuotedName(str(t[0])[1:-1].replace('""', '"'))
213
214
215 def _parseVOUnit(s, p, t):
216 # parse action for unitLiteral; in particular, this converts exceptions
217 # so we drop ParseSyntaxExceptions rather than BadUnits
218 # I can't import base top-level because ADQL is "lower" than base and
219 # we're breaking this already in ufunctions. Let's see how we'll
220 # refactor this to avoid the in-function import.
221 # Or perhaps we should defer all this and take it out of the grammar?
222 # We don't need the parse tree anyway...
223 from gavo.base import unitconv
224 try:
225 tree = unitconv.parseUnit(t[0][1:-1])
226 except unitconv.BadUnit as exc:
227 raise ParseFatalException(s, p, f"Cannot parse unit: {exc}")
228 if not tree.isValid:
229 raise ParseFatalException(s, p,
230 f"Non-VOUnits unit in {t[0]}: if you really"
231 " want to keep an unknown unit, put it in single quotes")
232 return t[0][1:-1]
233
234
235 def Args(pyparseSymbol):
236 """wraps pyparseSymbol such that matches get added to an args list
237 on the parent node.
238 """
239 return pyparseSymbol.setResultsName("args", listAllMatches=True)
240
241
242 class RegularIdentifier(Word):
243 """regular identifiers are all C-style identifiers except reserved
244 words.
245
246 Filtering these in the parse action doesn't always work properly for
247 all versions of pyparsing, thus this special class.
248
249 reservedWords are assumed to be in upper case, but matching
250 case-insensitively.
251 """
252 def __init__(self, reservedWords):
253 self.reservedWords = reservedWords
254 super(RegularIdentifier, self).__init__(alphas+"_", alphanums+"_")
255 # oh wow. in pyparsing 2.4, Word sets __class__, which we
256 # can't have. Let's undo the damage.
257 self.__class__ = RegularIdentifier
258
259 def parseImpl(self, instring, loc, doActions=True):
260 locNew, match = super(RegularIdentifier, self).parseImpl(instring,
261 loc, doActions)
262 if match.upper() in self.reservedWords:
263 raise ParseException(instring, loc, "Reserved word not allowed here")
264 return locNew, match
265
266
267 class LongestMatch(ParseExpression):
268 """pyparsing's Or, except that ParseFatalExceptions are still propagated.
269 """
270 def __init__(self, exprs, savelist=False):
271 super(LongestMatch, self).__init__(exprs, savelist)
272 self.mayReturnEmpty = False
273 for e in self.exprs:
274 if e.mayReturnEmpty:
275 self.mayReturnEmpty = True
276 break
277
278 def parseImpl(self, instring, loc, doActions=True):
279 maxExcLoc = -1
280 maxMatchLoc = -1
281 maxException = None
282 for e in self.exprs:
283 try:
284 loc2 = e._parse(instring, loc, doActions=False)[0]
285 except ParseException as err:
286 if err.loc>maxExcLoc:
287 maxException = err
288 maxExcLoc = err.loc
289 except IndexError:
290 if len(instring)>maxExcLoc:
291 maxException = ParseException(
292 instring, len(instring), e.errmsg, self)
293 maxExcLoc = len(instring)
294 else:
295 if loc2>maxMatchLoc:
296 maxMatchLoc = loc2
297 maxMatchExp = e
298
299 if maxMatchLoc<0:
300 if maxException is not None:
301 raise maxException
302 else:
303 raise ParseException(instring, loc,
304 "no defined alternatives to match", self)
305
306 return maxMatchExp._parse(instring, loc, doActions)
307
308 def __str__( self ):
309 if hasattr(self,"name"):
310 return self.name
311
312 if self.strRepr is None:
313 self.strRepr = "{" + " ^ ".join( [ str(e) for e in self.exprs ] ) + "}"
314
315 return self.strRepr
316
317 def checkRecursion( self, parseElementList ):
318 subRecCheckList = parseElementList[:] + [ self ]
319 for e in self.exprs:
320 e.checkRecursion( subRecCheckList )
321
322
323 def getADQLGrammarCopy(nodes):
324 """returns a pair symbols, selectSymbol for a grammar parsing ADQL.
325
326 You should only use this if you actually require a fresh copy
327 of the ADQL grammar. Otherwise, use getADQLGrammar or a wrapper
328 function defined by a client module.
329 """
330 g = bindinggrammar.AutoBindingGrammar(nodes)
331
332 with pyparsingWhitechars("\n\t\r "):
333
334 # Fundamental syntactic units and literals
335 g.sqlComment = Regex("--[^\n\r]*")
336 g.whitespace = Word(" \t\n") # need that as a hack now and then to keep
337 # numbers and identifiers from sticking
338
339 g.unsignedInteger = Regex(r"\d+")
340 g.unsignedInteger.setName("unsigned integer")
341 exactNumericRE = r"\d+(\.(\d+)?)?|\.\d+"
342 g.exactNumericLiteral = Regex(exactNumericRE)
343 g.approximateNumericLiteral = Regex(r"(?i)(%s)E[+-]?\d+"%exactNumericRE)
344 g.unsignedHexadecimal = Regex("0[xX][0-9A-Fa-f]+"
345 ).addParseAction(lambda s,p,t: str(int(t[0], 16))
346 )
347 g.unsignedHexadecimal.setName("numeric literal")
348 g.unsignedNumericLiteral = (
349 g.unsignedHexadecimal
350 | g.approximateNumericLiteral
351 | g.exactNumericLiteral)
352 g.unsignedNumericLiteral.setName("numericLiteral")
353 g.characterStringLiteral = sglQuotedString + ZeroOrMore( sglQuotedString )
354 g.generalLiteral = g.characterStringLiteral.copy()
355 g.literalWithUnit = Forward()
356 g.unsignedLiteral = g.literalWithUnit ^ g.unsignedNumericLiteral
357 # !!! DEVIATION: we're not accepting | generalLiteral here.
358 g.sign = Literal("+") | "-"
359 g.signedInteger = (Optional( g.sign )
360 + g.unsignedInteger)
361 g.signedInteger.setName("signed integer")
362 g.nullLiteral = CaselessKeyword("NULL")
363 g.nullLiteral.setName("NULL")
364
365 g.regularIdentifier = RegularIdentifier(ALL_RESERVED_WORDS)
366 g.regularIdentifier.setName("identifier")
367 # There's a bug with QuotedString in some versions of pyparsing.
368 # So, don't use this:
369 # delimitedIdentifier = QuotedString(quoteChar='"', escQuote='"',
370 # unquoteResults=True).addParseAction(
371 # lambda s,p,t: utils.QuotedName(str(t)))
372 # but rather
373 g.delimitedIdentifier = Regex('("[^"]*")+').addParseAction(
374 _makeQuotedName)
375 g.delimitedIdentifier.setName("delimited identifier")
376 g.identifier = g.regularIdentifier | g.delimitedIdentifier
377
378 # Operators
379 g.compOp = Regex("=|!=|<=|>=|<>|<|>")
380 g.compOp.setName("comparison operator")
381 g.multOperator = Literal("*") | Literal("/")
382 g.addOperator = Literal("+") | Literal("-")
383 g.notKeyword = CaselessKeyword("NOT")
384
385 # Column names and such
386 g.columnName = g.identifier.copy()
387 g.columnName.setName("column name")
388 g.correlationName = g.identifier.copy()
389 g.qualifier = (g.identifier
390 + Optional( "." + g.identifier )
391 + Optional( "." + g.identifier ))
392 g.tableName = g.qualifier("tableName")
393 g.uploadTableName = (CaselessKeyword("tap_user")
394 + Optional( "." + g.identifier )
395 + Optional( "." + g.identifier ))("tableName")
396 g.columnReferenceByUCD = (
397 CaselessKeyword("UCDCOL")
398 + '(' + g.characterStringLiteral + ')')
399 g.columnReference = (
400 g.columnReferenceByUCD
401 | g.identifier
402 + Optional( "." + g.identifier )
403 + Optional( "." + g.identifier )
404 + Optional( "." + g.identifier ))
405 g.columnReference.setName("column reference")
406 g.asClause = Optional(CaselessKeyword("AS")) + g.columnName("alias")
407
408 g.valueExpression = Forward()
409
410 # set functions
411 g.setFunctionType = Regex("(?i)AVG|MAX|MIN|SUM|COUNT|STDDEV")
412 g.setQuantifier = Regex("(?i)DISTINCT|ALL")
413 g.generalSetFunction = (g.setFunctionType("fName")
414 + '(' + Optional(g.setQuantifier) + Args(g.valueExpression) + ')')
415 g.countAll = (CaselessLiteral("COUNT")("fName")
416 + '(' + Args(Literal('*')) + ')')
417 g.setFunctionSpecification = (g.countAll | g.generalSetFunction)
418
419 # cast
420 g.castOperand = (
421 g.valueExpression
422 | g.nullLiteral)
423 g.castOperand.setName("value to cast")
424 g.length = g.unsignedInteger | '*'
425 g.sqlTypeLength = Literal("(") - g.length - Literal(")")
426 g.sqlAtomType = (
427 ((CaselessKeyword("CHAR") | CaselessKeyword("VARCHAR"))
428 + Optional(g.sqlTypeLength))
429 | (CaselessKeyword("NATIONAL") - CaselessKeyword("CHAR")
430 + Optional(g.sqlTypeLength))
431 | CaselessKeyword("INTEGER")
432 | CaselessKeyword("BIGINT")
433 | CaselessKeyword("SMALLINT")
434 | CaselessKeyword("REAL")
435 | CaselessKeyword("DOUBLE") + CaselessKeyword("PRECISION")
436 | CaselessKeyword("TIMESTAMP")
437 | CaselessKeyword("POINT")
438 | CaselessKeyword("CIRCLE")
439 | CaselessKeyword("POLYGON"))
440 g.sqlArraySpec = (Literal("[")
441 + Optional(g.unsignedInteger)
442 + Literal("]"))
443 g.castTarget = (g.sqlAtomType
444 + Optional(g.sqlArraySpec)).addParseAction(
445 lambda s,p,t: " ".join(t).upper())
446 g.castSpecification = (
447 CaselessLiteral("CAST")
448 - "(" + g.castOperand.setResultsName("value")
449 - CaselessLiteral("AS")
450 + g.castTarget.setResultsName("newType") - ')')
451
452 # new-style units
453 g.unitLiteral = Regex(r"\{[^}]+\}").addParseAction(_parseVOUnit)
454 g.unitCoercion = Literal('@')
455 g.literalWithUnit << g.unsignedNumericLiteral - g.unitLiteral
456
457 # value expressions
458 g.arrayReference = (
459 g.columnReference
460 + Literal('[')
461 + g.valueExpression
462 + Literal(']'))
463 g.valueExpressionPrimary = (
464 CaselessKeyword("NULL")
465 | g.unsignedLiteral
466 | g.arrayReference
467 | g.columnReference
468 | g.setFunctionSpecification
469 # this should allow whole character value expressions by the
470 # spec. If we ever actually want that, we'd have to see how
471 # to avoid infinite recursion.
472 | g.generalLiteral
473 | '(' + g.valueExpression + ')'
474 | g.castSpecification)
475 g.valueExpressionPrimary.setName("value expression")
476
477 # string literal stuff
478 g.characterPrimary = Forward()
479 g.characterPrimary.setName("String expression")
480 g.characterFactor = g.characterPrimary
481 g.characterValueExpression = (g.characterFactor +
482 ZeroOrMore("||" + g.characterFactor))
483 g.stringValueExpression = g.characterValueExpression
484
485 # numeric expressions/terms
486 g.numericValueExpression = Forward()
487 g.numericValueExpression.setName("Numeric expression")
488 g.numericValueFunction = Forward()
489 g.numericValueFunction.setName("Numeric value function")
490 g.numericExpressionPrimary = (
491 g.unsignedLiteral
492 | g.columnReference
493 | g.setFunctionSpecification
494 | '(' + g.valueExpression + ')')
495 g.numericPrimary = (
496 g.numericValueFunction
497 | g.valueExpressionPrimary)
498 g.numericPrimary.setName("numeric expression")
499 g.plainFactor = Optional(g.sign) + g.numericPrimary
500 g.coercedFactor = (
501 g.plainFactor - g.unitCoercion - g.unitLiteral("toUnit"))
502
503 g.factor = g.coercedFactor ^ g.plainFactor
504 g.factor.setName("Numeric factor")
505 g.term = (g.factor
506 + ZeroOrMore(g.multOperator + g.factor))
507 g.term.setName("Numeric term")
508 g.numericValueExpression << (
509 g.term + ZeroOrMore(g.addOperator + g.term))
510 g.numericValueExpression.setName("numeric expression")
511 g.nvArgs = Args(g.numericValueExpression)
512
513 # geometry types and expressions
514 g.userDefinedFunction = Forward()
515 g.userDefinedFunction.setName("User defined function")
516 g.geometryValueExpression = Forward()
517 g.geometryValueExpression.setName("Geometry expression")
518 g.tapCoordLiteral = Regex("(?i)'(?P<sys>%s)'"%"|".join(stc.TAP_SYSTEMS)
519 ).addParseAction(lambda s,p,t: t["sys"].upper()
520 )
521 g.tapCoordLiteral.setName("coordinate system literal (ICRS, GALACTIC,...)")
522 g.coordSys = (g.tapCoordLiteral
523 | g.nullLiteral.copy().addParseAction(lambda s,p,t: "UNKNOWN")
524 ).setResultsName("coordSys")
525 g.coordSys.setName("coordinate system literal (ICRS, GALACTIC,...)")
526 g.coordinates = (g.nvArgs + ',' + g.nvArgs)
527 g.box = (CaselessKeyword("BOX")("fName")
528 - '(' + Optional(g.coordSys + ',')
529 + g.coordinates + ','
530 + g.coordinates + ')')
531 g.point = (CaselessKeyword("POINT")("fName")
532 - '(' + Optional(g.coordSys - ',')
533 + g.coordinates + ')')
534 g.coordValue = (
535 g.userDefinedFunction
536 | g.point
537 | g.columnReference)
538
539 g.circleSplitCooArgs = (g.coordinates + ',' - g.nvArgs)
540 g.circlePointCooArgs = (
541 Args(g.coordValue) + ','
542 - g.nvArgs)
543 g.circle = (CaselessKeyword("CIRCLE")("fName")
544 - '(' + Optional(g.coordSys + ',')
545 + (g.circleSplitCooArgs | g.circlePointCooArgs)
546 + ')')
547
548 g.polygonSplitCooArgs = (g.coordinates
549 + ',' + g.coordinates
550 + OneOrMore( ',' + g.coordinates ))
551 g.polygonPointCooArgs = (Args(g.coordValue)
552 - ',' - Args(g.coordValue)
553 - OneOrMore(',' - Args(g.coordValue)))
554 g.polygon = (CaselessKeyword("POLYGON")("fName")
555 - '(' + Optional(g.coordSys + ',')
556 + Args(g.polygonSplitCooArgs | g.polygonPointCooArgs)
557 + ')')
558
559 g.mocArgs = (
560 Args(g.stringValueExpression)
561 ^ Args(
562 g.numericValueExpression) - ','
563 - Args(g.geometryValueExpression))
564 g.moc = (CaselessKeyword("MOC")("fName")
565 - '(' + g.mocArgs + ')')
566
567 g.region = (CaselessKeyword("REGION")("fName")
568 + '('
569 + Args(g.stringValueExpression) + ')')
570 g.geometryExpression = (g.box
571 | g.point
572 | g.circle
573 | g.polygon
574 | g.region
575 | g.moc)
576 g.geometryValue = g.columnReference.copy()
577 g.centroid = (CaselessKeyword("CENTROID")("fName")
578 + '(' + Args(g.geometryValueExpression) + ')')
579 g.geometryValueExpression << (g.geometryExpression
580 | g.userDefinedFunction
581 | g.geometryValue
582 | g.centroid)
583 g.geometryValueExpression.setName("geometry value expression")
584
585 # geometry functions
586 g.distanceSplitCooArgs = (g.coordinates + ','
587 + g.coordinates)
588 g.distanceSplitCooArgs.setName("Numeric coordinates")
589 g.distancePointCooArgs = (Args(g.coordValue) + ','
590 + Args(g.coordValue))
591 g.distancePointCooArgs.setName("Geometry argument")
592 g.distanceFunction = (CaselessKeyword("DISTANCE")("fName")
593 - '(' + (g.distanceSplitCooArgs | g.distancePointCooArgs) + ')')
594 g.pointFunction = (Regex("(?i)COORD[12]|COORDSYS")("fName") + '(' +
595 Args(g.coordValue) + ')')
596 g.area = (CaselessKeyword("AREA")("fName")
597 + '(' + Args(g.geometryValueExpression) + ')')
598 g.nonPredicateGeometryFunction = (
599 g.distanceFunction
600 | g.pointFunction
601 | g.area )
602 g.predicateGeoFunctionName = Regex("(?i)CONTAINS|INTERSECTS")
603 g.predicateGeometryFunction = (g.predicateGeoFunctionName("fName")
604 + '(' + Args(g.geometryValueExpression)
605 + ',' + Args(g.geometryValueExpression) + ')')
606 g.numericGeometryFunction = (g.predicateGeometryFunction
607 | g.nonPredicateGeometryFunction)
608
609 # numeric, system, user defined functions
610 g.trig1ArgFunctionName = Regex("(?i)ACOS|ASIN|ATAN|COS|COT|SIN|TAN")
611 # trig1ArgFunction is what causes a parse failure on common numeric
612 # value expressions. We take the liberty of misnaming it for better
613 # error messages in most cases.
614 g.trig1ArgFunctionName.setName("numeric expression")
615 g.trigFunction = (
616 g.trig1ArgFunctionName("fName") + '('
617 + g.nvArgs + ')'
618 | CaselessKeyword("ATAN2")("fName") + '('
619 + g.nvArgs + ','
620 + g.nvArgs + ')')
621 g.math0ArgFunctionName = Regex("(?i)PI")
622 g.optIntFunctionName = Regex("(?i)RAND")
623 g.math1ArgFunctionName = Regex("(?i)ABS|CEILING|DEGREES|EXP|FLOOR|LOG10|"
624 "LOG|RADIANS|SQUARE|SQRT|BITWISE_NOT")
625 g.optPrecArgFunctionName = Regex("(?i)ROUND|TRUNCATE")
626 g.math2ArgFunctionName = Regex("(?i)POWER|MOD|BITWISE_AND|BITWISE_OR"
627 "|BITWISE_XOR")
628 g.mathFunction = (
629 g.math0ArgFunctionName("fName") + '(' + ')'
630 | g.optIntFunctionName("fName") + '('
631 + Optional( Args(g.unsignedInteger) ) + ')'
632 | g.math1ArgFunctionName("fName") + '('
633 + g.nvArgs + ')'
634 | g.optPrecArgFunctionName("fName") + '('
635 + g.nvArgs +
636 Optional( ',' + Args(g.signedInteger) ) + ')'
637 | g.math2ArgFunctionName("fName") + '('
638 + g.nvArgs
639 + ',' + g.nvArgs + ')')
640 g.inUnitFunction = (
641 CaselessKeyword("IN_UNIT")
642 - '('
643 - g.numericValueExpression
644 - ','
645 - g.characterStringLiteral
646 - ')')
647 g.scalarArray1FunctionName = Regex(
648 "(?i)arr_(min|max|avg|stddev|sum|count)")
649 g.arrayFunctionArguments = Literal('(') - g.nvArgs - ')'
650 g.arrayFunctionArguments.setName("array function argument")
651 g.scalarArray1Function = (
652 g.scalarArray1FunctionName("fName")
653 - g.arrayFunctionArguments)
654 g.scalarArray2FunctionName = Regex("(?i)arr_dot")
655 g.scalarArray2Function = (
656 g.scalarArray2FunctionName("fName")
657 - '(' - g.nvArgs - ',' - g.nvArgs - ')')
658 g.scalarArrayFunction = (
659 g.scalarArray2Function
660 | g.scalarArray1Function)
661
662 g.arrayMapFunction = (
663 CaselessKeyword("arr_map")("fName") - '('
664 - Args(g.numericValueExpression)
665 - ',' - g.nvArgs - ')')
666
667 g.userDefinedFunctionParam = g.valueExpression
668 g.userDefinedFunctionName = Regex("(?i)"+userFunctionPrefix+"_[A-Za-z_]+")
669 g.userDefinedFunctionName.setName("Name of locally defined function")
670 g.userDefinedFunction << (g.userDefinedFunctionName("fName")
671 + '('
672 + Optional(Args(g.userDefinedFunctionParam)
673 + ZeroOrMore("," + Args(g.userDefinedFunctionParam)))
674 + ')')
675
676 g.numericValueFunction << (g.trigFunction
677 | g.mathFunction
678 | g.inUnitFunction
679 | g.scalarArrayFunction
680 | g.arrayMapFunction
681 | g.userDefinedFunction
682 | g.numericGeometryFunction)
683
684 g.foldFunction = (
685 (CaselessKeyword("UPPER") | CaselessKeyword("LOWER"))("fName")
686 - '(' + Args(g.characterValueExpression) + ')' )
687 g.stringValueFunction = g.foldFunction
688
689 g.characterPrimary << (
690 g.stringValueFunction
691 | g.generalLiteral
692 | g.userDefinedFunction
693 | g.valueExpressionPrimary)
694
695 g.timestampFunction = (
696 CaselessKeyword('TIMESTAMP')("fName") - '('
697 + Args(g.stringValueExpression) - ')')
698 g.dateValueExpression = (g.timestampFunction)
699
700 g.coalesceExpression = (
701 CaselessKeyword('COALESCE') - '('
702 + Args(g.valueExpression)
703 + ZeroOrMore(',' + Args(g.valueExpression)) - ')')
704
705 g.searchCondition = Forward()
706 g.searchCondition.setName("Condition")
707 g.caseResult = g.valueExpression
708 g.searchedWhenClause = (
709 CaselessKeyword('WHEN')
710 + g.searchCondition
711 + CaselessKeyword('THEN')
712 + g.caseResult)
713 g.simpleWhenClause = (
714 CaselessKeyword('WHEN')
715 + g.valueExpression
716 + CaselessKeyword('THEN')
717 + g.caseResult)
718 g.caseElseClause = CaselessKeyword('ELSE') + g.caseResult
719 g.searchedCase = (
720 CaselessKeyword('CASE')
721 + OneOrMore(g.searchedWhenClause)
722 + Optional(g.caseElseClause)
723 - CaselessKeyword('END'))
724 g.simpleCase = (
725 CaselessKeyword('CASE')
726 + g.valueExpression
727 + OneOrMore(g.simpleWhenClause)
728 + Optional(g.caseElseClause)
729 - CaselessKeyword('END'))
730 g.caseExpression = (
731 g.coalesceExpression
732 | g.searchedCase
733 | g.simpleCase)
734
735 # toplevel value expression
736 g.valueExpression << (
737 LongestMatch([
738 g.caseExpression,
739 g.numericValueExpression,
740 g.stringValueExpression,
741 g.dateValueExpression,
742 g.geometryValueExpression]))
743 g.valueExpression.setName("value expression")
744 g.derivedColumn = g.valueExpression("expr") + Optional(g.asClause)
745
746 # parts of select clauses
747 g.setQuantifier = (CaselessKeyword( "DISTINCT" )
748 | CaselessKeyword( "ALL" ))("setQuantifier")
749 g.setLimit = CaselessKeyword( "TOP" ) - g.unsignedInteger("setLimit")
750 g.offsetSpec = CaselessKeyword( "OFFSET" )- g.unsignedInteger("offset")
751 g.qualifiedStar = g.qualifier + "." + "*"
752 g.selectSublist = (g.qualifiedStar | g.derivedColumn
753 ).setResultsName("fieldSel", listAllMatches=True)
754 g.selectSublist.setName("select list item")
755 g.selectList = (Literal("*")("starSel")
756 | g.selectSublist + ZeroOrMore("," - g.selectSublist)
757 )
758 g.selectList.setName("select list")
759
760 # boolean terms
761 g.subquery = Forward()
762 g.subquery.setName("Subquery")
763 g.comparisonPredicate = g.valueExpression + g.compOp + g.valueExpression
764 g.betweenPredicate = (g.valueExpression
765 + Optional(g.notKeyword)
766 + CaselessKeyword("BETWEEN")
767 - g.valueExpression
768 + CaselessKeyword("AND")
769 - g.valueExpression)
770 g.inValueList = g.valueExpression + ZeroOrMore(',' + g.valueExpression)
771 g.inPredicateValue = g.subquery | ("(" + g.inValueList + ")")
772 g.inPredicate = (g.valueExpression + Optional(g.notKeyword)
773 + CaselessKeyword("IN") + g.inPredicateValue)
774 g.existsPredicate = CaselessKeyword("EXISTS") - g.subquery
775 g.likePredicate = (
776 g.characterValueExpression
777 + Optional(g.notKeyword)
778 + (CaselessKeyword("LIKE") | CaselessKeyword("ILIKE"))
779 + g.characterValueExpression)
780 g.nullPredicate = (g.columnReference
781 + CaselessKeyword("IS")
782 + Optional(g.notKeyword) - g.nullLiteral)
783 g.predicate = (g.comparisonPredicate
784 | g.betweenPredicate
785 | g.inPredicate
786 | g.likePredicate
787 | g.nullPredicate
788 | g.existsPredicate)
789 g.booleanPrimaryOpener = Literal('(') # for error messages
790 g.booleanPrimaryOpener.setName("boolean expression")
791 g.booleanPrimary = (
792 g.booleanPrimaryOpener + g.searchCondition + ')'
793 | g.predicate)
794 g.booleanPrimary.setName("boolean expression")
795 g.booleanFactor = Optional(g.notKeyword) + g.booleanPrimary
796 g.booleanTerm = (g.booleanFactor +
797 ZeroOrMore(CaselessKeyword("AND") - g.booleanFactor))
798
799 # WHERE clauses and such
800 g.searchCondition << (g.booleanTerm
801 + ZeroOrMore(CaselessKeyword("OR") - g.booleanTerm)
802 )
803 g.searchCondition.setName("search condition")
804 g.whereClause = (CaselessKeyword("WHERE")
805 - g.searchCondition)("whereClause")
806
807 # Referencing tables
808 g.queryExpression = Forward()
809 g.queryExpression.setName("Query expression")
810 g.correlationSpecification = (
811 Optional(CaselessKeyword("AS") | g.whitespace)
812 + g.correlationName("alias"))
813 g.subqueryOpener = Literal('(') # for error reporting
814 g.subqueryOpener.setName("subquery")
815 g.subquery << (g.subqueryOpener + g.queryExpression + ')')
816 g.derivedTable = g.subquery.copy() + g.correlationSpecification
817 g.tablesample = (CaselessKeyword("TABLESAMPLE")
818 - Literal('(')
819 - g.unsignedNumericLiteral
820 - Literal(')'))
821 g.possiblyAliasedTable = (
822 (g.uploadTableName | g.tableName)
823 + Optional(g.correlationSpecification)
824 + Optional(g.tablesample)("tablesample"))
825 g.setGeneratingFunction = (
826 CaselessKeyword("generate_series")
827 - Literal('(')
828 - g.nvArgs
829 - ','
830 - g.nvArgs
831 - Literal(')')
832 + Optional(g.correlationSpecification))
833 g.joinedTable = Forward()
834 g.subJoin = '(' + g.joinedTable + ')'
835 g.joinOperand = (
836 g.setGeneratingFunction
837 | g.possiblyAliasedTable
838 | g.derivedTable
839 | g.subJoin).setName("Join Operand")
840 g.tableReference = (
841 g.joinedTable
842 | g.possiblyAliasedTable
843 | g.derivedTable)
844 g.tableReference.setName("table reference")
845
846 # JOINs
847 g.columnNameList = (
848 g.columnName
849 + ZeroOrMore( "," + g.columnName)
850 )
851 g.columnNameList.setName("column name list")
852 g.namedColumnsJoin = (
853 CaselessKeyword("USING")
854 + '(' + g.columnNameList("columnNames") + ')')
855 g.joinCondition = CaselessKeyword("ON") - g.searchCondition
856 g.joinSpecification = g.joinCondition | g.namedColumnsJoin
857 g.outerJoinType = (CaselessKeyword("LEFT")
858 | CaselessKeyword("RIGHT")
859 | CaselessKeyword("FULL"))
860 g.joinType = (CaselessKeyword("INNER")
861 | (g.outerJoinType + Optional(CaselessKeyword("OUTER")))
862 | CaselessKeyword("CROSS")) # local extension
863 g.joinOperator = (Optional(CaselessKeyword("NATURAL"))
864 + Optional(g.joinType)
865 + CaselessKeyword("JOIN"))
866 g.joinedTable << (g.joinOperand
867 + ZeroOrMore(g.joinOperator
868 + g.joinOperand
869 + Optional(g.joinSpecification))).setName("Joined Table")
870
871 # Detritus in table expressions
872 g.groupByClause = (CaselessKeyword("GROUP") + CaselessKeyword("BY")
873 + g.valueExpression
874 + ZeroOrMore(',' + g.valueExpression))("groupby")
875 g.havingClause = (CaselessKeyword("HAVING")
876 + g.searchCondition)("having")
877 g.orderingSpecification = (Regex("(?i)ASC|DESC"))
878 g.sortKey = g.valueExpression
879 g.sortSpecification = g.sortKey + Optional(g.orderingSpecification)
880 g.orderByClause = (CaselessKeyword("ORDER")
881 + CaselessKeyword("BY") + g.sortSpecification
882 + ZeroOrMore( ',' + g.sortSpecification ))("orderBy")
883
884 # FROM fragments and such
885 g.fromClause = (Suppress(CaselessKeyword("FROM").setName("FROM"))
886 + g.tableReference
887 + ZeroOrMore(Suppress(',') - g.tableReference))("fromClause")
888 g.tableExpression = (g.fromClause
889 + Optional(g.whereClause)
890 + Optional(g.groupByClause)
891 + Optional(g.havingClause)
892 + Optional(g.orderByClause))
893
894 # Common Table Expressions
895 g.selectExpression = Forward().setName("Select expression")
896 g.querySetExpression = Forward()
897 g.querySetTerm = Forward()
898
899 g.withQuery = (g.regularIdentifier("queryName")
900 + CaselessKeyword("AS")
901 + '(' + g.selectExpression + ')')
902 g.withSpecification = (CaselessLiteral("WITH")
903 + g.withQuery + ZeroOrMore(',' + g.withQuery) )
904
905 # toplevel select clause and set operators
906 g.selectQuery = (CaselessKeyword("SELECT").setName("SELECT")
907 + Optional(g.setQuantifier)
908 + Optional(g.setLimit)
909 + g.selectList + g.tableExpression)
910
911 g.optionalAll = Optional(CaselessKeyword("ALL"))
912 g.intersectOperator = (
913 CaselessKeyword("INTERSECT")
914 + g.optionalAll)
915 g.additiveSetOperator = ((
916 CaselessKeyword("UNION")
917 | CaselessKeyword("EXCEPT") )
918 + g.optionalAll)
919
920 # I had to rewrite a few of the following ones to avoid pyparse
921 # infinite recursions.
922 g.querySetPrimary = MatchFirstWithSaneError([
923 g.selectQuery,
924 '(' + g.selectExpression + ')'])
925 g.querySetTerm << (
926 g.querySetPrimary
927 + ZeroOrMore(g.intersectOperator + g.querySetExpression))
928 g.querySetExpression << (
929 g.querySetTerm
930 + ZeroOrMore(g.additiveSetOperator + g.querySetTerm))
931
932 g.selectExpression << (
933 g.querySetExpression
934 + Optional(g.offsetSpec))
935 g.queryExpression << (g.selectExpression | g.joinedTable).setName(
936 "Query Expression")
937
938 g.querySpecification = Optional(g.withSpecification) + g.selectExpression
939
940 g.createAs = (
941 CaselessKeyword("CREATE")
942 - CaselessKeyword("TABLE")
943 - g.uploadTableName
944 - CaselessKeyword("AS"))
945 g.statement = (
946 Optional(g.createAs)
947 + g.querySpecification + Suppress(Optional(White()) + StringEnd()))
948
949 g.statement.ignore(g.sqlComment)
950 return g.getSymbols_(), g.statement
951
952
953 _grammarCache = None
954
955 def enableDebug(syms, debugNames=None): # pragma: no cover
956 if not debugNames:
957 debugNames = syms
958 for name in debugNames:
959 ob = syms[name]
960 if not ob.debug:
961 ob.setDebug(True)
962 ob.setName(name)
963 if "sqlComment" in syms:
964 syms["sqlComment"].setDebug(False)
965
966
967 def enableTree(syms): # pragma: no cover
968 def makeAction(name):
969 def action(s, pos, toks):
970 return [name, toks]
971 return action
972 for name in syms:
973 ob = syms[name]
974 if not ob.debug:
975 ob.setDebug(True)
976 ob.setName(name)
977 ob.addParseAction(makeAction(name))
978
979
980 @functools.lru_cache(1)
981 def getADQLGrammar():
982 """returns a pair of (symbols, root) for an ADQL grammar.
983
984 This probably is mainly useful for testing. At least you should not set
985 names or parseActions on whatever you are returned unless you are
986 testing.
987 """
988 return getADQLGrammarCopy([])
989
990
991 if __name__=="__main__": # pragma: no cover
992 def printCs(s, pos, toks):
993 print("---------------Tokens:", toks)
994 import pprint
995 syms, grammar = getADQLGrammar()
996 enableTree(syms)
997 res = syms["statement"].parseString(
998 """select 4.5@{km} from misc
999 """
1000 , parseAll=True)
1001 pprint.pprint(res.asList(), stream=sys.stderr)