Debian Codegraph @

gavo/adql/nodes.py

raw
1 """
2 Node classes and factories used in ADQL tree processing.
3 """
4
5 #c Copyright 2008-2025, the GAVO project <[email protected]>
6 #c
7 #c This program is free software, covered by the GNU GPL. See the
8 #c COPYING file in the source distribution.
9
10
11 import fnmatch
12 import functools
13 import itertools
14 import re
15 import sys
16 import traceback
17 import weakref
18 from functools import reduce
19
20 from gavo import stc
21 from gavo import utils
22 from gavo.adql import common
23 from gavo.adql import fieldinfo
24 from gavo.adql import fieldinfos
25 from gavo.adql import grammar
26 from gavo.stc import tapstc
27 from gavo.utils import parsetricks
28
29 DEBUG_BUILDERS = False
30
31
32 ################ Various helpers
33
34 class ReplaceNode(utils.ExecutiveAction):
35 """can be raised by code in the constructor of an ADQLNode to replace
36 itself.
37
38 It is constructed with the (single) ADQLNode that should stand in its
39 stead.
40
41 This is intended as a special service for ufuncs that want to insert
42 complex, annotatable expressions. We also use that in certain situations
43 when casting.
44 """
45 def __init__(self, replacingNode):
46 self.replacingNode = replacingNode
47
48
49 def symbolAction(*symbols):
50 """is a decorator to mark functions as being a parseAction for symbol.
51
52 This is evaluated by getADQLGrammar below. Be careful not to alter
53 global state in such a handler.
54 """
55 def deco(func):
56 for symbol in symbols:
57 if hasattr(func, "parseActionFor"):
58 # plan for double decoration (so don't worry about no coverage)
59 func.parseActionFor.append(symbol)
60 else:
61 func.parseActionFor = [symbol]
62
63 if DEBUG_BUILDERS:
64 def handler(parseResult):
65 try:
66 return func(parseResult)
67 except Exception:
68 sys.stderr.write(f"While executing {func} on {parseResult}:\n")
69 traceback.print_exc()
70 func.fromParseResult = handler
71 else:
72 func.fromParseResult = func
73 return func
74 return deco
75
76
77 def getType(arg):
78 """returns the type of an ADQL node or the value of str if arg is a string.
79 """
80 if isinstance(arg, str):
81 return str
82 else:
83 return arg.type
84
85
86 def flatten(arg):
87 """returns the SQL serialized representation of arg.
88 """
89 if isinstance(arg, str):
90 return arg
91
92 elif isinstance(arg, (int, float)):
93 return repr(arg)
94
95 elif isinstance(arg, parsetricks.ParseResults):
96 return " ".join(flatten(c) for c in arg)
97
98 # elif arg is None: import pdb;pdb.Pdb(nosigint=True).set_trace()
99
100 else:
101 return arg.flatten()
102
103
104 def autocollapse(nodeBuilder, children):
105 """inhibts the construction via nodeBuilder if children consists of
106 a single ADQLNode.
107
108 This function will automatically be inserted into the the constructor
109 chain if the node defines an attribute collapsible=True.
110 """
111 if len(children)==1 and isinstance(children[0], ADQLNode):
112 return children[0]
113 return nodeBuilder.fromParseResult(children)
114
115
116 def collectUserData(infoChildren):
117 userData, tainted = (), False
118 for c in infoChildren:
119 userData = userData+c.fieldInfo.userData
120 tainted = tainted or c.fieldInfo.tainted
121 return userData, tainted
122
123
124 def flattenKWs(obj, *fmtTuples):
125 """returns a string built from the obj according to format tuples.
126
127 A format tuple is consists of a literal string, and
128 an attribute name. If the corresponding attribute is
129 non-None, the plain string and the flattened attribute
130 value are inserted into the result string, otherwise
131 both are ignored.
132
133 Nonexisting attributes are taken to have None values.
134
135 To allow unconditional literals, the attribute name can
136 be None. The corresponding literal is always inserted.
137
138 All contributions are separated by single blanks.
139
140 This is a helper method for flatten methods of parsed-out
141 elements.
142 """
143 res = []
144 for literal, attName in fmtTuples:
145 if attName is None:
146 res.append(literal)
147 else:
148 if getattr(obj, attName, None) is not None:
149 if literal:
150 res.append(literal)
151 res.append(flatten(getattr(obj, attName)))
152 return " ".join(res)
153
154
155 def cleanNamespace(ns):
156 """removes all names starting with an underscore from the dict ns.
157
158 This is intended for _getInitKWs methods. ns is changed in place *and*
159 returned for convenience
160 """
161 return dict((k,v) for k,v in ns.items() if not k.startswith("_")
162 and k!="cls")
163
164
165 def getChildrenOfType(nodeSeq, type):
166 """returns a list of children of type typ in the sequence nodeSeq.
167 """
168 return [c for c in nodeSeq if getType(c)==type]
169
170
171 def getChildrenOfClass(nodeSeq, cls):
172 return [c for c in nodeSeq if isinstance(c, cls)]
173
174
175 class BOMB_OUT(object): pass
176
177 def _uniquify(matches, default, exArgs):
178 # helper method for getChildOfX -- see there
179 if len(matches)==0:
180 if default is not BOMB_OUT:
181 return default
182 raise common.NoChild(*exArgs)
183 if len(matches)!=1:
184 raise common.MoreThanOneChild(*exArgs)
185 return matches[0]
186
187
188 def getChildOfType(nodeSeq, type, default=BOMB_OUT):
189 """returns the unique node of type in nodeSeq.
190
191 If there is no such node in nodeSeq or more than one, a NoChild or
192 MoreThanOneChild exception is raised, Instead of raising NoChild,
193 default is returned if given.
194 """
195 return _uniquify(getChildrenOfType(nodeSeq, type),
196 default, (type, nodeSeq))
197
198
199 def getChildOfClass(nodeSeq, cls, default=BOMB_OUT):
200 """returns the unique node of class in nodeSeq.
201
202 See getChildOfType.
203 """
204 return _uniquify(getChildrenOfClass(nodeSeq, cls),
205 default, (cls, nodeSeq))
206
207
208 def parseArgs(parseResult):
209 """returns a sequence of ADQL nodes suitable as function arguments from
210 parseResult.
211
212 This is for cleaning up _parseResults["args"], i.e. stuff from the
213 Args symbol decorator in grammar.
214 """
215 args = []
216 for _arg in parseResult:
217 # _arg is either another ParseResult, an ADQL identifier, or an ADQLNode
218 if isinstance(_arg, (ADQLNode, str, utils.QuotedName)):
219 args.append(_arg)
220 else:
221 args.append(autocollapse(GenericValueExpression, _arg))
222 return tuple(args)
223
224
225 def getStringLiteral(node, description="Argument"):
226 """ensures that node only contains a constant string literal
227 and returns its value if so.
228
229 The function raises an adql.Error mentioning description otherwise.
230 """
231 if node.type!='characterStringLiteral':
232 raise common.Error(
233 "%s must be a constant string literal"%description)
234
235 return node.value
236
237
238
239 ######################### Misc helpers related to simple query planning
240
241 def _getDescendants(args):
242 """returns the nodes in the sequence args and all their descendants.
243
244 This is a helper function for when you have to analyse what's contributing
245 to complex terms.
246 """
247 descendants = list(args)
248 for arg in args:
249 if hasattr(arg, "iterTree"):
250 descendants.extend(c[1] for c in arg.iterTree())
251 return descendants
252
253
254 def iterFieldInfos(args):
255 """returns fieldInfo objects found within the children of the node list
256 args.
257 """
258 for desc in _getDescendants(args):
259 if getattr(desc, "fieldInfo", None) is not None:
260 yield desc.fieldInfo
261
262
263 def _isConstant(args):
264 """returns true if no columnReference-s are found below the node list args.
265 """
266 for desc in _getDescendants(args):
267 if getattr(desc, "type", None)=="columnReference":
268 return False
269 return True
270
271
272 def _estimateTableSize(args):
273 """returns an estimate for the size of a table mentioned in the node list
274 args.
275
276 Actually, we wait for the first column in fieldInfo userdata that has
277 a reference to a table that knows its nrows. If that comes, that's
278 our estimate. If it doesn't come, we return None.
279 """
280 for fi in iterFieldInfos(args):
281 if fi.ignoreTableStats:
282 return
283 for ud in fi.userData:
284 sizeEst = getattr(ud.parent, "nrows", None)
285 if sizeEst is not None:
286 return sizeEst
287
288 return None
289
290
291 def _sortLargeFirst(arg1, arg2):
292 """returns arga, argb such that arga deals with the larger table
293 if we can figure that out.
294
295 This is for distance; postgres in general only uses an index for them if the
296 point stands alone (rather than in the circle). So, it normally pays to have
297 the larger table first in our expressions (which are point op geom where
298 applicable).
299
300 This will also swap constant arguments second (so, into the circle).
301 """
302 if _isConstant([arg1]):
303 return arg2, arg1
304
305 if _isConstant([arg2]):
306 return arg1, arg2
307
308 size1, size2 = _estimateTableSize([arg1]), _estimateTableSize([arg2])
309
310 if size1 is None:
311 if size2 is None:
312 # we know nothing; don't change anything to keep the user in control
313 return arg1, arg2
314 else:
315 # we assume all large tables are nrows-annotated, so presumably
316 # arg1 isn't large. So, swap.
317 return arg2, arg1
318 else:
319 if size2 is None:
320 # see one comment up
321 return arg1, arg2
322 else:
323 if size1>size2:
324 return arg1, arg2
325 else:
326 return arg2, arg1
327
328
329
330 ######################### Generic Node definitions
331
332
333 class ADQLNode(utils.AutoNode):
334 """A node within an ADQL parse tree.
335
336 ADQL nodes may be parsed out; in that case, they have individual attributes
337 and are craftily flattened in special methods. We do this for nodes
338 that are morphed.
339
340 Other nodes basically just have a children attribute, and their flattening
341 is just a concatenation for their flattened children. This is convenient
342 as long as they are not morphed.
343
344 To derive actual classes, define
345
346 - the _a_<name> class attributes you need,
347 - the type (a nonterminal from the ADQL grammar)
348 - bindings if the class handles more than one symbol (in which case
349 type is ignored)
350 - a class method _getInitKWs(cls, parseResult); see below.
351 - a method flatten() -> string if you define a parsed ADQLNode.
352 - a method _polish() that is called just before the constructor is
353 done and can be used to create more attributes. There is no need
354 to call _polish of superclasses.
355
356 The _getInitKWs methods must return a dictionary mapping constructor argument
357 names to values. You do not need to manually call superclass _getInitKWs,
358 since the fromParseResult classmethod figures out all _getInitKWs in the
359 inheritance tree itself. It calls all of them in the normal MRO and updates
360 the argument dictionary in reverse order.
361
362 The fromParseResult class method additionally filters out all names starting
363 with an underscore; this is to allow easy returning of locals().
364 """
365 type = None
366
367 @classmethod
368 def fromParseResult(cls, parseResult):
369 try:
370 initArgs = {}
371 for superclass in reversed(cls.mro()):
372 if hasattr(superclass, "_getInitKWs"):
373 initArgs.update(superclass._getInitKWs(parseResult))
374 try:
375 return cls(**cleanNamespace(initArgs))
376 except TypeError:
377 raise common.BadKeywords("%s, %s"%(cls, cleanNamespace(initArgs)))
378 except ReplaceNode as rn:
379 return rn.replacingNode
380 except Exception:
381 if DEBUG_BUILDERS:
382 sys.stderr.write(f"While building {cls} on {parseResult}:\n")
383 traceback.print_exc()
384 raise
385
386 def _setupNode(self):
387 for cls in reversed(self.__class__.mro()):
388 if hasattr(cls, "_polish"):
389 cls._polish(self)
390 self._setupNodeNext(ADQLNode)
391
392 def __repr__(self):
393 return "<ADQL Node %s>"%(self.type)
394
395 def flatten(self):
396 """returns a string representation of the text content of the tree.
397
398 This default implementation will only work if you returned all parsed
399 elements as children. This, in turn, is something you only want to
400 do if you are sure that the node is question will not be morphed.
401
402 Otherwise, override it to create an SQL fragment out of the parsed
403 attributes.
404 """
405 return " ".join(flatten(c) for c in self.children)
406
407 def asTree(self):
408 res = []
409 for name, val in self.iterChildren():
410 if isinstance(val, ADQLNode):
411 res.append(val.asTree())
412 return self._treeRepr()+tuple(res)
413
414 def _treeRepr(self):
415 return (self.type,)
416
417 def iterTree(self):
418 for name, val in self.iterChildren():
419 if isinstance(val, ADQLNode):
420 for item in val.iterTree():
421 yield item
422 yield name, val
423
424
425 class TransparentMixin:
426 """a mixin just pulling through the children and serializing them.
427 """
428 _a_children = ()
429
430 @classmethod
431 def _getInitKWs(cls, _parseResult):
432 return {"children": list(_parseResult)}
433
434
435 class FieldInfoedNode(ADQLNode):
436 """An ADQL node that carries a FieldInfo.
437
438 This is true for basically everything in the tree below a derived
439 column. This class is the basis for column annotation.
440
441 You'll usually have to override addFieldInfo. The default implementation
442 just looks in its immediate children for anything having a fieldInfo,
443 and if there's exactly one such child, it adopts that fieldInfo as
444 its own, not changing anything.
445
446 FieldInfoedNode, when change()d, keep their field info. This is usually
447 what you want when morphing, but sometimes you might need adjustments.
448 """
449 fieldInfo = None
450
451 def _getInfoChildren(self):
452 return [c for c in self.iterNodeChildren() if hasattr(c, "fieldInfo")]
453
454 def addFieldInfo(self, context):
455 infoChildren = self._getInfoChildren()
456 if len(infoChildren)==1:
457 self.fieldInfo = infoChildren[0].fieldInfo
458 else:
459 if len(infoChildren):
460 msg = "More than one"
461 else:
462 msg = "No"
463 raise common.Error("%s child with fieldInfo with"
464 " no behaviour defined in %s, children %s"%(
465 msg,
466 self.__class__.__name__,
467 list(self.iterChildren())))
468
469 def change(self, **kwargs):
470 other = ADQLNode.change(self, **kwargs)
471 other.fieldInfo = self.fieldInfo
472 return other
473
474
475 class FunctionNode(FieldInfoedNode):
476 """An ADQLNodes having a function name and arguments.
477
478 The rules having this as action must use the Arg "decorator" in
479 grammar.py around their arguments and must have a string-valued
480 result "fName".
481
482 FunctionNodes have attributes args (unflattened arguments),
483 and funName (a string containing the function name, all upper
484 case).
485 """
486 _a_args = ()
487 _a_funName = None
488
489 @classmethod
490 def _getInitKWs(cls, _parseResult):
491 try:
492 args = parseArgs(_parseResult["args"]) #noflake: locals returned
493 except KeyError: # Zero-Arg function
494 pass
495 funName = _parseResult["fName"].upper() #noflake: locals returned
496 return locals()
497
498 def flatten(self):
499 return "%s(%s)"%(self.funName, ", ".join(flatten(a) for a in self.args))
500
501
502 class ColumnBearingNode(ADQLNode):
503 """A Node types defining selectable columns.
504
505 These are tables, subqueries, etc. This class is the basis for the
506 annotation of tables and subqueries.
507
508 Their getFieldInfo(name)->fi method gives annotation.FieldInfos
509 objects for their columns, None for unknown columns.
510
511 These keep their fieldInfos on a change()
512 """
513 fieldInfos = None
514 originalTable = None
515
516 def getFieldInfo(self, name):
517 if self.fieldInfos:
518 return self.fieldInfos.getFieldInfo(name)
519
520 def getAllNames(self): # pragma: no cover
521 """yields all relation names mentioned in this node.
522 """
523 raise TypeError("Override getAllNames for ColumnBearingNodes.")
524
525 def change(self, **kwargs):
526 other = ADQLNode.change(self, **kwargs)
527 other.fieldInfos = self.fieldInfos
528 return other
529
530
531 ############# Toplevel query language node types (for query analysis)
532
533 class TableName(ADQLNode):
534 type = "tableName"
535 _a_cat = None
536 _a_schema = None
537 _a_name = None
538
539 def __eq__(self, other):
540 if hasattr(other, "qName"):
541 return self.qName.lower()==other.qName.lower()
542 try:
543 return self.qName.lower()==other.lower()
544 except AttributeError:
545 # other has no lower, so it's neither a string nor a table name;
546 # thus, fall through to non-equal case
547 pass
548 return False
549
550 def __ne__(self, other):
551 return not self==other
552
553 def __bool__(self):
554 return bool(self.name)
555
556 def __str__(self):
557 return "TableName(%s)"%self.qName
558
559 def _polish(self):
560 # Implementation detail: We map tap_upload to temporary tables
561 # here; therefore, we can just nil out anything called tap_upload.
562 # If we need more flexibility, this probably is the place to implement
563 # the mapping (though on tap_user, we don't and create a different
564 # node).
565 if self.schema and self.schema.lower()=="tap_upload":
566 self.schema = None
567
568 self.qName = ".".join(flatten(n)
569 for n in (self.cat, self.schema, self.name) if n)
570 self.physicalName = self.qName
571
572 @classmethod
573 def _getInitKWs(cls, _parseResult):
574 _parts = _parseResult[::2]
575 cat, schema, name = [None]*(3-len(_parts))+_parts
576 return locals()
577
578 def flatten(self):
579 return self.qName
580
581 def lower(self):
582 """returns self's qualified name in lower case.
583 """
584 return self.qName.lower()
585
586 @staticmethod
587 def _normalizePart(part):
588 if isinstance(part, utils.QuotedName):
589 return part.name
590 else:
591 return part.lower()
592
593 def getNormalized(self):
594 """returns self's qualified name lowercased for regular identifiers,
595 in original capitalisation otherwise.
596 """
597 return ".".join(self._normalizePart(p)
598 for p in [self.cat, self.schema, self.name]
599 if p is not None)
600
601
602 class UploadTableName(TableName):
603 """a reference to a table in tap_upload.
604
605 In DaCHS these are mapped to tables in a magic schema, and their
606 interpretation depends on the current user. Here, using the class
607 we just give a sentinel to later components that something needs to be
608 done, specifically, establish the physical table name during anntation
609 and then making sure the node is morphed into that.
610 """
611 type = "uploadTableName"
612 fieldInfo = None
613
614 def addFieldInfo(self, context):
615 # we don't actually have field infos on this, but we need to find
616 # our physical name using the context's fieldInfoGetter.
617 # We have to call getInfosFor explicitly before we can do that,
618 # because the DaCHS' FieldInfoGetter only then retrieves that
619 # information from the database.
620 # By the way, I can't just query tap_user.tables here directly because
621 # down here I have no idea which user is running the query. Perhaps
622 # I should keep that info in the annotation context and get rid
623 # of this slightly insane indirection?
624 innerName = self.qName.lower()
625 context.fieldInfoGetter.getInfosFor(innerName)
626 self.physicalName = context.fieldInfoGetter.physicalNameMap[innerName]
627
628 def flatten(self):
629 # we flatten to our physicalName, because that's what the database
630 # will evaluate; note that before annotation, this will be the
631 # same as the ADQL-visible name. Yes, this is confusing behaviour,
632 # but I don't have a good idea on how to fix this.
633 if not re.match(r"tap_user\.[A-Za-z_]+$", self.physicalName):
634 raise NotImplementedError(
635 f"Not a regular table reference: {self.physicalName}")
636 return self.physicalName
637
638
639 class PlainTableRef(ColumnBearingNode):
640 """A reference to a simple table.
641
642 The tableName is the name this table can be referenced as from within
643 SQL, originalName is the name within the database; they are equal unless
644 a correlationSpecification has been given.
645 """
646 type = "possiblyAliasedTable"
647 _a_tableName = None # a TableName instance
648 _a_originalTable = None # a TableName instance
649 _a_wasAliased = False
650 _a_sampling = None
651
652 @classmethod
653 def _getInitKWs(cls, _parseResult):
654 if _parseResult.get("alias"):
655 tableName = TableName(name=_parseResult.get("alias"))
656 originalTable = _parseResult.get("tableName")
657 wasAliased = True
658 else:
659 tableName = getChildOfClass(_parseResult, TableName)
660 originalTable = tableName #noflake: locals returned
661 wasAliased = False
662
663 if _parseResult.get("tablesample"):
664 sampling = float(_parseResult.get("tablesample")[2])
665
666 return locals()
667
668 def addFieldInfos(self, context):
669 self.fieldInfos = fieldinfos.TableFieldInfos.makeForNode(self, context)
670
671 def _polish(self):
672 self.qName = flatten(self.tableName)
673
674 def flatten(self):
675 origTable = flatten(self.originalTable)
676 if self.wasAliased:
677 literal = "%s AS %s"%(origTable, flatten(self.tableName))
678 else:
679 literal = origTable
680
681 if self.sampling:
682 # TODO: Postgres dependency; this should be in morphpg
683 literal = "%s TABLESAMPLE SYSTEM (%s)"%(literal, self.sampling)
684
685 return literal
686
687 def getAllNames(self):
688 yield self.tableName.qName
689
690 def getAllTables(self):
691 yield self
692
693 def makeUpId(self):
694 # for suggestAName
695 n = self.tableName.name
696 if isinstance(n, utils.QuotedName):
697 return "_"+re.sub("[^A-Za-z0-9_]", "", n.name)
698 else:
699 return n
700
701
702 class DerivedTable(ColumnBearingNode):
703 type = "derivedTable"
704 _a_query = None
705 _a_tableName = None
706
707 def getFieldInfo(self, name):
708 return self.query.getFieldInfo(name)
709
710 def _get_fieldInfos(self):
711 return self.query.fieldInfos
712
713 def _set_fieldInfos(self, val):
714 self.query.fieldInfos = val
715 fieldInfos = property(_get_fieldInfos, _set_fieldInfos)
716
717 @classmethod
718 def _getInitKWs(cls, _parseResult):
719 tmp = {'tableName': TableName(name=str(_parseResult.get("alias"))),
720 'query': getChildOfClass(_parseResult, SelectExpression),
721 }
722 return tmp
723
724 def flatten(self):
725 return "(%s) AS %s"%(flatten(self.query), flatten(self.tableName))
726
727 def getAllNames(self):
728 yield self.tableName.qName
729
730 def getAllTables(self):
731 yield self
732
733 def makeUpId(self):
734 # for suggestAName
735 n = self.tableName.name
736 if isinstance(n, utils.QuotedName):
737 return "_"+re.sub("[^A-Za-z0-9_]", "", n.name)
738 else:
739 return n
740
741
742 class SetGeneratingFunction(ColumnBearingNode, TransparentMixin):
743 """a function that can stand instead of a table.
744
745 For starters, we only do generate_series here. Let's see where this
746 leads.
747 """
748 type = "setGeneratingFunction"
749 _a_functionName = None
750 _a_args = None
751 _a_name = None # name is both the name of the column and the "table"
752 # here. This will come from a correlationSpec where
753 # available. It's generate_series otherwise.
754
755 @classmethod
756 def _getInitKWs(cls, _parseResult):
757 functionName = _parseResult[0]
758 # TODO: We really should allow more than two arguments here
759 args = [_parseResult[2], _parseResult[4]]
760 name = _parseResult.get("alias")
761 if name is None:
762 name = functionName
763 return locals()
764
765 def _polish(self):
766 self.tableName = self.name
767
768 def getFieldInfo(self, name):
769 return self.fieldInfos.getFieldInfo(name)
770
771 def getAllTables(self):
772 yield self
773
774 def addFieldInfos(self, context):
775 # TODO: Infer types from argument types
776 self.fieldInfos = fieldinfos.FieldInfos(self, context)
777 self.fieldInfos.addColumn(self.name,
778 fieldinfo.FieldInfo("integer", None, None, sqlName=self.name))
779
780 def getAllNames(self):
781 yield self.name
782
783 def makeUpId(self):
784 return self.name
785
786
787 class JoinSpecification(ADQLNode, TransparentMixin):
788 """A join specification ("ON" or "USING").
789 """
790 type = "joinSpecification"
791
792 _a_children = ()
793 _a_predicate = None
794 _a_usingColumns = ()
795
796 @classmethod
797 def _getInitKWs(cls, _parseResult):
798 predicate = _parseResult[0].upper()
799 if predicate=="USING":
800 usingColumns = [ #noflake: locals returned
801 n for n in _parseResult["columnNames"] if n!=',']
802 children = list(_parseResult) #noflake: locals returned
803 return locals()
804
805
806 class JoinOperator(ADQLNode, TransparentMixin):
807 """the complete join operator (including all LEFT, RIGHT, ",", and whatever).
808 """
809 type = "joinOperator"
810
811 def isCrossJoin(self):
812 return self.children[0] in (',', 'CROSS')
813
814
815 class JoinedTable(ColumnBearingNode):
816 """A joined table.
817
818 These aren't made directly by the parser since parsing a join into
819 a binary structure is very hard using pyparsing. Instead, there's
820 the helper function makeJoinedTableTree handling the joinedTable
821 symbol that manually creates a binary tree.
822 """
823 type = None
824 originalTable = None
825 tableName = TableName()
826 qName = None
827
828 _a_leftOperand = None
829 _a_operator = None
830 _a_rightOperand = None
831 _a_joinSpecification = None
832
833 @classmethod
834 def _getInitKWs(cls, _parseResult):
835 leftOperand = _parseResult[0] #noflake: locals returned
836 operator = _parseResult[1] #noflake: locals returned
837 rightOperand = _parseResult[2] #noflake: locals returned
838 if len(_parseResult)>3:
839 joinSpecification = _parseResult[3] #noflake: locals returned
840 return locals()
841
842 def flatten(self):
843 js = ""
844 if self.joinSpecification is not None:
845 js = flatten(self.joinSpecification)
846 return "%s %s %s %s"%(
847 self.leftOperand.flatten(),
848 self.operator.flatten(),
849 self.rightOperand.flatten(),
850 js)
851
852 def addFieldInfos(self, context):
853 self.fieldInfos = fieldinfos.TableFieldInfos.makeForNode(self, context)
854
855 def _polish(self):
856 self.joinedTables = [self.leftOperand, self.rightOperand]
857
858 def getAllNames(self):
859 """iterates over all fully qualified table names mentioned in this
860 (possibly joined) table reference.
861 """
862 for t in self.joinedTables:
863 yield t.tableName.qName
864
865 def getTableForName(self, name):
866 return self.fieldInfos.locateTable(name)
867
868 def makeUpId(self):
869 # for suggestAName
870 return "_".join(t.makeUpId() for t in self.joinedTables)
871
872 def getJoinType(self):
873 """returns a keyword indicating how result rows are formed in this
874 join.
875
876 This can be NATURAL (all common columns are folded into one),
877 USING (check the joinSpecification what columns are folded),
878 CROSS (no columns are folded).
879 """
880 if self.operator.isCrossJoin():
881 if self.joinSpecification is not None:
882 raise common.Error("Cannot use cross join with a join predicate.")
883 return "CROSS"
884 if self.joinSpecification is not None:
885 if self.joinSpecification.predicate=="USING":
886 return "USING"
887 if self.joinSpecification.predicate=="ON":
888 return "CROSS"
889 return "NATURAL"
890
891 def getAllTables(self):
892 """returns all actual tables and subqueries (not sub-joins)
893 within this join.
894 """
895 res = []
896 def collect(node):
897 if hasattr(node.leftOperand, "leftOperand"):
898 collect(node.leftOperand)
899 else:
900 res.append(node.leftOperand)
901 if hasattr(node.rightOperand, "leftOperand"):
902 collect(node.rightOperand)
903 else:
904 res.append(node.rightOperand)
905 collect(self)
906 return res
907
908
909 class SubJoin(ADQLNode):
910 """A sub join (JoinedTable surrounded by parens).
911
912 The parse result is just the parens and a joinedTable; we need to
913 camouflage as that joinedTable.
914 """
915 type = "subJoin"
916 _a_joinedTable = None
917
918 @classmethod
919 def _getInitKWs(cls, _parseResult):
920 return {"joinedTable": _parseResult[1]}
921
922 def flatten(self):
923 return "("+self.joinedTable.flatten()+")"
924
925 def __getattr__(self, attName):
926 return getattr(self.joinedTable, attName)
927
928
929 @symbolAction("joinedTable")
930 def makeBinaryJoinTree(children):
931 """takes the parse result for a join and generates a binary tree of
932 JoinedTable nodes from it.
933
934 It's much easier to do this in a separate step than to force a
935 non-left-recursive grammar to spit out the right parse tree in the
936 first place.
937 """
938 children = list(children)
939 while len(children)>1:
940 if len(children)>3 and isinstance(children[3], JoinSpecification):
941 exprLen = 4
942 else:
943 exprLen = 3
944 args = children[:exprLen]
945 children[:exprLen] = [JoinedTable.fromParseResult(args)]
946 return children[0]
947
948
949 class TransparentNode(ADQLNode, TransparentMixin):
950 """An abstract base for Nodes that don't parse out anything.
951 """
952 type = None
953
954
955 class WhereClause(TransparentNode):
956 type = "whereClause"
957
958 class Grouping(TransparentNode):
959 type = "groupByClause"
960
961 class Having(TransparentNode):
962 type = "havingClause"
963
964 class OrderBy(TransparentNode):
965 type = "sortSpecification"
966
967 class OffsetSpec(ADQLNode):
968 type = "offsetSpec"
969
970 _a_offset = None
971
972 @classmethod
973 def _getInitKWs(cls, _parseResult):
974 return {"offset": int(_parseResult[1])}
975
976 def flatten(self):
977 if self.offset is not None:
978 # for morphpg, this never happens because _PGQS deals with it
979 # (and sets self.offset to None).
980 return "OFFSET %d"%self.offset
981 return ""
982
983
984 class SelectQuery(ColumnBearingNode):
985 type = "selectQuery"
986
987 _a_setQuantifier = None
988 _a_setLimit = None
989 _a_selectList = None
990 _a_fromClause = None
991 _a_whereClause = None
992 _a_groupby = None
993 _a_having = None
994 _a_orderBy = None
995
996 def _polish(self):
997 self.query = weakref.proxy(self)
998
999 @classmethod
1000 def _getInitKWs(cls, _parseResult):
1001 res = {}
1002 for name in ["setQuantifier", "setLimit", "fromClause",
1003 "whereClause", "groupby", "having", "orderBy"]:
1004 res[name] = _parseResult.get(name)
1005 res["selectList"] = getChildOfType(_parseResult, "selectList")
1006 return res
1007
1008 def _iterSelectList(self):
1009 for f in self.selectList.selectFields:
1010 if isinstance(f, DerivedColumn):
1011 yield f
1012 elif isinstance(f, QualifiedStar):
1013 for sf in self.fromClause.getFieldsForTable(f.sourceTable):
1014 yield sf
1015 else:
1016 raise common.Error("Unexpected %s in select list"%getType(f))
1017
1018 def getSelectFields(self):
1019 if self.selectList.allFieldsQuery:
1020 return self.fromClause.getAllFields()
1021 else:
1022 return self._iterSelectList()
1023
1024 def addFieldInfos(self, context):
1025 self.fieldInfos = fieldinfos.QueryFieldInfos.makeForNode(self, context)
1026
1027 def resolveField(self, fieldName):
1028 return self.fromClause.resolveField(fieldName)
1029
1030 def getAllNames(self):
1031 return self.fromClause.getAllNames()
1032
1033 def flatten(self):
1034 return flattenKWs(self, ("SELECT", None),
1035 ("", "setQuantifier"),
1036 ("TOP", "setLimit"),
1037 ("", "selectList"),
1038 ("", "fromClause"),
1039 ("", "whereClause"),
1040 ("", "groupby"),
1041 ("", "having"),
1042 ("", "orderBy"))
1043
1044 def suggestAName(self):
1045 """returns a string that may or may not be a nice name for a table
1046 resulting from this query.
1047
1048 Whatever is being returned here, it's a regular SQL identifier.
1049 """
1050 try:
1051 sources = [tableRef.makeUpId()
1052 for tableRef in self.fromClause.getAllTables()]
1053 if sources:
1054 return "_".join(sources)
1055 else:
1056 return "query_result"
1057 except: # should not happen, but we don't want to bomb from here
1058 import traceback;traceback.print_exc()
1059 return "weird_table_report_this"
1060
1061 def getContributingNames(self):
1062 """returns a set of table names mentioned below this node.
1063 """
1064 names = set()
1065 for name, val in self.iterTree():
1066 if isinstance(val, TableName):
1067 names.add(val.flatten())
1068 return names
1069
1070
1071 class SetOperationNode(ColumnBearingNode, TransparentMixin):
1072 """A node containing a set expression.
1073
1074 This is UNION, INTERSECT, or EXCEPT. In all cases, we need to check
1075 all contributing sub-expressions have compatible degree. For now,
1076 in violation of SQL1992, we require identical names on all operands --
1077 sql92 in 7.10 says
1078
1079 [if column names are unequal], the <column name> of the i-th column of TR
1080 is implementation-dependent and different from the <column name> of any
1081 column, other than itself, of any table referenced by any <table reference>
1082 contained in the SQL-statement.
1083
1084 Yikes.
1085
1086 These collapse to keep things simple in the typical case.
1087 """
1088 def _assertFieldInfosCompatible(self):
1089 """errors out if operands have incompatible signatures.
1090
1091 For convenience, if all are compatible, the common signature (ie,
1092 fieldInfos) is returned.
1093 """
1094 fieldInfos = None
1095 for child in self.children:
1096 # Skip WithQueries -- they're not part of set operations.
1097 if hasattr(child, "fieldInfos") and not isinstance(child, WithQuery):
1098 if fieldInfos is None:
1099 fieldInfos = child.fieldInfos.copy(self)
1100 else:
1101 fieldInfos.assertIsCompatible(child.fieldInfos)
1102 for (l1, mycol), (l2, theircol) in zip(fieldInfos, child.fieldInfos):
1103 if mycol.ucd != theircol.ucd:
1104 mycol.ucd = ""
1105 if mycol.unit != theircol.unit:
1106 mycol.unit = ""
1107
1108 return fieldInfos
1109
1110 def addFieldInfos(self, context):
1111 self.fieldInfos = self._assertFieldInfosCompatible()
1112
1113 def getAllNames(self):
1114 for index, child in enumerate(self.children):
1115 if hasattr(child, "getAllNames"):
1116 for name in child.getAllNames():
1117 yield name
1118 elif hasattr(child, "suggestAName"):
1119 yield child.suggestAName()
1120 else: # pragma: no cover
1121 assert False, "no name"
1122
1123 def getSelectClauses(self):
1124 for child in self.children:
1125 for sc in getattr(child, "getSelectClauses", lambda: [])():
1126 yield sc
1127 if hasattr(child, "setLimit"):
1128 yield child
1129
1130
1131 class SetTerm(SetOperationNode):
1132 type = "querySetTerm"
1133 collapsible = True
1134
1135
1136 class SetExpression(SetOperationNode):
1137 type = "querySetExpression"
1138 collapsible = True
1139
1140 # we hand the various introspection items through to our first child;
1141 # if one day we want to make sure the relations of all children are
1142 # reconcilable, this probably should happen in a _polish method.
1143
1144 @property
1145 def fromClause(self):
1146 return self.children[0].fromClause
1147
1148 def getContributingNames(self):
1149 res = []
1150 for child in self.children:
1151 if hasattr(child, "getContributingNames"):
1152 res.extend(child.getContributingNames())
1153 return res
1154
1155
1156 class WithQuery(SetOperationNode):
1157 """A query from a with clause.
1158
1159 This essentially does everything a table does.
1160 """
1161 type = "withQuery"
1162
1163 def addFieldInfos(self, context):
1164 # overridden because we need to discard statistics here. We
1165 # have code that looks at table sizes (look for "optimize"),
1166 # and it looks at columns' parents to do that. These stats
1167 # will be totally off in CTEs. To avoid dis-optimisations,
1168 # we note it's all off here.
1169 SetOperationNode.addFieldInfos(self, context)
1170 for _, fi in self.fieldInfos:
1171 fi.ignoreTableStats = True
1172
1173 def _polish(self):
1174 self.name = self.children[0]
1175 for c in self.children:
1176 # this should be a selectExpression, but this we want to be sure
1177 # we don't fail when morphers replace the main query node
1178 # (as the pg morpher does)
1179 if hasattr(c, "setLimit"):
1180 self.select = c
1181 break
1182 else: # pragma: no cover
1183 raise NotImplementedError("WithQuery without select?")
1184
1185
1186 class SelectExpression(SetOperationNode):
1187 """A complete query excluding CTEs.
1188
1189 The main ugly thing here is the set limit; the querySpecification has
1190 max of the limits of the children, if existing, otherwise to None.
1191
1192 Other than that, we hand through attribute access to our first child.
1193
1194 If there is a set expression on the top level, this will have a complex
1195 structure; the first-child thing still ought to work since after
1196 annotation we'll have errored out if set operator arguments aren't
1197 reasonably congurent.
1198 """
1199 type = "selectExpression"
1200
1201 _a_setLimit = None
1202 _a_offset= None
1203
1204 def getSelectClauses(self):
1205 for child in self.children:
1206 for sc in getattr(child, "getSelectClauses", lambda: [])():
1207 yield sc
1208 if hasattr(child, "setLimit"):
1209 yield child
1210
1211 def _polish(self):
1212 if self.setLimit is None:
1213 limits = [selectClause.setLimit
1214 for selectClause in self.getSelectClauses()]
1215
1216 limits = [int(s) for s in limits if s]
1217 if limits:
1218 self.setLimit = max(limits)
1219
1220 for child in self.children:
1221 if isinstance(child, OffsetSpec) and child.offset is not None:
1222 self.offset = child.offset
1223 child.offset = None
1224
1225 def __getattr__(self, attrName):
1226 return getattr(self.children[0], attrName)
1227
1228
1229 class QuerySpecification(TransparentNode):
1230 """The toplevel query objects including CTEs.
1231
1232 Apart from any CTEs, that's just a SelectExpression (which is always the last
1233 child), and we hand through essentially all attribute access to it.
1234 """
1235 type = "querySpecification"
1236
1237 def _polish(self):
1238 self.withTables = []
1239 for child in self.children:
1240 if isinstance(child, WithQuery):
1241 self.withTables.append(child)
1242
1243 def _setSetLimit(self, val):
1244 self.children[-1].setLimit = val
1245 def _getSetLimit(self):
1246 return self.children[-1].setLimit
1247 setLimit = property(_getSetLimit, _setSetLimit)
1248
1249 def __getattr__(self, attrName):
1250 # our last child always is a querySpecification
1251 return getattr(self.children[-1], attrName)
1252
1253
1254 class Statement(FieldInfoedNode):
1255 type = "statement"
1256 _a_createAs = None
1257 _a_query = None
1258
1259 @classmethod
1260 def _getInitKWs(cls, _parseResult):
1261 if len(_parseResult)==1:
1262 createAs, query = None, _parseResult[0]
1263 elif len(_parseResult)==2:
1264 createAs, query = _parseResult
1265 else:
1266 raise NotImplementedError(f"Extra tokens in statement {_parseResult}.")
1267 return locals()
1268
1269 def flatten(self):
1270 if self.createAs:
1271 return "{} {}".format(flatten(self.createAs), flatten(self.query))
1272 else:
1273 return self.query.flatten()
1274
1275 def addFieldInfos(self, context):
1276 self.query.addFieldInfos(context)
1277 if self.createAs:
1278 self.createAs.allocateTAPUpload(context)
1279
1280 def __getattr__(self, attrName):
1281 return getattr(self.query, attrName)
1282
1283
1284 class _BaseColumnReference(FieldInfoedNode):
1285 # normal column references will be handled by the dispatchColumnReference
1286 # function below; there we look at the columnReference type to figure
1287 # out whether something is constant, though, and so multiple
1288 # non-terminals share this.
1289 # That's why we're unbinding everything here and leave it to
1290 # deriving classes to set up bindings.
1291 type = "columnReference"
1292 bindings = []
1293 _a_refName = None # if given, a TableName instance
1294 _a_name = None
1295
1296 def _polish(self):
1297 if not self.refName:
1298 self.refName = None
1299 self.colName = ".".join(
1300 flatten(p) for p in (self.refName, self.name) if p)
1301
1302 @classmethod
1303 def _getInitKWs(cls, _parseResult):
1304 names = [_c for _c in _parseResult if _c!="."]
1305 names = [None]*(4-len(names))+names
1306 refName = TableName(cat=names[0],
1307 schema=names[1],
1308 name=names[2])
1309 if not refName:
1310 refName = None
1311 return {
1312 "name": names[-1],
1313 "refName": refName}
1314
1315 def addFieldInfo(self, context):
1316 self.fieldInfo = context.getFieldInfo(self.name, self.refName)
1317
1318 srcColumn = None
1319 if self.fieldInfo.userData:
1320 srcColumn = self.fieldInfo.userData[0]
1321 if hasattr(srcColumn, "originalName"):
1322 # This is a column from a VOTable upload we have renamed to avoid
1323 # clashes with postgres-reserved column names. Update the name
1324 # so the "bad" name doesn't apprear in the serialised query.
1325 if not isinstance(self.name, utils.QuotedName):
1326 self.name = srcColumn.name
1327 self._polish()
1328
1329 def flatten(self):
1330 if self.fieldInfo and self.fieldInfo.sqlName:
1331 return ".".join(
1332 flatten(p) for p in (self.refName, self.fieldInfo.sqlName) if p)
1333 return self.colName
1334
1335 def _treeRepr(self):
1336 return (self.type, self.name)
1337
1338
1339 class ColumnReference(_BaseColumnReference):
1340 # No bindings: constructed by dispatchColumnReference
1341 pass
1342
1343 class GeometryValue(_BaseColumnReference):
1344 bindings = ["geometryValue"]
1345
1346
1347 class ColumnReferenceByUCD(_BaseColumnReference):
1348 # these are tricky: As, when parsing, we don't know where the columns
1349 # might come from, we have to later figure out where to get our metadata
1350 # from.
1351 bindings = ["columnReferenceByUCD"]
1352 _a_ucdWanted = None
1353
1354 @classmethod
1355 def _getInitKWs(cls, _parseResult):
1356 return {
1357 "ucdWanted": _parseResult[2].value,
1358 "name": utils.Undefined,
1359 "refName": utils.Undefined}
1360
1361 def addFieldInfo(self, context):
1362 # I've not really thought about where these might turn up.
1363 # Hence, I just heuristically walk up the ancestor stack
1364 # until I find a from clause. TODO: think about if that's valid.
1365 for ancestor in reversed(context.ancestors):
1366 if hasattr(ancestor, "fromClause"):
1367 break
1368 else:
1369 raise common.Error("UCDCOL outside of query specification with FROM")
1370
1371 for field in ancestor.fromClause.getAllFields():
1372 if fnmatch.fnmatch(field.fieldInfo.ucd, self.ucdWanted):
1373 self.fieldInfo = field.fieldInfo.change()
1374 self.name = self.colName = field.name
1375 self.refName = None
1376 break
1377 else:
1378 raise utils.NotFoundError(self.ucdWanted, "column matching ucd",
1379 "from clause")
1380
1381 self.fieldInfo.properties["src-expression"] = flatten(self)
1382
1383
1384 @symbolAction("columnReference")
1385 def dispatchColumnReference(parseResult):
1386 # this dispatch is there so ColumnReference is not bothered
1387 # by the by-UCD hack in the normal case. It should go if we
1388 # punt UCDCOL, and the columnReference binding should then go
1389 # back to ColumnReference
1390 if len(parseResult)==1 and isinstance(parseResult[0], ColumnReferenceByUCD):
1391 return parseResult[0]
1392 else:
1393 return ColumnReference.fromParseResult(parseResult)
1394
1395
1396 class FromClause(ADQLNode):
1397 type = "fromClause"
1398 _a_tableReference = ()
1399 _a_tables = ()
1400
1401 @classmethod
1402 def _getInitKWs(cls, parseResult):
1403 parseResult = list(parseResult)
1404 if len(parseResult)==1:
1405 tableReference = parseResult[0]
1406 else:
1407 # it's a cross join; to save repeating the logic, we'll
1408 # just build an artificial join as the table reference
1409 tableReference = reduce(lambda left, right:
1410 JoinedTable(
1411 leftOperand=left,
1412 operator=JoinOperator(children=[","]),
1413 rightOperand=right), parseResult)
1414 return {
1415 "tableReference": tableReference,
1416 "tables": parseResult}
1417
1418 def flatten(self):
1419 return "FROM %s"%(' , '.join(t.flatten() for t in self.tables))
1420
1421 def getAllNames(self):
1422 """returns the names of all tables taking part in this from clause.
1423 """
1424 return self.tableReference.getAllNames()
1425
1426 def resolveField(self, name):
1427 return self.tableReference.getFieldInfo(name)
1428
1429 def _makeColumnReference(self, sourceTableName, colPair):
1430 """returns a ColumnReference object for a name, colInfo pair from a
1431 table's fieldInfos.
1432 """
1433 if isinstance(sourceTableName, TableName):
1434 cr = ColumnReference(
1435 name=colPair[0],
1436 refName=sourceTableName.physicalName)
1437 else:
1438 cr = ColumnReference(name=colPair[0], refName=sourceTableName)
1439 cr.fieldInfo = colPair[1]
1440 return cr
1441
1442 def getAllFields(self):
1443 """returns all fields from all tables in this FROM.
1444
1445 These will be qualified names. Columns taking part in joins are
1446 resolved here.
1447
1448 This will only work for annotated tables.
1449 """
1450 res = []
1451 commonColumns = common.computeCommonColumns(self.tableReference)
1452 commonColumnsMade = set()
1453
1454 for table in self.getAllTables():
1455 for label, fi in table.fieldInfos.seq:
1456 if label in commonColumns:
1457 if label not in commonColumnsMade:
1458 res.append(self._makeColumnReference(
1459 None, (label, fi)))
1460 commonColumnsMade.add(label)
1461
1462 else:
1463 res.append(self._makeColumnReference(
1464 table.tableName, (label, fi)))
1465
1466 return res
1467
1468 def getFieldsForTable(self, srcTableName):
1469 """returns the fields in srcTable.
1470
1471 srcTableName is a TableName.
1472 """
1473 if fieldinfos.tableNamesMatch(self.tableReference, srcTableName):
1474 table = self.tableReference
1475 else:
1476 table = self.tableReference.fieldInfos.locateTable(srcTableName)
1477
1478 return [self._makeColumnReference(table.tableName, ci)
1479 for ci in table.fieldInfos.seq]
1480
1481 def getAllTables(self):
1482 return self.tableReference.getAllTables()
1483
1484
1485 class DerivedColumn(FieldInfoedNode):
1486 """A column within a select list.
1487 """
1488 type = "derivedColumn"
1489 _a_expr = None
1490 _a_alias = None
1491 _a_tainted = True
1492
1493 def _polish(self):
1494 if getType(self.expr)=="columnReference":
1495 self.tainted = False
1496
1497 @property
1498 def name(self):
1499 # todo: be a bit more careful here to come up with meaningful
1500 # names (users don't like the funny names). Also: do
1501 # we make sure somewhere we're getting unique names?
1502 if self.alias is not None:
1503 return self.alias
1504
1505 elif hasattr(self.expr, "name"):
1506 return self.expr.name
1507
1508 else:
1509 return utils.intToFunnyWord(id(self))
1510
1511 @classmethod
1512 def _getInitKWs(cls, _parseResult):
1513 expr = _parseResult["expr"] #noflake: locals returned
1514 alias = _parseResult.get("alias") #noflake: locals returned
1515 return locals()
1516
1517 def flatten(self):
1518 return flattenKWs(self,
1519 ("", "expr"),
1520 ("AS", "alias"))
1521
1522 def _treeRepr(self):
1523 return (self.type, self.name)
1524
1525 def addFieldInfo(self, context):
1526 FieldInfoedNode.addFieldInfo(self, context)
1527 if self.fieldInfo and self.alias:
1528 self.fieldInfo = self.fieldInfo.change()
1529 if hasattr(self.alias, "name"): # a QName, presumably
1530 self.fieldInfo.properties["src-expression"] = self.alias.name
1531 else:
1532 self.fieldInfo.properties["src-expression"] = self.alias
1533
1534
1535 class QualifiedStar(ADQLNode):
1536 type = "qualifiedStar"
1537 _a_sourceTable = None # A TableName for the column source
1538
1539 @classmethod
1540 def _getInitKWs(cls, _parseResult):
1541 parts = _parseResult[:-2:2] # kill dots and star
1542 cat, schema, name = [None]*(3-len(parts))+parts
1543 return {"sourceTable": TableName(cat=cat, schema=schema, name=name)}
1544
1545 def flatten(self):
1546 return "%s.*"%flatten(self.sourceTable)
1547
1548
1549 class SelectList(ADQLNode):
1550 type = "selectList"
1551 _a_selectFields = ()
1552 _a_allFieldsQuery = False
1553
1554 @classmethod
1555 def _getInitKWs(cls, _parseResult):
1556 allFieldsQuery = _parseResult.get("starSel", False)
1557 if allFieldsQuery:
1558 # Will be filled in by query, we don't have the from clause here.
1559 selectFields = None #noflake: locals returned
1560 else:
1561 selectFields = list(itertools.chain(#noflake: locals returned
1562 *_parseResult.get("fieldSel")))
1563 return locals()
1564
1565 def flatten(self):
1566 if self.allFieldsQuery:
1567 return self.allFieldsQuery
1568 else:
1569 return ", ".join(flatten(sf) for sf in self.selectFields)
1570
1571
1572 ######## all expression parts we need to consider when inferring units and such
1573
1574 class Comparison(ADQLNode):
1575 """is required when we want to morph the braindead contains(...)=1 into
1576 a true boolean function call.
1577 """
1578 type = "comparisonPredicate"
1579 _a_op1 = None
1580 _a_opr = None
1581 _a_op2 = None
1582
1583 @classmethod
1584 def _getInitKWs(cls, _parseResult):
1585 op1, opr, op2 = _parseResult #noflake: locals returned
1586 return locals()
1587
1588 def flatten(self):
1589 return "%s %s %s"%(flatten(self.op1), self.opr, flatten(self.op2))
1590
1591
1592 def _guessNumericType(literal):
1593 """returns a guess for a type suitable to hold a numeric value given in
1594 literal.
1595
1596 I don't want to pull through the literal symbol that matched
1597 from grammar in all cases. Thus, at times I simply guess the type
1598 (and yes, I'm aware that -32768 still is a smallint).
1599 """
1600 try:
1601 val = int(literal)
1602 if abs(val)<32767:
1603 type = "smallint"
1604 elif abs(val)<2147483648:
1605 type = "integer"
1606 else:
1607 type = "bigint"
1608 except ValueError:
1609 if literal.lower()=="null":
1610 type = None
1611 else:
1612 # I'm too lazy to spell out all sorts of float.
1613 type = "double precision"
1614 return type
1615
1616
1617 class Factor(FieldInfoedNode, TransparentMixin):
1618 """a factor within an SQL expression.
1619
1620 factors may have only one (direct) child with a field info and copy
1621 this. They can have no child with a field info, in which case they're
1622 simply numeric (about the weakest assumption: They're doubles).
1623 """
1624 type = "factor"
1625 collapsible = True
1626
1627 def addFieldInfo(self, context):
1628 infoChildren = self._getInfoChildren()
1629 if infoChildren:
1630 assert len(infoChildren)==1
1631 self.fieldInfo = infoChildren[0].fieldInfo
1632 else:
1633 self.fieldInfo = fieldinfo.FieldInfo(
1634 _guessNumericType("".join(self.children)), "", "")
1635
1636 self.fieldInfo.properties["src-expression"] = flatten(self)
1637
1638
1639 class ArrayReference(FieldInfoedNode, TransparentMixin):
1640 type = "arrayReference"
1641 collapsible = False
1642
1643 def addFieldInfo(self, context):
1644 infoChild = self.children[0]
1645 childInfo = infoChild.fieldInfo
1646
1647 if childInfo.type is None:
1648 raise common.Error("Cannot subscript a typeless thing in %s"%(
1649 self.flatten()))
1650
1651 lastSubscript = re.search(r"\[[0-9]*\]$", childInfo.type)
1652 if lastSubscript is None:
1653 raise common.Error("Cannot subscript a non-array in %s"%(
1654 self.flatten()))
1655
1656 self.fieldInfo = fieldinfo.FieldInfo(
1657 childInfo.type[:lastSubscript.start()],
1658 childInfo.unit,
1659 childInfo.ucd,
1660 childInfo.userData,
1661 tainted=True # array might actually have semantics
1662 )
1663
1664 self.fieldInfo.properties["src-expression"] = flatten(self)
1665
1666
1667 class LiteralWithUnit(FieldInfoedNode):
1668 type = "literalWithUnit"
1669 collapsible = False
1670
1671 _a_literal = None
1672 _a_unit = None
1673
1674 @classmethod
1675 def _getInitKWs(cls, _parseResult):
1676 literal, unit = list(_parseResult)
1677 return locals()
1678
1679 def flatten(self):
1680 return self.literal
1681
1682 def addFieldInfo(self, context):
1683 self.fieldInfo = fieldinfo.FieldInfo(
1684 _guessNumericType("".join(self.literal)),
1685 str(self.unit),
1686 None)
1687
1688
1689 class CombiningFINode(FieldInfoedNode):
1690 def addFieldInfo(self, context):
1691 infoChildren = self._getInfoChildren()
1692 if not infoChildren:
1693 if len(self.children)==1:
1694 # probably a naked numeric literal in the grammar, e.g.,
1695 # in mathFunction
1696 self.fieldInfo = fieldinfo.FieldInfo(
1697 _guessNumericType(self.children[0]), "", "")
1698 else:
1699 raise common.Error("Oops -- did not expect '%s' when annotating %s"%(
1700 "".join(self.children), self))
1701 elif len(infoChildren)==1:
1702 self.fieldInfo = infoChildren[0].fieldInfo
1703 else:
1704 self.fieldInfo = self._combineFieldInfos()
1705
1706 if self.fieldInfo:
1707 self.fieldInfo.properties["src-expression"] = flatten(self)
1708
1709
1710 class Term(CombiningFINode, TransparentMixin):
1711 type = "term"
1712 collapsible = True
1713
1714 def _combineFieldInfos(self):
1715 # These are either multiplication or division
1716 toDo = self.children[:]
1717 opd1 = toDo.pop(0)
1718 fi1 = opd1.fieldInfo
1719 while toDo:
1720 opr = toDo.pop(0)
1721 fi1 = fieldinfo.FieldInfo.fromMulExpression(opr, fi1,
1722 toDo.pop(0).fieldInfo)
1723 return fi1
1724
1725
1726 class NumericValueExpression(CombiningFINode, TransparentMixin):
1727 type = "numericValueExpression"
1728 collapsible = True
1729
1730 def _combineFieldInfos(self):
1731 # These are either addition or subtraction
1732 toDo = self.children[:]
1733 fi1 = toDo.pop(0).fieldInfo
1734 while toDo:
1735 opr = toDo.pop(0)
1736 fi1 = fieldinfo.FieldInfo.fromAddExpression(
1737 opr, fi1, toDo.pop(0).fieldInfo)
1738 return fi1
1739
1740
1741 class StringValueExpression(FieldInfoedNode, TransparentMixin):
1742 type = "stringValueExpression"
1743 collapsible = True
1744
1745 def addFieldInfo(self, context):
1746 # This is concatenation; we treat is as if we'd be adding numbers
1747 infoChildren = self._getInfoChildren()
1748 if infoChildren:
1749 fi1 = infoChildren.pop(0).fieldInfo
1750 if fi1.type=="unicode":
1751 baseType = "unicode"
1752 else:
1753 baseType = "text"
1754 while infoChildren:
1755 if infoChildren[0].fieldInfo.type=="unicode":
1756 baseType = "unicode"
1757 fi1 = fieldinfo.FieldInfo.fromAddExpression(
1758 "+", fi1, infoChildren.pop(0).fieldInfo, forceType=baseType)
1759 self.fieldInfo = fi1
1760 else:
1761 self.fieldInfo = fieldinfo.FieldInfo(
1762 "text", "", "")
1763
1764 self.fieldInfo.properties["src-expression"] = flatten(self)
1765
1766
1767 class GenericValueExpression(CombiningFINode, TransparentMixin):
1768 """A container for value expressions that we don't want to look at
1769 closer.
1770
1771 It is returned by the makeValueExpression factory below to collect
1772 stray children.
1773 """
1774 type = "genericValueExpression"
1775 collapsible = True
1776
1777 def _combineFieldInfos(self):
1778 # we don't really know what these children are. Let's just give up
1779 # unless all child fieldInfos are more or less equal (which of course
1780 # is a wild guess).
1781 childUnits, childUCDs = set(), set()
1782 infoChildren = self._getInfoChildren()
1783 for c in infoChildren:
1784 childUnits.add(c.fieldInfo.unit)
1785 childUCDs.add(c.fieldInfo.ucd)
1786 if len(childUnits)==1 and len(childUCDs)==1:
1787 # let's taint the first info and be done with it
1788 return infoChildren[0].fieldInfo.change(tainted=True)
1789 else:
1790 # if all else fails: let's hope someone can make a string from it
1791 return fieldinfo.FieldInfo("text", "", "")
1792
1793
1794 @symbolAction("valueExpression")
1795 def makeValueExpression(children):
1796 if len(children)!=1:
1797 res = GenericValueExpression.fromParseResult(children)
1798 res.type = "valueExpression"
1799 return res
1800 else:
1801 return children[0]
1802
1803
1804 class SetFunction(TransparentMixin, FieldInfoedNode):
1805 """An aggregate function.
1806
1807 These typically amend the ucd by a word from the stat family and copy
1808 over the unit. There are exceptions, however, see table in class def.
1809 """
1810 type = "setFunctionSpecification"
1811
1812 funcDefs = {
1813 'AVG': ('{u};stat.mean', None, "double precision"),
1814 'STDDEV': ('stat.stdev;{u}', None, "double precision"),
1815 'MAX': ('stat.max;{u}', None, None),
1816 'MIN': ('stat.min;{u}', None, None),
1817 'SUM': (None, None, None),
1818 'COUNT': ('meta.number;{u}', '', "integer"),}
1819
1820 def addFieldInfo(self, context):
1821 funcName = self.children[0].upper()
1822 ucdPref, newUnit, newType = self.funcDefs[funcName]
1823
1824 # try to find out about our child
1825 infoChildren = self._getInfoChildren()
1826 if infoChildren:
1827 assert len(infoChildren)==1
1828 fi = infoChildren[0].fieldInfo
1829 else:
1830 fi = fieldinfo.FieldInfo("double precision", "", "")
1831
1832 if ucdPref is None:
1833 # ucd of a sum is the ucd of the summands?
1834 ucd = fi.ucd
1835 elif fi.ucd:
1836 ucd = ucdPref.format(u=fi.ucd)
1837 else:
1838 # no UCD given; if we're count, we're meta.number, otherwise we
1839 # don't know
1840 if funcName=="COUNT":
1841 ucd = "meta.number"
1842 else:
1843 ucd = None
1844
1845 # most of these keep the unit of what they're working on
1846 if newUnit is None:
1847 newUnit = fi.unit
1848
1849 # most of these keep the type of what they're working on
1850 if newType is None:
1851 newType = fi.type
1852
1853 self.fieldInfo = fieldinfo.FieldInfo(
1854 newType, unit=newUnit, ucd=ucd, userData=fi.userData, tainted=fi.tainted)
1855
1856 self.fieldInfo.properties["src-expression"] = flatten(self)
1857
1858
1859 class NumericValueFunction(FunctionNode):
1860 """A numeric function.
1861
1862 This is really a mixed bag. We work through handlers here. See table
1863 in class def. Unknown functions result in dimlesses.
1864 """
1865 type = "numericValueFunction"
1866 collapsible = True # if it's a real function call, it has at least
1867 # a name, parens and an argument and thus won't be collapsed.
1868
1869 funcDefs = {
1870 "ACOS": ('rad', '', None),
1871 "ASIN": ('rad', '', None),
1872 "ATAN": ('rad', '', None),
1873 "ATAN2": ('rad', '', None),
1874 "PI": ('', '', None),
1875 "RAND": ('', '', None),
1876 "EXP": ('', '', None),
1877 "LOG": ('', '', None),
1878 "LOG10": ('', '', None),
1879 "SQRT": ('', '', None),
1880 "SQUARE": ('', '', None),
1881 "POWER": ('', '', None),
1882 "ABS": (None, None, "keepMeta"),
1883 "CEILING": (None, None, "keepMeta"),
1884 "FLOOR": (None, None, "keepMeta"),
1885 "ROUND": (None, None, "keepMeta"),
1886 "TRUNCATE": (None, None, "keepMeta"),
1887 "DEGREES": ('deg', None, "keepMeta"),
1888 "RADIANS": ('rad', None, "keepMeta"),
1889 # bitwise operators: hopeless
1890 }
1891
1892 def _handle_keepMeta(self, infoChildren):
1893 fi = infoChildren[0].fieldInfo
1894 return fi.unit, fi.ucd
1895
1896 def addFieldInfo(self, context):
1897 infoChildren = self._getInfoChildren()
1898 unit, ucd = '', ''
1899 overrideUnit, overrideUCD, handlerName = self.funcDefs.get(
1900 self.funName, ('', '', None))
1901 if handlerName:
1902 unit, ucd = getattr(self, "_handle_"+handlerName)(infoChildren)
1903 if overrideUnit:
1904 unit = overrideUnit
1905 if overrideUCD:
1906 ucd = overrideUCD
1907 self.fieldInfo = fieldinfo.FieldInfo("double precision",
1908 unit, ucd, *collectUserData(infoChildren))
1909 self.fieldInfo.tainted = True
1910
1911 self.fieldInfo.properties["src-expression"] = flatten(self)
1912
1913
1914 class ScalarArrayFunction(FunctionNode):
1915 """All of these are functions somehow aggregating array elements.
1916
1917 For those that we know we try to infer units and UCDs.
1918 """
1919 type = "scalarArrayFunction"
1920
1921 funcDefs = {
1922 'ARR_MIN': ('stat.min;{u}', None, 1),
1923 'ARR_MAX': ('stat.max;{u}', None, 1),
1924 'ARR_AVG': ('{u};stat.mean', None, 1),
1925 'ARR_STDDEV': ('stat.stdev;{u}', None, 1),
1926 'ARR_SUM': ('{u};arith.sum', None, 1),
1927 'ARR_COUNT': ('meta.number;{u}', "", 1),
1928 'ARR_DOT': (None, None, 2),
1929 }
1930
1931 def addFieldInfo(self, context):
1932 ucdchange, unitchange, nPar = self.funcDefs.get(
1933 self.funName, (None, None, 1))
1934
1935 infoChildren = self._getInfoChildren()
1936 if len(infoChildren)!=nPar:
1937 raise common.Error(
1938 "Grammar vs. annotation function arity mismatch!")
1939
1940 # we're being very liberal with upcasting to double precision
1941 # here since that may help fend off integer overflows.
1942 type = "double precision"
1943 if nPar==1:
1944 baseFI = infoChildren[0].fieldInfo
1945 mat = fieldinfo.isArray(baseFI.type)
1946 if not mat:
1947 raise common.Error(
1948 "Scalar array function called on non-array?")
1949 if self.funName=="ARR_COUNT":
1950 type = "integer"
1951
1952 elif nPar==2:
1953 baseFI = fieldinfo.FieldInfo(type, "", "",
1954 userData=infoChildren)
1955 else:
1956 assert False
1957
1958
1959 ucd, unit = "", baseFI.unit
1960 if ucdchange is not None and baseFI.ucd:
1961 ucd = ucdchange.format(u=baseFI.ucd)
1962 if unitchange is not None:
1963 unit = unitchange
1964
1965 self.fieldInfo = fieldinfo.FieldInfo(type, unit, ucd,
1966 *collectUserData(infoChildren))
1967
1968
1969 class ArrayMapFunction(FunctionNode):
1970 """The arr_map extension.
1971
1972 arg 1 is the expression; any x in it will be the filled with the array
1973 elements. arg 2 is the array to take the elements from.
1974 """
1975 type = "arrayMapFunction"
1976
1977 def addFieldInfo(self, context):
1978 self.fieldInfo = fieldinfo.FieldInfo("double precision[]", "", "")
1979
1980 def _polish(self):
1981 # we need to pre-annotate all column references to "x" (our unbound
1982 # variable) in our first argument with a literal "x" to keep
1983 # our annotation engine from looking at them
1984 def preAnnotate(node):
1985 for child in node.iterNodeChildren():
1986 if isinstance(child, ColumnReference) and child.name=="x":
1987 child.fieldInfo = fieldinfo.FieldInfo(
1988 "double precision", "", "")
1989 preAnnotate(child)
1990
1991 preAnnotate(self.args[0])
1992
1993
1994 class StringValueFunction(FunctionNode):
1995 type = "stringValueFunction"
1996
1997 def addFieldInfo(self, context):
1998 self.fieldInfo = fieldinfo.FieldInfo("text", "", "",
1999 userData=collectUserData(self._getInfoChildren())[0])
2000
2001 self.fieldInfo.properties["src-expression"] = flatten(self)
2002
2003
2004 class TimestampFunction(FunctionNode):
2005 type = "timestampFunction"
2006
2007 def addFieldInfo(self, context):
2008 subordinates = self._getInfoChildren()
2009 if subordinates:
2010 ucd, stc = subordinates[0].fieldInfo.ucd, subordinates[0].fieldInfo.stc
2011 else:
2012 ucd, stc = None, None
2013 userData, tainted = collectUserData(subordinates)
2014 self.fieldInfo = fieldinfo.FieldInfo("timestamp", "",
2015 ucd=ucd, stc=stc, userData=userData, tainted=tainted)
2016
2017
2018 class InUnitFunction(FieldInfoedNode):
2019 # This is reused below in CoercedFactor (except for
2020 # _getInitKWs)
2021 type = "inUnitFunction"
2022 _a_expr = None
2023 _a_unit = None
2024
2025 conversionFactor = None
2026
2027 @classmethod
2028 def _getInitKWs(cls, _parseResult):
2029 return {
2030 'expr': _parseResult[2],
2031 'unit': _parseResult[4].value,
2032 }
2033
2034 def addFieldInfo(self, context):
2035 try:
2036 from gavo.base import computeConversionFactor, IncompatibleUnits, BadUnit
2037 except ImportError: # pragma: no cover
2038 raise utils.ReportableError("in_unit only available with gavo.base"
2039 " installed")
2040
2041 if not hasattr(self.expr, "fieldInfo"):
2042 raise common.Error("You cannot unit-coerce literals")
2043
2044 try:
2045 self.conversionFactor = computeConversionFactor(
2046 self.expr.fieldInfo.unit, self.unit)
2047 self.fieldInfo = self.expr.fieldInfo.change(unit=self.unit)
2048 except IncompatibleUnits as msg:
2049 raise common.Error("in_unit error: %s"%msg)
2050 except BadUnit as msg:
2051 raise common.Error("Bad unit passed to in_unit: %s"%msg)
2052
2053 def flatten(self):
2054 if self.conversionFactor is None: # pragma: no cover
2055 raise common.Error(
2056 "Unit coercion can only be flattened in annotated trees")
2057
2058 if isinstance(self.expr, ColumnReference):
2059 exprPat = "%s"
2060 else:
2061 exprPat = "(%s)"
2062 return "(%s * %.16g)"%(exprPat%flatten(self.expr), self.conversionFactor)
2063
2064 def change(self, **kwargs):
2065 copy = FieldInfoedNode.change(self, **kwargs)
2066 copy.conversionFactor = self.conversionFactor
2067 return copy
2068
2069
2070 class CoercedFactor(InUnitFunction):
2071 type = "coercedFactor"
2072
2073 @classmethod
2074 def fromParseResult(cls, parseResult):
2075 # we need to override this because the original method walks up the
2076 # inheritance tree, and InUnit's fromParseResult expects different
2077 # tokens.
2078 expr = []
2079 for _n in parseResult:
2080 if _n=="@":
2081 break
2082 expr.append(_n)
2083
2084 if len(expr)==1:
2085 expr = expr[0]
2086 else:
2087 expr = Factor(expr)
2088 return cls(expr, parseResult[-1])
2089
2090
2091 class CharacterStringLiteral(FieldInfoedNode):
2092 """according to the current grammar, these are always sequences of
2093 quoted strings.
2094 """
2095 type = "characterStringLiteral"
2096 bindings = ["characterStringLiteral", "generalLiteral"]
2097
2098 _a_value = None
2099
2100 @classmethod
2101 def _getInitKWs(cls, _parseResult):
2102 value = "".join(_c[1:-1] for _c in _parseResult) #noflake: locals returned
2103 return locals()
2104
2105 def flatten(self):
2106 return "'%s'"%self.value
2107
2108 def addFieldInfo(self, context):
2109 self.fieldInfo = fieldinfo.FieldInfo("text", "", "")
2110
2111
2112 class CastSpecification(FieldInfoedNode, TransparentMixin):
2113 type = "castSpecification"
2114 _a_value = None
2115 _a_newType = None
2116
2117 @classmethod
2118 def _getInitKWs(cls, _parseResult):
2119 value = _parseResult["value"]
2120 newType = _parseResult["newType"].lower()
2121 if newType.startswith("char (") or newType.startswith("varchar ("):
2122 newType = "text"
2123 elif newType.startswith("national char"):
2124 newType = "unicode"
2125 return locals()
2126
2127 geometryConstructors = {
2128 "POINT": "Point",
2129 "CIRCLE": "Circle",
2130 "POLYGON": "Polygon"}
2131
2132 def _polish(self):
2133 # the casts to geometries need to be turned into constructor calls.
2134 # We could theoretically do this while morphing, but then annotation
2135 # would get a lot more complicated.
2136 newNodeName = self.geometryConstructors.get(
2137 self.newType.upper(), None)
2138 if newNodeName is None:
2139 return
2140
2141 # we only have names in geometryConstructors because we're defined
2142 # lexically above the geometries
2143 nodeClass = globals()[newNodeName]
2144 raise ReplaceNode(nodeClass.fromCastArgument(self.value))
2145
2146 def addFieldInfo(self, context):
2147 # We copy units and UCDs from the subordinate value (if it's there;
2148 # NULLs have nothing, of course). That has the somewhat unfortunate
2149 # effect that we may be declaring units on strings. Ah well.
2150 if hasattr(self.value, "fieldInfo"):
2151 self.fieldInfo = self.value.fieldInfo.change(
2152 type=self.newType, tainted=True)
2153 else:
2154 self.fieldInfo = fieldinfo.FieldInfo(self.newType, "", "")
2155
2156 def flatten(self):
2157 if self.children[-2].lower().endswith("char ( * )"):
2158 # postgres, surprisingly, can't cast to char(*), so we just hack
2159 # it to text (the endswith is for national char)
2160 self.children[-2] = "TEXT"
2161 return FieldInfoedNode.flatten(self)
2162
2163
2164 class CoalesceExpression(FieldInfoedNode, TransparentMixin):
2165 type = "coalesceExpression"
2166
2167 # The trouble as to inference here is that of course anything
2168 # might happen per-row, as people could stick in whatever.
2169 # But we assume well-meaning people and thus just take the annotation
2170 # from the first argument (which is supposed to be the "normal case").
2171 def addFieldInfo(self, context):
2172 subordinates = self._getInfoChildren()
2173 if subordinates:
2174 self.fieldInfo = subordinates[0].fieldInfo.change(tainted=True)
2175 else:
2176 # there's probably only nulls here; make it so we produce
2177 # the most robust NULL VOTable has.
2178 self.fieldInfo = fieldinfo.FieldInfo('real', None, None)
2179
2180
2181 class CaseExpression(FieldInfoedNode, TransparentMixin):
2182 type = "searchedCase"
2183 bindings = ["searchedCase", "simpleCase"]
2184
2185 def addFieldInfo(self, context):
2186 results, nextIsResult = [], False
2187 for c in self.children:
2188 if c in {"THEN", "ELSE"}:
2189 nextIsResult = 1
2190 else:
2191 if nextIsResult:
2192 results.append(c)
2193 nextIsResult = False
2194
2195 for res in results:
2196 # we try to find a case that has proper user data (i.e., a column)
2197 # attached; anything else will probably be empty info.
2198 if res.fieldInfo and res.fieldInfo.userData:
2199 self.fieldInfo = res.fieldInfo.change(tainted=True)
2200 break
2201
2202 else:
2203 # We probably only have literals. Get the type from the first
2204 # and run. Should we make sure that all cases have matching types?
2205 for res in results:
2206 if res.fieldInfo and res.fieldInfo.type:
2207 self.fieldInfo = res.fieldInfo.change(tainted=True)
2208 break
2209
2210 else:
2211 # we cannot venture any guess what we'll return. Let's avoid
2212 # wild guesses for now and just fail.
2213 raise common.Error("CASE statement seems to have no results.")
2214
2215
2216 ###################### Geometry and stuff that needs morphing into real SQL
2217
2218 class CoosysMixin(object):
2219 """is a mixin that works cooSys into FieldInfos for ADQL geometries.
2220 """
2221 _a_cooSys = None
2222
2223 @classmethod
2224 def _getInitKWs(cls, _parseResult):
2225 refFrame = _parseResult.get("coordSys", "")
2226 if isinstance(refFrame, ColumnReference): # pragma: no cover
2227 raise NotImplementedError("References frames must not be column"
2228 " references.")
2229 return {"cooSys": refFrame}
2230
2231
2232 class GeometryNode(CoosysMixin, FieldInfoedNode):
2233 """Nodes for geometry constructors.
2234
2235 In ADQL 2.1, most of these became polymorphous. For instance, circles
2236 can be constructed with a point as the first (or second, if a coosys
2237 is present) argument; that point can also be a column reference.
2238
2239 Also, these will always get morphed in some way (as the database
2240 certainly doesn't understand ADQL geometries). So, we're
2241 trying to give the morphers a fair chance of not getting confused
2242 despite the wild variety of argument forms and types.
2243
2244 stcArgs is a list of symbolic names that *might* contain stc (or similar)
2245 information. Some of the actual attributes will be None.
2246
2247 Flatten is only there for debugging; it'll return invalid SQL.
2248 OrigArgs is not for client consumption; clients must go through the
2249 symbolic names.
2250
2251 If you want your geometry to support casts, give it a
2252 fromCastArgs(args) method that will, in general, probably replace
2253 the node with a GeometryCast node. You'll then have to teach GeometryCast
2254 how to annotate your geometry and add the type name to the
2255 geometryConstructors dictionary in CastSpecification.
2256 """
2257 _a_origArgs = None
2258
2259 def flatten(self):
2260 return "%s%s"%(self.type.upper(),
2261 "".join(flatten(arg) for arg in self.origArgs))
2262
2263 @classmethod
2264 def _getInitKWs(cls, _parseResult):
2265 return {"origArgs": list(_parseResult[1:])}
2266
2267 def addFieldInfo(self, context):
2268 fis = [attr.fieldInfo
2269 for attr in
2270 (getattr(self, arg) for arg in self.stcArgs if getattr(self, arg))
2271 if attr and attr.fieldInfo]
2272 childUserData, childUnits = [], []
2273 thisSystem = tapstc.getSTCForTAP(self.cooSys)
2274
2275 # get reference frame from first child if not given in node and
2276 # one is defined there.
2277 if thisSystem.astroSystem.spaceFrame.refFrame is None:
2278 if fis and fis[0].stc:
2279 thisSystem = fis[0].stc
2280
2281 ignoreTableStats = False
2282 for index, fi in enumerate(fis):
2283 childUserData.extend(fi.userData)
2284 childUnits.append(fi.unit)
2285 ignoreTableStats = ignoreTableStats or fi.ignoreTableStats
2286 if not context.policy.match(fi.stc, thisSystem):
2287 context.errors.append("When constructing %s: Argument %d has"
2288 " incompatible STC"%(self.type, index+1))
2289
2290 self.fieldInfo = fieldinfo.FieldInfo(
2291 type=self.sqlType,
2292 ucd="",
2293 unit="",
2294 userData=tuple(childUserData),
2295 stc=thisSystem,
2296 ignoreTableStats=ignoreTableStats)
2297 self.fieldInfo.properties["xtype"] = self.xtype
2298
2299
2300 class GeometryCast(GeometryNode):
2301 """A cast to a geometry type.
2302
2303 For these, we defer to functions built into the database.
2304 """
2305 _a_argument = None
2306 _a_cast_function = None
2307
2308 resultingTypes = {
2309 "cast_to_point": "spoint",
2310 "cast_to_circle": "scircle",
2311 "cast_to_polygon": "spoly",}
2312
2313 def addFieldInfo(self, context):
2314 self.fieldInfo = fieldinfo.FieldInfo(
2315 type=self.resultingTypes[self.cast_function],
2316 unit='',
2317 ucd='',
2318 stc=None)
2319
2320 def flatten(self):
2321 return "{}({})".format(
2322 self.cast_function,
2323 self.argument.flatten())
2324
2325
2326 class Point(GeometryNode):
2327 type = "point"
2328 _a_x = _a_y = None
2329 xtype = "point"
2330 sqlType = "spoint"
2331
2332 stcArgs = ("x", "y")
2333
2334 def flatten(self):
2335 return "%s(%s)"%(self.type.upper(),
2336 ", ".join(flatten(arg) for arg in [self.x, self.y]))
2337
2338 @classmethod
2339 def _getInitKWs(cls, _parseResult):
2340 x, y = parseArgs(_parseResult["args"]) #noflake: locals returned
2341 return locals()
2342
2343 @classmethod
2344 def fromCastArgument(self, arg):
2345 raise ReplaceNode(GeometryCast(
2346 argument=arg,
2347 cast_function="cast_to_point"))
2348
2349
2350 class Circle(GeometryNode):
2351 """A circle parsed from ADQL.
2352
2353 There are two ways a circle is specified: either with (x, y, radius)
2354 or as (center, radius). In the second case, center is an spoint-valued
2355 column reference. Cases with a point-valued literal are turned into
2356 the first variant during parsing.
2357 """
2358 type = "circle"
2359 _a_radius = None
2360 _a_center = None
2361 stcArgs = ("center", "radius")
2362 xtype = "circle"
2363 sqlType = "scircle"
2364
2365 @classmethod
2366 def _getInitKWs(cls, _parseResult):
2367 args = parseArgs(_parseResult["args"])
2368 res = {a: None for a in cls.stcArgs}
2369 if len(args)==2:
2370 res["center"], res["radius"] = args[0], args[1]
2371 elif len(args)==3:
2372 res["center"] = Point(cooSys=_parseResult.get("coordSys", ""),
2373 x=args[0], y=args[1])
2374 res["radius"] = args[2]
2375 else: # pragma: no cover
2376 assert False, "Grammar let through invalid args to Circle"
2377 return res
2378
2379 @classmethod
2380 def fromCastArgument(self, arg):
2381 raise ReplaceNode(GeometryCast(
2382 argument=arg,
2383 cast_function="cast_to_circle"))
2384
2385
2386 class MOC(GeometryNode):
2387 """a MOC in an ADQL syntax tree.
2388
2389 This can be constructed from an ASCII-MOC string or from an order
2390 and a geometry value expression.
2391 """
2392 type = "moc"
2393 _a_literal = None
2394 _a_order = None
2395 _a_geometry = None
2396 stcArgs = ()
2397 xtype = "moc"
2398 sqlType = "smoc"
2399
2400 @classmethod
2401 def _getInitKWs(cls, _parseResult):
2402 _args = parseArgs(_parseResult["args"])
2403 if len(_args)==1:
2404 literal = _args[0]
2405
2406 elif len(_args)==2:
2407 order, geometry = _args[0], _args[1]
2408
2409 else:
2410 raise common.Error("MOC() takes either one literal or order, geo")
2411
2412 return locals()
2413
2414 def flatten(self):
2415 # there's no point morphing this; when people put this into db
2416 # engines, they can just as well use the ADQL signature.
2417 if self.literal is None:
2418 return "smoc(%s, %s)"%(flatten(self.order), flatten(self.geometry))
2419 else:
2420 return "smoc(%s)"%flatten(self.literal)
2421
2422
2423 class Box(GeometryNode):
2424 type = "box"
2425 _a_x = _a_y = _a_width = _a_height = None
2426 stcArgs = ("x", "y", "width", "height")
2427 xtype = "polygon"
2428 sqlType = "sbox"
2429
2430 @classmethod
2431 def _getInitKWs(cls, _parseResult):
2432 x, y, width, height = parseArgs( #noflake: locals returned
2433 _parseResult["args"])
2434 return locals()
2435
2436
2437 class PolygonCoos(FieldInfoedNode):
2438 """a base class for the various argument forms of polygons.
2439
2440 We want to tell them apart to let the grammar tell the tree builder
2441 what it thinks the arguments were. Polygon may have to reconsider
2442 this when it learns the types of its arguments, but we don't want
2443 to discard the information coming from the grammar.
2444 """
2445 _a_args = None
2446
2447 @classmethod
2448 def _getInitKWs(cls, _parseResult):
2449 return {"args": parseArgs(_parseResult["args"])}
2450
2451 def addFieldInfo(self, context):
2452 # these fieldInfos are never used because Polygon doesn't ask us.
2453 pass
2454
2455 def flatten(self):
2456 return ", ".join(flatten(a) for a in self.args)
2457
2458
2459 class PolygonSplitCooArgs(PolygonCoos):
2460 type = "polygonSplitCooArgs"
2461
2462
2463 class PolygonPointCooArgs(PolygonCoos):
2464 type = "polygonPointCooArgs"
2465
2466
2467 class Polygon(GeometryNode):
2468 type = "polygon"
2469 _a_coos = None
2470 _a_points = None
2471 stcArgs = ("coos", "points")
2472 xtype = "polygon"
2473 sqlType = "spoly"
2474
2475 @classmethod
2476 def _getInitKWs(cls, _parseResult):
2477 # XXX TODO: The grammar will parse even-numbered arguments >=6 into
2478 # splitCooArgs. We can't fix that here as we don't have reliable
2479 # type information at this point. Fix coos/points confusion
2480 # in addFieldInfo, I'd say
2481 arg = parseArgs(_parseResult["args"])[0]
2482
2483 if arg.type=="polygonPointCooArgs":
2484 # geometry-typed arguments
2485 res = {"points": tuple(parseArgs(arg.args))}
2486
2487 # See if they're all literal points, which which case we fall
2488 # back to the split args
2489 for item in res["points"]:
2490 if item.type!="point":
2491 return res
2492 # all points: mutate args to let us fall through to the split coup
2493 # case
2494 arg.type = "polygonSplitCooArgs"
2495 newArgs = []
2496 for item in res["points"]:
2497 newArgs.extend([item.x, item.y])
2498 arg.args = newArgs
2499
2500 if arg.type=="polygonSplitCooArgs":
2501 # turn numeric expressions into pairs
2502 coos, toDo = [], list(arg.args)
2503 while toDo:
2504 coos.append(tuple(toDo[:2]))
2505 del toDo[:2]
2506 res = {"coos": coos}
2507
2508 else: # pragma: no cover
2509 assert False, "Invalid arguments to polygon"
2510
2511 return res
2512
2513 @classmethod
2514 def fromCastArgument(self, arg):
2515 raise ReplaceNode(GeometryCast(
2516 argument=arg,
2517 cast_function="cast_to_polygon"))
2518
2519 def addFieldInfo(self, name):
2520 if self.points is not None:
2521 systemSource = self.points
2522 elif self.coos is not None:
2523 systemSource = (c[0] for c in self.coos)
2524 else: # pragma: no cover
2525 assert False
2526
2527 if self.cooSys and self.cooSys!="UNKNOWN":
2528 thisSystem = tapstc.getSTCForTAP(self.cooSys)
2529
2530 for geo in systemSource:
2531 if geo.fieldInfo.stc and geo.fieldInfo.stc.astroSystem.spaceFrame.refFrame:
2532 thisSystem = geo.fieldInfo.stc
2533 break
2534 else:
2535 thisSystem = tapstc.getSTCForTAP("UNKNOWN")
2536
2537 userData, tainted = collectUserData(
2538 self.points or [c[0] for c in self.coos]+[c[1] for c in self.coos])
2539 self.fieldInfo = fieldinfo.FieldInfo(
2540 type=self.sqlType, unit="deg", ucd="phys.angArea",
2541 userData=userData, tainted=tainted,
2542 stc=thisSystem)
2543
2544
2545 _regionMakers = []
2546 def registerRegionMaker(fun):
2547 """adds a region maker to the region resolution chain.
2548
2549 region makers are functions taking the argument to REGION and
2550 trying to do something with it. They should return either some
2551 kind of FieldInfoedNode that will then replace the REGION or None,
2552 in which case the next function will be tried.
2553
2554 As a convention, region specifiers here should always start with
2555 an identifier (like simbad, siapBbox, etc, basically [A-Za-z]+).
2556 The rest is up to the region maker, but whitespace should separate
2557 this rest from the identifier.
2558
2559 The entire region functionality will probably disappear with TAP 1.1.
2560 Don't do anything with it any more. Use ufuncs instead.
2561 """
2562 _regionMakers.append(fun)
2563
2564
2565 @symbolAction("region")
2566 def makeRegion(children):
2567 if len(children)!=4 or not isinstance(children[2], CharacterStringLiteral):
2568 raise common.RegionError("Invalid argument to REGION: '%s'."%
2569 "".join(flatten(c) for c in children[2:-1]),
2570 hint="Here, regions must be simple strings; concatenations or"
2571 " non-constant parts are forbidden. Use ADQL geometry expressions"
2572 " instead.")
2573 arg = children[2].value
2574 for r in _regionMakers:
2575 res = r(arg)
2576 if res is not None:
2577 return res
2578 raise common.RegionError("Invalid argument to REGION: '%s'."%
2579 arg, hint="None of the region parsers known to this service could"
2580 " make anything of your string. While STC-S should in general"
2581 " be comprehendable to TAP services, it's probably better to"
2582 " use ADQL geometry functions.")
2583
2584
2585 class STCSRegion(FieldInfoedNode):
2586 bindings = [] # we're constructed by makeSTCSRegion, not by the parser
2587 type = "stcsRegion"
2588 xtype = "adql:REGION"
2589
2590 _a_tapstcObj = None # from tapstc -- STCSRegion or a utils.pgshere object
2591
2592 def _polish(self):
2593 self.cooSys = self.tapstcObj.cooSys
2594
2595 def addFieldInfo(self, context):
2596 # XXX TODO: take type and unit from tapstcObj
2597 self.fieldInfo = fieldinfo.FieldInfo("spoly", unit="deg", ucd=None,
2598 stc=tapstc.getSTCForTAP(self.cooSys))
2599
2600 def flatten(self): # pragma: no cover
2601 raise common.FlattenError("STCRegion objectcs cannot be flattened, they"
2602 " must be morphed.")
2603
2604
2605 def makeSTCSRegion(spec):
2606 try:
2607 return STCSRegion(stc.parseSimpleSTCS(spec))
2608 except stc.STCSParseError: #Not a valid STC spec, try next region parser
2609 return None
2610
2611 registerRegionMaker(makeSTCSRegion)
2612
2613
2614 class Centroid(FunctionNode):
2615 type = "centroid"
2616
2617 def addFieldInfo(self, context):
2618 self.fieldInfo = fieldinfo.FieldInfo(type="spoint",
2619 unit="", ucd="",
2620 userData=collectUserData(self._getInfoChildren())[0])
2621
2622
2623 class Distance(FunctionNode):
2624 type = "distanceFunction"
2625
2626 def addFieldInfo(self, context):
2627 self.fieldInfo = fieldinfo.FieldInfo(type="double precision",
2628 unit="deg", ucd="pos.angDistance",
2629 userData=collectUserData(self._getInfoChildren())[0])
2630
2631 def optimize(self, stack):
2632 assert len(self.args)==2, "unexpected arguments in distance"
2633 self.args = list(self.args)
2634 self.args[0], self.args[1] = _sortLargeFirst(self.args[0], self.args[1])
2635
2636 @classmethod
2637 def _getInitKWs(cls, _parseResult):
2638 args = parseArgs(_parseResult["args"])
2639 if len(args)==4:
2640 # always normalise to (point, point)
2641 args = [
2642 Point(cooSys="", x=args[0], y=args[1]),
2643 Point(cooSys="", x=args[2], y=args[3])]
2644 return locals()
2645
2646
2647 class PredicateGeometryFunction(FunctionNode):
2648 type = "predicateGeometryFunction"
2649
2650 _pgFieldInfo = fieldinfo.FieldInfo("integer", "", "")
2651
2652 def optimize(self, stack):
2653 if len(self.args)!=2:
2654 assert False, "Grammar let through bad arguments to pgf"
2655
2656 self.args = list(self.args)
2657
2658 # by ADQL, an INTERSECTS with a point has to become a CONTAINS
2659 if self.funName=="INTERSECTS":
2660 ltype = getattr(self.args[0].fieldInfo, "type", None)
2661 rtype = getattr(self.args[1].fieldInfo, "type", None)
2662 if ltype=='spoint':
2663 self.funName = "CONTAINS"
2664 elif rtype=='spoint':
2665 self.funName = "CONTAINS"
2666 self.args[0], self.args[1] = self.args[1], self.args[0]
2667
2668 leftInd, rightInd = 0, 1
2669 # optimise the common case of contains(point, circle); both
2670 # q3c and pgsphere won't use an index (properly) if the sequence
2671 # of the arguments is "wrong".
2672 if (self.args[leftInd].type=="point"
2673 and self.args[rightInd].type=="circle"):
2674
2675 if _isConstant([self.args[leftInd]]):
2676 self.args[leftInd], self.args[rightInd].center = \
2677 self.args[rightInd].center, self.args[leftInd]
2678
2679 else:
2680 self.args[leftInd], self.args[rightInd].center = _sortLargeFirst(
2681 self.args[leftInd], self.args[rightInd].center)
2682 # in case we swapped, coosys meta might be out of whack, so
2683 # fix that:
2684 self.args[rightInd].cooSys = self.args[rightInd].center.cooSys
2685
2686
2687 def addFieldInfo(self, context):
2688 # swallow all upstream info, it really doesn't help here
2689 self.fieldInfo = self._pgFieldInfo
2690
2691 def flatten(self):
2692 return "%s(%s)"%(self.funName, ", ".join(flatten(a) for a in self.args))
2693
2694
2695 class PointFunction(FunctionNode):
2696 type = "pointFunction"
2697
2698 def _makeCoordsysFieldInfo(self):
2699 return fieldinfo.FieldInfo("text", unit="", ucd="meta.ref;pos.frame")
2700
2701 def _makeCoordFieldInfo(self):
2702 # this should pull in the metadata from the 1st or 2nd component
2703 # of the argument. However, given the way geometries are constructed
2704 # in ADQL, what comes back here is in degrees in the frame of the
2705 # child always. We're a bit pickier with the user data -- if there's
2706 # exactly two user data fields in the child, we assume the child
2707 # has been built from individual columns, and we try to retrieve the
2708 # one pulled out.
2709 childFieldInfo = self.args[0].fieldInfo
2710 if len(childFieldInfo.userData)==2:
2711 userData = (childFieldInfo.userData[int(self.funName[-1])-1],)
2712 else:
2713 userData = childFieldInfo.userData
2714 return fieldinfo.FieldInfo("double precision",
2715 ucd=None, unit="deg", userData=userData)
2716
2717 def addFieldInfo(self, context):
2718 if self.funName=="COORDSYS":
2719 makeFieldInfo = self._makeCoordsysFieldInfo
2720 else: # it's coordN
2721 makeFieldInfo = self._makeCoordFieldInfo
2722 self.fieldInfo = makeFieldInfo()
2723
2724
2725 class Area(FunctionNode):
2726 type = "area"
2727
2728 def addFieldInfo(self, context):
2729 self.fieldInfo = fieldinfo.FieldInfo(type="double precision",
2730 unit="deg**2", ucd="phys.angSize",
2731 userData=collectUserData(self._getInfoChildren())[0])
2732
2733
2734 ############################### the odd one: DDL, CREATE TABLE AS
2735
2736 class CreateAs(ADQLNode):
2737 """this must basically work like the embedded query specification,
2738 except that it morphs into a create table statement.
2739
2740 Well, it also has to arrange for name mangling of the uploaded
2741 table and for having it added to the management tables. All this
2742 happens during annotation time, as we don't have the necessary
2743 information while we are parsing. Yes, that's a bit more
2744 brittle than I would like it to be, but exposing the requesting
2745 users to the parsing code seems dramatically overdoing it, too.
2746 """
2747 type = "createAs"
2748
2749 _a_destName = None
2750
2751 @classmethod
2752 def _getInitKWs(cls, parseResult):
2753 return {"destName": parseResult[2]}
2754
2755 def flatten(self):
2756 return "CREATE TABLE {} AS ".format(flatten(self.destName))
2757
2758 def allocateTAPUpload(self, context):
2759 """creates a tap_upload table for the table we are selecting into.
2760
2761 This is called from statement's addFieldInfos. It is important
2762 to not hand through the addFieldInfos call to our table, because
2763 we don't have that at this point. Instead, we poke our
2764 child's physicalName attribute.
2765 """
2766 # this is all a DaCHS extension, so we're liberally importing
2767 # from DaCHS' guts
2768 from gavo.web import tap_uploads
2769 from gavo import base
2770
2771 requestedName = self.destName.name.lower()
2772 if not re.match("[a-z_]+$", requestedName):
2773 raise NotImplementedError("Non-regular upload table name")
2774
2775 with base.getWritableUntrustedConn() as conn:
2776 self.destName.physicalName = tap_uploads.uploadUserTable(
2777 conn,
2778 requestedName,
2779 None,
2780 context.fieldInfoGetter.forUser)
2781
2782
2783 ############################## Bookkeeping
2784
2785 _ADDITIONAL_NODES = []
2786 def registerNode(node):
2787 """registers a node class or a symbolAction from a module other than node.
2788
2789 This is a bit of magic -- some module can call this to register a node
2790 class that is then bound to some parse action as if it were in nodes.
2791
2792 I'd expect this to be messy in the presence of chaotic imports (when
2793 classes are not necessarily singletons and a single module can be
2794 imported more than once. For now, I ignore this potential bomb.
2795 """
2796 # adding a node probably changes the grammar bindings, so we
2797 # need to clear the cached grammar
2798 getTreeBuildingGrammar.cache_clear()
2799
2800 # if a module registering a node is re-loaded, we have to remove the
2801 # node it previously registered, or we'll get a symbol clash.
2802 # It's not totally straightforward to figure out what the previous
2803 # version was; for now, let's look at type, but given the various
2804 # ways nodes might use to bind, that's potentially not enough.
2805 for existing in _ADDITIONAL_NODES:
2806 if existing.type==node.type:
2807 _ADDITIONAL_NODES.remove(existing)
2808 break
2809
2810 _ADDITIONAL_NODES.append(node)
2811
2812
2813 def getNodeClasses():
2814 """returns a list of node classes (and standalone parse actions) available
2815 for tree building.
2816
2817 This is what needs to be passed to adql.getADQLGrammarCopy to get
2818 a proper parse tree out of the parser.
2819 """
2820 res = []
2821 for item in itertools.chain(globals().values(), _ADDITIONAL_NODES):
2822 if isinstance(item, type) and issubclass(item, ADQLNode):
2823 res.append(item)
2824 if hasattr(item, "parseActionFor"):
2825 res.append(item)
2826 return res
2827
2828
2829 @functools.lru_cache(1)
2830 def getTreeBuildingGrammar():
2831 return grammar.getADQLGrammarCopy(getNodeClasses())
2832
2833
2834 if __name__=="__main__": # pragma: no cover
2835 DEBUG_BUILDERS = True
2836 syms, g = getTreeBuildingGrammar()
2837 print(syms["numericValueExpression"].parseString("4.5e-9@{J/pc**2}/44.3@{mm**-2}", parseAll=True)[0].asTree())
2838 #g.parseString("select 4.5e-9@{J/pc**2}/44.3@{mm**-2} from spatial", parseAll=True)