Debian Codegraph @

gavo/adql/morphpg.py

raw
1 """
2 Morphing ADQL into queries that postgres/pgSphere can understand.
3
4 For most of ADQL, Postgres supports most of the stuff out of the box, with
5 perhaps a few syntactic differences.
6
7 Spherical geometry is morphed rather extensively, mainly to pgsphere.
8 There is support for legacy q3c, but since q3c will always be inadequate
9 for full ADQL geometry support, we'll phase this out (although it's a good
10 deal faster when it works).
11 """
12
13 #c Copyright 2008-2025, the GAVO project <[email protected]>
14 #c
15 #c This program is free software, covered by the GNU GPL. See the
16 #c COPYING file in the source distribution.
17
18
19 import functools
20
21 from gavo.adql import common
22 from gavo.adql import morphhelpers
23 from gavo.adql import nodes
24 from gavo.adql.nodes import flatten
25 from gavo.stc import tapstc
26
27
28 class PostgresMorphError(common.MorphError):
29 pass
30
31
32 def getOriginal(node):
33 """returns the node.original if it exists, node itself otherwise.
34
35 This is to undo pgsphere morphing when pgsphereCode has been
36 inserted.
37 """
38 if getattr(node, "original", None) is None:
39 return node
40 else:
41 return node.original
42
43
44 ######## Begin q3c specials
45 # q3c morphing must happen before pgsphere morphs all the mess to
46 # become spoints and stuff (at least the way we built things so far).
47 # Hence, this is written as a fairly freaky early morpher.
48
49 def _flatAndMorph(node):
50 # This helper flattens a node after applying standard morphs on it.
51 # I need this for the arguments of q3c stuff, since there may
52 # be ADQL specifics in there.
53 if isinstance(node, str):
54 return node
55 else:
56 return nodes.flatten(morphPG(node)[1])
57
58
59 def _q3cIndexPresent(args):
60 """returns True if we think there's a q3c index on anything that's
61 mentioned in args.
62
63 This is a bit heuristic in that it will go for any user data in
64 any field info in args. This certainly means nothing more
65 than "there's a chance the query planner might use a q3c index here".
66 """
67 for fi in nodes.iterFieldInfos(args):
68 for ud in fi.userData:
69 if "q3c" in (ud.isIndexed() or []):
70 return True
71
72 return False
73
74
75 def _booleanizeContainsQ3C(node, operator, operand):
76 """turns ADQL CONTAINS calls into q3c expressions if appropriate.
77
78 This will only work if the arguments have been morphed into pgsphere
79 geometries already. It will leave alone anything it doesn't understand,
80 hopefully for pgsphere to pick it up.
81 """
82 args = []
83 for arg in node.args:
84 if hasattr(arg, "original"): # recover pre-pgsphere-morph object
85 args.append(arg.original)
86 else:
87 args.append(arg)
88
89 if not _q3cIndexPresent(args):
90 return None
91
92 # leave morphing to someone else if we don't check for point in shape
93 # or if system transformations are required.
94 if len(args)!=2:
95 return None
96 if not hasattr(args[0], "cooSys") or not hasattr(args[1], "cooSys"):
97 # arguments do not look like geometries; leave it to someone else
98 # to blow up
99 return None
100 if tapstc.getPGSphereTrafo(args[0].cooSys, args[1].cooSys) is not None:
101 # we'll need a transform; q3c cannot do this.
102 return None
103
104 expr = None
105 p, shape = getOriginal(args[0]), getOriginal(args[1])
106 if p.type!="point":
107 # punt to pgsphere
108 return None
109
110 if shape.type=="circle":
111 # if we have an spoint-valued center, there's nothing q3c can do
112 if p.x is None:
113 return None
114
115 # the way PredicateGeometryFunction.optimize sorts the arguments
116 # has constants last, and here we want constants first.
117 expr = ("q3c_join(%s, %s, %s, %s, %s)"%tuple(map(_flatAndMorph,
118 (shape.center.x, shape.center.y, p.x, p.y, shape.radius))))
119
120 elif shape.type=="polygon":
121 # if there's spoint columns in the array, there's no coos but
122 # points, and q3c can't do it.
123 if shape.coos is not None:
124 expr = "q3c_poly_query(%s, %s, ARRAY[%s])"%(
125 _flatAndMorph(p.x), _flatAndMorph(p.y), ",".join([
126 "%s,%s"%(_flatAndMorph(x), _flatAndMorph(y)) for x,y in shape.coos]))
127
128 return expr
129
130
131 def _distanceToQ3C(node, state):
132 # this is called by _distanceToPG below (which seems preferable
133 # to a complex mechanism letting us decouple pgs and q3c morphing)
134 # if it finds a q3c on any of node's arguments (and if there are
135 # split-coordinate arguments).
136 #
137 # Experimentally, comparisons with q3c_dist are much less likely to
138 # be index-optimised than q3c_join, so we take a bit of pains to
139 # generate a q3c_join. This includes rather crazy stack manipulations
140 # to tell the comparison to disappear.
141
142 parent = state.nodeStack[-1]
143 if (parent.type!="comparisonPredicate"
144 or parent.opr not in ['<', '<=', '>', '>=']):
145 # no supported comparison; pass this on to pgsphere (which probably
146 # isn't much slower, as q3c_dist is bad with indices, too).
147 return None
148
149 # now figure out if we're comparing within or without
150 op1, opr, otherOp = parent.op1, parent.opr, parent.op2
151 if getOriginal(op1) is not getOriginal(node):
152 opr = {'<': '>', '<=': '>=', '>': '<', '>=': '<='}[opr]
153 otherOp = op1
154 negation = ""
155 if opr in ['>', '>=']:
156 negation = "NOT "
157
158 p1, p2 = node.original.args[1], node.original.args[0]
159
160 try:
161 fillers = (negation,) + tuple(
162 flatten(a) for a in (p1.x, p1.y, p2.x, p2.y, otherOp))
163 except AttributeError:
164 # arguments are not simple points -- punt to pgsphere.
165 return None
166
167 parent.OVERRIDE_RESULT = "%s q3c_join(%s, %s, %s, %s, %s)"%fillers
168 return node
169
170 ######### End q3c specials
171
172
173
174 ######### Begin morphing to pgSphere
175
176 class PgSphereCode(object):
177 """A node that contains serialized pgsphere expressions plus
178 a coordinate system id for cases in which we must conform.
179
180 Pass the optional original (the node that generates the stuff)
181 to allow code like the q3c booleanizer above to still work on
182 things if necessary.
183 """
184 type = "pgsphere literal"
185
186 def __init__(self, cooSys, content, original=None):
187 self.cooSys, self.content = cooSys, content
188 self.original = original
189
190 def flatten(self):
191 return self.content
192
193 def iterAttributes(self):
194 if False:
195 yield None
196
197 def iterTree(self):
198 return self.original.iterTree()
199
200
201 def _morphCircle(node, state):
202 return PgSphereCode(node.cooSys,
203 "scircle(%s, RADIANS(%s))"%(
204 _flatAndMorph(node.center), _flatAndMorph(node.radius)),
205 original=node)
206
207
208 def _morphPoint(node, state):
209 return PgSphereCode(node.cooSys,
210 "spoint(RADIANS(%s), RADIANS(%s))"%tuple(
211 flatten(a) for a in (node.x, node.y)),
212 original=node)
213
214
215 def _makePoly(cooSys, points, node):
216 # helper for _morph(Polygon|Box)
217 return PgSphereCode(cooSys,
218 "(SELECT spoly(q.p) FROM (VALUES %s ORDER BY column1) as q(ind,p))"%", ".join(
219 '(%d, %s)'%(i, p) for i, p in enumerate(points)),
220 original=node)
221
222
223 def _morphPolygon(node, state):
224 if node.coos is not None:
225 points = ['spoint(RADIANS(%s), RADIANS(%s))'%(
226 _flatAndMorph(a[0]), _flatAndMorph(a[1]))
227 for a in node.coos]
228 elif node.points is not None:
229 points = [_flatAndMorph(p) for p in node.points]
230 else: # pragma: no cover
231 assert False
232
233 return _makePoly(node.cooSys, points, node)
234
235
236 def _morphBox(node, state):
237 args = tuple("RADIANS(%s)"%_flatAndMorph(v) for v in (
238 node.x, node.width, node.y, node.height))
239 points = [
240 "spoint(%s-%s/2, %s-%s/2)"%args,
241 "spoint(%s-%s/2, %s+%s/2)"%args,
242 "spoint(%s+%s/2, %s+%s/2)"%args,
243 "spoint(%s+%s/2, %s-%s/2)"%args]
244 return _makePoly(node.cooSys, points, node)
245
246
247 def _getSystem(node):
248 return getattr(getOriginal(node), "cooSys", None)
249
250
251 def _transformSystems(pgLiteral, fromSystem, toSystem):
252 # a helper to _booleanizeGeoPredsPGS
253 if fromSystem!=toSystem:
254 trafo = tapstc.getPGSphereTrafo(fromSystem, toSystem)
255 if trafo is not None:
256 pgLiteral = "(%s)%s"%(pgLiteral, trafo)
257 return pgLiteral
258
259
260 def _booleanizeGeoPredPGS(node, geoOp):
261 """returns an expression node for pgsphere for an ADQL
262 CONTAINS/INTERSECTS call.
263 """
264 expr = None
265 sys1, sys2 = _getSystem(node.args[0]), _getSystem(node.args[1])
266
267 if isinstance(node.args[0], tapstc.GeomExpr):
268 if isinstance(node.args[1], tapstc.GeomExpr):
269 raise NotImplementedError("Cannot have compound regions in both"
270 " arguments of a geometry predicate")
271 arg2Str = _transformSystems(flatten(node.args[1]), sys1, sys2)
272 expr = node.args[0].asLogic("(%%s %s (%s))"%(geoOp, arg2Str))
273
274 elif isinstance(node.args[1], tapstc.GeomExpr):
275 arg1Str = _transformSystems(flatten(node.args[0]), sys2, sys1)
276 expr = node.args[0].asLogic("((%s) %s (%%s))"%(arg1Str, geoOp))
277
278 else: # both arguments plain
279 arg1Str = _transformSystems(flatten(node.args[0]), sys1, sys2)
280 arg2Str = flatten(node.args[1])
281 expr = "((%s) %s (%s))"%(arg1Str, geoOp, arg2Str)
282
283 return expr
284
285
286 def _convertGeoPredicates(node, state):
287 """morphs contains and intersects to pgsphere expressions when
288 they are arguments to a suitable comparison.
289 """
290 if node.funName=="CONTAINS":
291 geoOp = "<@"
292 elif node.funName=="INTERSECTS":
293 geoOp = "&&"
294 else:
295 return node
296
297 parent = state.nodeStack[-1]
298 funCall, compareAgainst = morphhelpers.analyzeFuncComp(parent)
299 if funCall is None:
300 return node
301
302
303 compareAgainst = flatten(compareAgainst)
304 expr = _booleanizeContainsQ3C(node, parent.opr, compareAgainst)
305
306 if expr is None:
307 expr = _booleanizeGeoPredPGS(node, geoOp)
308
309 parent.OVERRIDE_RESULT = morphhelpers.addNotToBooleanized(
310 nodes.flatten(expr), parent.opr, compareAgainst)
311 return funCall
312
313
314 def _computePointFunction(node, state):
315 if node.funName=="COORD1":
316 return "DEGREES(long(%s))"%flatten(node.args[0])
317 elif node.funName=="COORD2":
318 return "DEGREES(lat(%s))"%flatten(node.args[0])
319 elif node.funName=="COORDSYS":
320 if node.args[0].fieldInfo:
321 cSys = tapstc.getTAPSTC(node.args[0].fieldInfo.stc)
322 else:
323 cSys = getattr(node.args[0], "cooSys", "UNKNOWN")
324 return "'%s'"%cSys
325 else:
326 return node
327
328
329 def _distanceToPG(node, state):
330 if _q3cIndexPresent(node.args):
331 res = _distanceToQ3C(node, state)
332 if res is not None:
333 return res
334
335 args = list(node.args)
336 parent = state.nodeStack[-1]
337
338 with state.onNodeStack(node):
339 expr = "DEGREES((%s) <-> (%s))"%tuple(flatten(a) for a in args)
340
341 # When used in comparisons, postgres (v11) doesn't use spoint
342 # indices in dist(a,b)<x expressions. So, I'll have to morph into
343 # contains statements if I am in such a situation.
344 funCall, compareAgainst = morphhelpers.analyzeFuncComp(
345 parent, ['<', '<=', '>', '>='])
346 if funCall is None:
347 return expr
348
349 # compareAgainst may or may not be morphed at this point, which
350 # I'd rather avoid, but that's not easy to guarantee. Let's
351 # hope morphing is idempotent and possibly morph again.
352 if isinstance(compareAgainst, nodes.ADQLNode):
353 compareAgainst = _pgMorpher._traverse(compareAgainst, state)
354
355 # now figure out if we're comparing within or without
356 op1, opr = parent.op1, parent.opr
357 if getOriginal(op1) is not getOriginal(node):
358 opr = {'<': '>', '<=': '>=', '>': '<', '>=': '<='}[opr]
359 negation = ""
360 if opr in ['>', '>=']:
361 negation = "NOT "
362
363 parent.OVERRIDE_RESULT = "%s (%s) <@ scircle(%s, RADIANS(%s))"%(
364 negation,
365 flatten(args[0]),
366 flatten(args[1]),
367 flatten(compareAgainst))
368
369 return expr
370
371
372 def _centroidToPG(node, state):
373 # pgsphere right now can only to centroids of points and circles. Try
374 # to come up with a good error message otherwise.
375
376 def _fail():
377 raise PostgresMorphError("Can only compute centroids of circles and points"
378 " yet. Complain to make us implement other geometries faster.")
379
380 arg = node.args[0]
381 if hasattr(arg, "original"):
382 arg = arg.original
383 if arg.type=="polygon" or arg.type=="box":
384 _fail()
385
386 if getattr(arg, "fieldInfo", None):
387 fi = arg.fieldInfo
388 if fi.type=="spoly" or fi.type=="sbox":
389 _fail()
390
391 return "@@(%s)"%(flatten(node.args[0]))
392
393
394 def _areaToPGSphere(node, state):
395 # pgsphere returns rad**2, adql wants deg**2
396 return "3282.806350011744*%s"%flatten(node)
397
398
399 def _regionToPG(node, state): # pragma: no cover
400 # Too obscure right now.
401 raise NotImplementedError("The REGION string you supplied is not"
402 " supported on this server")
403
404
405 def _stcsRegionToPGSphere(node, state):
406 # STCSRegions embed something returned by tapstc's parser. This is
407 # a pgsphere instance if we're lucky (just dump the thing as a string)
408 # or a tapstc.GeomExpr object if we're unlucky -- in that case, we
409 # leave the GeomExpr here and leave it to a contains or intersects
410 # handler to rewrite the entire expression.
411 if isinstance(node.tapstcObj, tapstc.GeomExpr):
412 return node.tapstcObj
413 else:
414 return PgSphereCode(node.cooSys, node.tapstcObj.asPgSphere())
415
416
417 _geometricMorphers = {
418 'circle': _morphCircle,
419 'point': _morphPoint,
420 'box': _morphBox,
421 'polygon': _morphPolygon,
422 "pointFunction": _computePointFunction,
423 "distanceFunction": _distanceToPG,
424 "centroid": _centroidToPG,
425 "region": _regionToPG,
426 "stcsRegion": _stcsRegionToPGSphere,
427 "area": _areaToPGSphere,
428 "predicateGeometryFunction": _convertGeoPredicates,
429 }
430
431
432 ########## End morphing to pgSphere
433
434
435
436 _renamedFunctions = {
437 "LOG": "LN",
438 "LOG10": "LOG",
439 "TRUNCATE": "TRUNC",
440 }
441
442 _BITWISE_MORPHERS = {
443 'BITWISE_NOT': lambda x: "~(%s)"%flatten(x),
444 'BITWISE_AND': lambda a, b: "(%s)&(%s)"%(flatten(a), flatten(b)),
445 'BITWISE_OR': lambda a, b: "(%s)|(%s)"%(flatten(a), flatten(b)),
446 'BITWISE_XOR': lambda a, b: "(%s)#(%s)"%(flatten(a), flatten(b)),
447 }
448
449
450 def _adqlFunctionToPG(node, state):
451 if node.funName in _renamedFunctions:
452 node.funName = _renamedFunctions[node.funName]
453
454 # ADQL lets RAND set a seed, fake this in an ugly way
455 if node.funName=='RAND':
456 if len(node.args)==1:
457 # I suppose we should execute a separate query here with
458 # a crafted call to setseed. There's no way to do
459 # that right now, and I'm not forcing it at this point since
460 # the semantics in the ADQL spec are dubious anyway.
461 return "random()"
462 else:
463 return "random()"
464
465 # ADQL has two-arg TRUNCATE/ROUND -- these become expressions,
466 # so we play it easy and return strings
467 elif node.funName=='TRUNC' or node.funName=='ROUND':
468 if len(node.args)==2:
469 val, prec = flatten(node.args[0]), flatten(node.args[1])
470 newTerm = nodes.Term(children=[
471 node.change(args=['(%s)*10^(%s)'%(val, prec)]),
472 "/",
473 "10^(%s)"%prec])
474 newTerm.addFieldInfo(None)
475 return newTerm
476
477 # ADQL SQUARE becomes a PG expression. Again, we downgrade to a string.
478 elif node.funName=='SQUARE':
479 return "(%s)^2"%flatten(node.args[0])
480
481 elif node.funName in _BITWISE_MORPHERS:
482 return _BITWISE_MORPHERS[node.funName](*node.args)
483
484 return node
485
486
487 def _morphTimestamp(node, state):
488 assert len(node.args)==1
489 return "(%s)::TIMESTAMP"%flatten(node.args[0])
490
491
492 class _PQAggregatedArray(nodes.TransparentMixin, nodes.FieldInfoedNode):
493 type = "_morphedArrayMap"
494
495
496 def _morphArrayMap(node, state):
497 # for now, we blindly serialise the expression (arg 1) into our new tree.
498 return _PQAggregatedArray(children=[
499 '(SELECT array_agg(',
500 node.args[0],
501 ') from unnest(',
502 node.args[1],
503 ') x)'])
504
505
506 _miscMorphers = {
507 "numericValueFunction": _adqlFunctionToPG,
508 "timestampFunction": _morphTimestamp,
509 "arrayMapFunction": _morphArrayMap,
510 }
511
512
513 class _PGSC(nodes.SelectQuery):
514 """A modifield SelectQuery that fixes the syntactic differences
515 between ADQL and postgres.
516 """
517 def flatten(self):
518 return nodes.flattenKWs(self,
519 ("SELECT", None),
520 ("", "setQuantifier"),
521 ("", "selectList"),
522 ("", "fromClause"),
523 ("", "whereClause"),
524 ("", "groupby"),
525 ("", "having"),
526 ("", "orderBy"),
527 ("LIMIT", "setLimit"))
528
529
530 class _PGQS(nodes.ADQLNode):
531 """A wrapper for a postgres query specification.
532
533 The only function here is to make sure there's just one LIMIT part
534 at the very end (except, of course, in deeper subqueries).
535
536 Nuking operand setLimits is already performed by _fixSetLimit below.
537 """
538 type = "postgres query specification"
539 _a_original = None
540 _a_setLimit = None
541 _a_offset = None
542
543 def flatten(self):
544 return nodes.flattenKWs(self,
545 ("", "original"),
546 ("LIMIT", "setLimit"),
547 ("OFFSET", "offset"))
548
549
550 def _insertPGSC(node, state):
551 """wraps a select clause into something that serializes to postgres.
552 """
553 return _PGSC.cloneFrom(node)
554
555
556 def _expandStars(node, state):
557 """tries to replace all expressions with * in a select list.
558
559 I'm forcing this because that seems easier than figuring out how
560 to apply the sequencing rules from sql1992, 7.5, to joins with more
561 than two operands.
562 """
563 # only work if annotation has taken place (else it's probably a test
564 # run anyway)
565 if state.nodeStack[-1].fieldInfos:
566 if node.allFieldsQuery:
567 return nodes.SelectList(
568 selectFields=state.nodeStack[-1].getSelectFields())
569 else:
570 newCols = []
571 for col in node.selectFields:
572 if isinstance(col, nodes.QualifiedStar):
573 newCols.extend(state.nodeStack[-1].fromClause.getFieldsForTable(
574 col.sourceTable))
575 else:
576 newCols.append(col)
577 return node.change(selectFields=tuple(newCols))
578
579 return node
580
581
582 def _forceAlias(node, state):
583 """forces anonymous expressions to have an alias.
584
585 We need this as we expand stars here, and with these we need some
586 way to refer to the items.
587 """
588 if isinstance(node.expr, str):
589 # this can happen if node.expr has been morphed. Though it may be
590 # silly, unconditionally add an alias (unless there already is one)
591 if node.alias is None:
592 node.alias = node.name
593 return node
594
595 if not isinstance(node.expr, nodes._BaseColumnReference
596 ) and node.alias is None:
597 node.alias = node.name
598 return node
599
600
601 def _fixSetLimit(node, state):
602 """postgres only wants a global limit on set expressions.
603 """
604 for n in node.getSelectClauses():
605 n.setLimit = None
606 offset = node.offset
607 node.offset = None
608 return _PGQS(original=node,
609 setLimit=node.setLimit and str(node.setLimit),
610 offset=offset)
611
612
613 @functools.lru_cache(None)
614 def _needsMaterialization():
615 """returns True if CTEs need to be explicitly materialised on our
616 current server to make them planner barriers.
617 """
618 from gavo import base
619 return base.getPgVersion()[0]>11
620
621 def _materializeIfNecessary(node, state):
622 """Makes sure CTEs are materialized.
623
624 starting with version 12, postgres will inline CTEs unless
625 they're explicitly materialised. Since we've materialised them
626 before, for consistency we make sure they are materialised in newer
627 postgres-es as well. We should probably have some way to have users
628 order us to not do it.
629 """
630 if _needsMaterialization():
631 for index, token in enumerate(node.children):
632 if token=='AS':
633 break
634 else:
635 raise PostgresMorphError("CTE seems to be missing an AS?")
636
637 index += 1
638 node.children = node.children[:index]+(
639 "MATERIALIZED",)+node.children[index:]
640 return node
641
642
643 _syntaxMorphers = {
644 "selectQuery": _insertPGSC,
645 'comparisonPredicate': morphhelpers.booleanizeComparisons,
646 'selectList': _expandStars,
647 'derivedColumn': _forceAlias,
648 "selectExpression": _fixSetLimit,
649 "withQuery": _materializeIfNecessary,
650 }
651
652 # Warning: if ever there are two Morphers for the same type, this will
653 # break, and we'll need to allow lists of Morphers (and need to think
654 # about their sequence...)
655 _allMorphers = _geometricMorphers.copy()
656 _allMorphers.update(_miscMorphers)
657 _allMorphers.update(_syntaxMorphers)
658
659
660 _pgMorpher = morphhelpers.Morpher(_allMorphers)
661
662 morphPG = _pgMorpher.morph