Debian Codegraph @

gavo/protocols/adqlglue.py

raw
1 """
2 Code to bind the adql library to the data center software.
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 sys
12
13 from gavo import adql
14 from gavo import base
15 from gavo import rsc
16 from gavo import rscdef
17 from gavo import svcs
18 from gavo import utils
19
20
21 def makeFieldInfo(column, sqlName=None):
22 """returns an adql.tree.FieldInfo object from a rscdef.Column.
23 """
24 return adql.FieldInfo(column.type,
25 column.unit, column.ucd, (column,), stc=column.stc, sqlName=sqlName)
26
27
28 class TDContext(object):
29 """An object keeping track of the generation of a table definition
30 for ADQL output.
31 """
32 def __init__(self):
33 self.existingNames = set()
34
35 def getName(self, desiredName):
36 while desiredName in self.existingNames:
37 desiredName = desiredName+"_"
38 self.existingNames.add(desiredName)
39 return desiredName
40
41
42 # For columns of types that have no automatic VOTable null value,
43 # we make up some when we don't have any yet. This is governed by
44 # the following dictionary.
45 # All this is in particular for columns that came into being from
46 # expressions.
47 #
48 # This largely follows what Mark Taylor does in topcat.
49 _artificialNULLs = {
50 "bytea": "255",
51 "smallint": "-32768",
52 "integer": "-2147483648",
53 "bigint": "-9223372036854775808",
54 }
55
56 def _makeColumnFromFieldInfo(ctx, colName, fi):
57 """constructs a rscdef.Column from a field info pair as left by the
58 ADQL machinery.
59
60 The strategy: If there's only one userData, we copy the Column
61 contained in there, update the unit and the ucd, plus a warning
62 if the Column has been tainted.
63
64 If there's more or less than one userData, we create a new
65 Column, use the data provided by fi and make up a description
66 consisting of the source descriptions. Add a taint warning
67 if necessary.
68
69 Since we cannot assign sensible verbLevels and assume the user wants
70 to see what s/he selected, all fields get verbLevel 1.
71
72 Types are a serious problem, handled by typesystems.
73 """
74 if len(fi.userData)==1:
75 res = svcs.OutputField.fromColumn(fi.userData[0])
76
77 if fi.type!=fi.userData[0].type:
78 res.xtype = None
79
80 if hasattr(fi.userData[0], "originalName"):
81 # the following is to undo column renaming for postgres-forbidden
82 # column names
83 colName = fi.userData[0].originalName
84
85 elif fi.userData[0].name.lower()==colName:
86 # undo case normalisation done by the ADQL machinery
87 # if we're reasonably sure there's no intervening AS
88 colName = fi.userData[0].name
89
90 else:
91 res = base.makeStruct(svcs.OutputField, name=colName)
92
93 res.name = ctx.getName(colName)
94 res.ucd = fi.ucd
95 res.unit = fi.unit
96 res.type = fi.type
97 if res.type is None:
98 # that's a literal NULL; it doesn't matter much what we use
99 # here, but the least troublesome NULLs in VOTable are for
100 # floats, so let's use them
101 res.type = 'real'
102
103 # XXX TODO: do something with stc's "broken" attribute
104 res.stc = fi.stc
105
106 if len(fi.userData)>1:
107 res.description = ("This field has traces of: %s"%("; ".join([
108 f.description for f in fi.userData if f.description])))
109
110 if fi.tainted:
111 res.description = (res.description+" -- *TAINTED*: the value"
112 " was operated on in a way that unit and ucd may be severely wrong")
113 if (fi.properties.get("src-expression", res.name)
114 !=res.name):
115 res.description += " [ADQL: {}]".format(
116 fi.properties["src-expression"])
117
118 # The xtype may be set by the node classes; this is used downstream
119 # to transform to STC-S strings.
120 if "xtype" in fi.properties:
121 res.xtype = fi.properties["xtype"]
122 res.needMunging = True
123
124 # dates and timestamps should be ISO format for TAP or consistency with it
125 if res.type=="date" or res.type=="timestamp":
126 res.xtype = "timestamp"
127
128 # integral types must have a null value set since we can't be
129 # sure that a query yields defined results for all of them.
130 # Tough luck if our artificial value is already taken by the table
131 # (remedy: select a suitable null value in the column metadata)
132 if (res.type in _artificialNULLs
133 and (
134 not (res.values and res.values.nullLiteral)
135 or fi.tainted)):
136 nullLiteral = _artificialNULLs[res.type]
137 if res.values:
138 res.feedObject("values", res.values.change(nullLiteral=nullLiteral))
139 else:
140 res.feedObject("values", base.makeStruct(rscdef.Values,
141 nullLiteral=nullLiteral))
142
143 # unconditionally do away with tableheads inherited from columns
144 # that have annotation indicating they're not plain column references
145 if "src-expression" in fi.properties:
146 res.tablehead = utils.makeEllipsis(
147 fi.properties["src-expression"], 30, "…")
148
149 res.verbLevel = 1
150 res.finishElement()
151 return res
152
153
154 def _getTableDescForOutput(parsedTree):
155 """returns a sequence of Column instances describing the output of the
156 parsed and annotated ADQL query parsedTree.
157 """
158 ctx = TDContext()
159 columns = [_makeColumnFromFieldInfo(ctx, *fi)
160 for fi in parsedTree.fieldInfos.seq]
161
162 # collect local table names to fetch metadata from
163 fromNames = []
164 for t in parsedTree.fromClause.getAllTables():
165 if getattr(t, "wasAliased", False):
166 fromNames.append(t.originalTable.flatten())
167 elif hasattr(t, "qName"):
168 fromNames.append(t.qName)
169
170 forceId = None
171 if parsedTree.createAs:
172 # we are a create table statement, and our table id
173 # must match the user specification to make things work
174 # in _runCreateAs below
175 forceId = parsedTree.createAs.destName.name
176
177 mth = base.caches.getMTH(None)
178 # if this is a simple one-table query, take the metadata and params
179 # from that table.
180 if len(fromNames)==1:
181 try:
182 srcTable = mth.getTableDefForTable(fromNames[0])
183 # swallow groups for now -- we don't really use them for db tables
184 # but if there are some, they'll be trouble when columns are missing.
185 resTable = srcTable.change(columns=columns, groups=[], primary=())
186 resTable.params.extend(srcTable.params)
187 resTable.copyMetaFrom(srcTable)
188 resTable.id = forceId or srcTable.id
189 return resTable
190 except base.NotFoundError:
191 # Single source is not one of our tables, hence no metadata, and
192 # fall through to normal table generation
193 pass
194
195 # collect the params from all input tables; if there are conflicting
196 # names, we pick one at random (which is about as wrong as anything else;
197 # there's just no way to know what the collision means).
198 params = []
199 for tableName in fromNames:
200 try:
201 params.extend(p.copy(parent=None)
202 for p in mth.getTableDefForTable(tableName).params)
203 except Exception:
204 # don't fail just because a funny thing is in fromNames
205 pass
206
207 if hasattr(parsedTree, "suggestAName"):
208 id = parsedTree.suggestAName()
209 else:
210 id = "result"
211
212 resTable = base.makeStruct(
213 rscdef.TableDef,
214 columns=columns,
215 params=params,
216 id=forceId or id)
217
218 return resTable
219
220
221 def _getADQLName(col):
222 """returns the name a column is known as within the ADQL query.
223
224 This can be different from the actual column name for uploaded
225 tables, where we have to rename columns called oid, tableoid,...
226
227 On the SQL side, our internal name is being used.
228 """
229 return getattr(col, "originalName", col.name)
230
231
232 def adqlTableRefToDaCHS(tableName):
233 """returns a DaCHS-internal table name suitable for dc.tablemeta for
234 an ADQL TableName node.
235
236 In particular, in DaCHS we don't support catalog, so that errors
237 out immediately. Also, we don't support delimited table identifiers.
238 Anything delimited not consisting exclusively of lower case letters
239 must therefore fail immediately. When they're all lowercase, people
240 engaged in gratuitous quoting. Then, just unquote and move on.
241 """
242 if isinstance(tableName, str):
243 return tableName
244
245 surfaceForm = adql.flatten(tableName)
246 if tableName.cat:
247 raise base.NotFoundError(surfaceForm, "table", "published tables",
248 hint="DaCHS services have no tables with catalog parts.")
249
250 if isinstance(tableName.schema, utils.QuotedName):
251 if not tableName.schema.isRegularLower():
252 raise base.NotFoundError(surfaceForm, "table", "published tables",
253 hint="You probably should not quote the table schema")
254 schema = tableName.schema.name+"."
255 else:
256 if tableName.schema:
257 schema = tableName.schema+"."
258 else:
259 schema = ""
260
261 if isinstance(tableName.name, utils.QuotedName):
262 if not tableName.name.isRegularLower():
263 raise base.NotFoundError(surfaceForm, "table", "published tables",
264 hint="You probably should not quote the table name")
265 else:
266 name = tableName.name.name
267 else:
268 name = tableName.name
269
270 return schema+name
271
272
273 class DaCHSFieldInfoGetter(adql.FieldInfoGetter):
274 def __init__(self, accessProfile=None, tdsForUploads=[], forUser="anonymous"):
275 adql.FieldInfoGetter.__init__(self)
276 self.forUser = forUser
277 self.mth = base.caches.getMTH(None)
278 for td in tdsForUploads:
279 self.addExtraFieldInfos(
280 td.id,
281 [(_getADQLName(f), makeFieldInfo(f, sqlName=f.name)) for f in td])
282
283 self.physicalNameMap = {}
284
285 def _getUserUploadedTable(self, tableName):
286 try:
287 schema, localName = tableName.split(".")
288 assert schema=="tap_user"
289 with base.getTableConn() as conn:
290 res = list(conn.query("SELECT metadata, physical_name"
291 " FROM tap_user.tables WHERE"
292 " user_name=%(forUser)s AND table_name=%(tableName)s",
293 {"forUser": self.forUser, "tableName": localName}))
294 if not res:
295 raise base.NotFoundError(tableName, "table", "your uploaded tables",
296 hint="Are you authenticated with the right credentials?")
297
298 self.physicalNameMap[tableName] = res[0][1]
299 return base.parseFromString(rscdef.TableDef, res[0][0])
300 except Exception as exc:
301 raise base.ui.logOldExc(base.NotFoundError(tableName, what="table",
302 within="your uploaded tables",
303 hint=f"Something more severe ({exc}) went wrong while loading the"
304 " table metadata. Consider contacting the data centre staff."))
305
306 def getInfosFor(self, tableName):
307 normalised = adqlTableRefToDaCHS(tableName).lower()
308 if normalised.startswith("tap_user."):
309 td = self._getUserUploadedTable(normalised)
310 else:
311 td = self.mth.getTableDefForTable(normalised)
312
313 return td and [
314 (_getADQLName(f), makeFieldInfo(f)) for f in td if not f.hidden]
315
316
317 def _addTableMeta(translated, query, tree, table):
318 """adds various info items from query and its parsed tree to a
319 result table.
320 """
321 # preserve existing INFOs copied from the source table
322 table.makeOriginal("info")
323
324 table.addMeta("info", "ADQL query translated to local SQL (for debugging)",
325 infoName="sql_query", infoValue=translated)
326 table.addMeta("info", "Original ADQL query",
327 infoName="query", infoValue=query)
328
329 mth = base.caches.getMTH(None)
330 sourceTables = tree.getContributingNames()
331
332 # for 1-table queries, we've already copied the entire table metadata.
333 # don't re-copy it. Otherwise tell votablewrite to obtain further
334 # metadata from our contributing tables
335 if len(sourceTables)!=1:
336 metaSources = []
337
338 # Secret handshake with taprunner._makeDataFor; see there.
339 table.tableDef.contributingTables = metaSources
340
341 for tableName in set(tableName for tableName in sourceTables):
342 try:
343 sourceTD = mth.getTableDefForTable(tableName)
344 metaSources.append(sourceTD)
345
346 for m in sourceTD.iterMeta("_associatedDatalinkService"):
347 idColumn = sourceTD.getColumnByName(
348 m.getMeta("idColumn").getContent())
349 # ideally, look for column(s) that were built from idColumn
350 # and are untainted (cave: join using)
351 # for now, let's just fake it:
352 try:
353 destCol = table.tableDef.getColumnByName(idColumn.name)
354 table.addMeta("_associatedDatalinkService", None)
355 table.addMeta("_associatedDatalinkService.idColumn",
356 destCol.name)
357 serviceId = m.getMeta("serviceId").getContent()
358 if "#" not in serviceId:
359 serviceId = "%s#%s"%(sourceTD.rd.sourceId, serviceId)
360 table.addMeta("_associatedDatalinkService.serviceId",
361 serviceId)
362 except base.NotFoundError:
363 # User hasn't selected the column with the id. No problem.
364 pass
365
366 except base.NotFoundError:
367 # that's probably upload tables; we don't parse their
368 # metadata so far anyway. Perhaps we should do so one day.
369 pass
370
371 except base.Error as msg:
372 # don't fail just because of funny metadata or tables not found
373 base.ui.notifyWarning(f"While adding TAP metadata: {msg}")
374
375
376 def _updateMatchLimits(tree, maxrec, hardLimit):
377 """instruments the ADQL tree for the user row set limit maxrec
378 and the system row set limit hard limit.
379
380 maxrec is a match limit from the protocol level, as opposed to the
381 setLimit from the ADQL TOP clause. The rules of interaction between
382 the two are documented inline below (it's messy).
383
384 This returns the overflow set limit. If exactly this many rows
385 are returned from he query, and overflow indicator should be set.
386 """
387 tree.overflowLimit = None
388 # First, fill in system defaults and make sure maxrec doesn't
389 # exceed the caller's or the system's hard limits.
390 if hardLimit is None:
391 hardLimit = base.getConfig("async", "hardMAXREC")
392
393 if maxrec is None:
394 maxrec = base.getConfig("async", "defaultMAXREC")
395
396 maxrec = min(maxrec, hardLimit)
397
398 if tree.query.setLimit is None:
399 # If no set limit has been passed in, put in maxrec and order
400 # overflow indicators starting there.
401 tree.query.setLimit = maxrec
402 return maxrec
403
404 elif maxrec>tree.query.setLimit:
405 # If the set limit passed in is not larger than maxrec, there's
406 # nothing we need to do, because we can never overflow
407 return maxrec
408
409 elif maxrec==tree.query.setLimit:
410 # Special (but probably non-negligible) case: maxrec==set limit
411 # we don't want to trigger an alarm and not touch the set limit either
412 return maxrec+1
413
414 else:
415 # We have both maxrec and TOP, and maxrec<=TOP. Set TOP to maxrec+1
416 # and instruct to report overflows with maxrec+1 rows. Let's hope
417 # no one will mind an extra row here and there.
418 tree.query.setLimit = maxrec+1
419 return maxrec+1
420
421
422 def morphADQL(query, metaProfile=None, tdsForUploads=[],
423 maxrec=None, hardLimit=None, forUser="anonymous"):
424 """returns an postgres query and an (empty) result table for the
425 ADQL in query.
426
427 For an explanation of maxrec and hardLimit, as well as the
428 additional table.tableDef.overflowLimit attribute on the returned table,
429 see _updateMatchLimits above; this will always be an integer.
430 """
431 base.ui.notifyInfo("Incoming ADQL query: %s"%query)
432
433 ctx, t = adql.parseAnnotating(query,
434 DaCHSFieldInfoGetter(metaProfile, tdsForUploads, forUser))
435
436 table = rsc.TableForDef(_getTableDescForOutput(t))
437 table.tableDef.overflowLimit = _updateMatchLimits(t, maxrec, hardLimit)
438 if hardLimit and int(t.setLimit)>hardLimit:
439 table.addMeta("_warning", "This service has a hard row limit"
440 " of %s. Your row limit was decreased to this value."%hardLimit)
441 t.setLimit = str(hardLimit)
442
443 morphStatus, morphedTree = adql.morphPG(t)
444 for warning in morphStatus.warnings:
445 table.addMeta("_warning", warning)
446
447 # escape % to hide them form dbapi replacing
448 translated = adql.flatten(morphedTree).replace("%", "%%")
449
450 _addTableMeta(translated, query, t, table)
451
452 return translated, table
453
454
455 def query(adqlQuery, timeout=15, metaProfile=None, tdsForUploads=[],
456 externalLimit=None, hardLimit=None, forUser="anonymous"):
457 """returns a table for query (a string containing ADQL).
458
459 This is a legacy wrapper for runTAPQuery used by the ADQL web form.
460 Don't use it anywhere else.
461 """
462 with base.getWritableUntrustedConn() as connection:
463 qtable = runTAPQuery(adqlQuery, timeout,
464 connection, tdsForUploads, externalLimit, False, forUser)
465
466 # instantiate the qtable; we want it all in one go
467 resTable = rsc.InMemoryTable(
468 qtable.tableDef,
469 rows=list(qtable))
470
471 qtable.cleanup()
472
473 if len(resTable)==resTable.tableDef.overflowLimit:
474 resTable.addMeta("_warning", "Query result probably incomplete due"
475 " to the match limit kicking in. Queries not providing a TOP"
476 " clause will be furnished with an automatic TOP %s by the machinery,"
477 " so adding a TOP clause with a higher number may help."%
478 base.getConfig("adql", "webDefaultLimit"))
479
480 return resTable
481
482
483 def _runCreateAs(connection, pgQuery, tableTrunk, forUser):
484 """helps runTAPQuery in case of a CREATE TABLE AS.
485
486 tableTrunk, in that case, has the name of whatever table pgQuery
487 selects into. Since this is run unprivleged, that table more or
488 less has to be in tap_user (and it's all that our grammar lets through
489 at the moment, which is probably still a good idea.
490 """
491 connection.execute(pgQuery)
492 # see above in _getTableDescForOutput on where this comes from
493 destName = tableTrunk.tableDef.id
494 metadata = base.structToXML(tableTrunk.tableDef
495 ).replace("<table>", f'<table id="{destName}">')
496
497 # TODO: Build a clean TableDef with columns from the output table def
498 # we are trying to serialise here, dropping crazy outputField
499 # attributes that we don't want here anyway. Until then,
500 # I'll do an ugly hack:
501 metadata = re.sub('select="[^"]*"', '',
502 metadata.replace("<outputField ", "<column "
503 ).replace("</outputField>", "</column>"))
504
505 connection.execute("update tap_user.tables"
506 " set metadata=%(metadata)s"
507 " where user_name=%(forUser)s and table_name=%(destName)s",
508 locals())
509 connection.commit()
510 return tableTrunk
511
512
513 def runTAPQuery(query, timeout, connection, tdsForUploads, maxrec,
514 autoClose=True, forUser="anonymous"):
515 """executes a TAP query and returns the result in a data instance.
516 """
517 # ugly convenience hack: because people these days regularly paste
518 # in 0xa0 for blanks and this kind of thing is almost impossible to spot,
519 # I just map them to blanks for now
520 query = query.replace("\xa0", " ")
521
522 postgresParams = [
523 # cursor tuple fraction only kicks in if we're actually using
524 # cursors (which for psycopg2 only happens with named cursors).
525 # Either way, we're going to eat all tuples, so tell that to
526 # postgres.
527 ("cursor_tuple_fraction", 1),
528 ("statement_timeout", "%s ms"%int(timeout*1000))]
529
530 try:
531 pgQuery, tableTrunk = morphADQL(query,
532 tdsForUploads=tdsForUploads, maxrec=maxrec, forUser=forUser)
533 base.ui.notifyInfo("Sending to postgres: %s"%repr(pgQuery))
534
535 # the following ugly hack works around a horrible planner
536 # failure with q3c; we don't want to mess with the planner
537 # unless we think that's necessary. And otherwise wait
538 # to migrate to pgsphere that hopefully doesn't confuse
539 # the planner as much.
540 if base.getConfig("db", "q3cplannerhack") and "q3c_" in pgQuery:
541 postgresParams.append(
542 ('enable_seqscan', 'no'))
543
544 resetTo = connection.configure(postgresParams)
545
546 # The postgres morpher can produce select into-s that will create
547 # persistent user tables and work rather differently in other
548 # respects, too (redirecting if successful). handle this
549 # in an extra function.
550 if pgQuery.startswith("CREATE TABLE"):
551 return _runCreateAs(connection, pgQuery, tableTrunk, forUser)
552
553 else:
554 result = rsc.QueryTable(tableTrunk.tableDef, pgQuery, connection,
555 autoClose=autoClose)
556 result.meta_ = tableTrunk.meta_
557
558 result.configureOnClose(resetTo)
559
560 except:
561 mapADQLErrors(*sys.exc_info())
562
563 return result
564
565
566 def mapADQLErrors(excType, excValue, excTb):
567 if (isinstance(excValue, adql.ParseException)
568 or isinstance(excValue, adql.ParseSyntaxException)):
569 raise base.ui.logOldExc(
570 base.ValidationError("Could not parse your query: %s"%
571 str(excValue), "query"))
572 elif isinstance(excValue, adql.ColumnNotFound):
573 raise base.ui.logOldExc(base.ValidationError("No such field known: %s"%
574 str(excValue), "query"))
575 elif isinstance(excValue, adql.AmbiguousColumn):
576 raise base.ui.logOldExc(base.ValidationError("%s needs to be qualified."%
577 str(excValue), "query"))
578 elif isinstance(excValue, adql.Error):
579 raise base.ui.logOldExc(base.ValidationError(str(excValue), "query"))
580 else:
581 svcs.mapDBErrors(excType, excValue, excTb)
582
583
584 class ADQLCore(svcs.Core, base.RestrictionMixin):
585 """A core taking an ADQL query from its query argument and returning the
586 result of that query in a standard table.
587
588 Since the columns returned depend on the query, the outputTable of an
589 ADQL core must not be defined.
590 """
591 name_ = "adqlCore"
592
593 def wantsTableWidget(self):
594 return True
595
596 def run(self, service, inputTable, queryMeta):
597 inRow = inputTable.getParamDict()
598 queryString = inRow["query"]
599 try:
600 res = query(queryString,
601 timeout=queryMeta["timeout"], hardLimit=100000,
602 externalLimit=queryMeta["dbLimit"])
603 # Warning: We're returning the db connection to the connection
604 # pool here while we still have a named cursor on it. This is
605 # risky because someone might futz with our connection later.
606 # However, postponing the return of the connection isn't nice
607 # either because then the renderer would have to manage the core's
608 # connections, which is ugly, too.
609 # I'm a bit at a loss for a good solution here. Let's see how
610 # well the "don't care" scheme works out. Maybe we need a "renderer closes
611 # connection" plan for this kind of streaming?
612 res.noPostprocess = True
613 queryMeta["Matched"] = len(res.rows)
614 return res
615 except:
616 mapADQLErrors(*sys.exc_info())
617
618
619 ################ region makers
620 # REGION was supposed to be a general extension mechanism but will now
621 # probably wither away. Let's keep things here while it does that.
622 import re
623
624 def _getRegionId(regionSpec, pat=re.compile("[A-Za-z_]+")):
625 mat = pat.match(regionSpec)
626 if mat:
627 return mat.group()
628
629
630 ################### local query interface #########################
631
632 def localquery():
633 """run the argument as an ADQL query.
634 """
635 from gavo import rscdesc #noflake: cache registration
636 from gavo import formats
637
638 q = sys.argv[1]
639 table = query(q, timeout=1000)
640 formats.formatData("votable", table, sys.stdout.buffer)