Debian Codegraph @

gavo/svcs/standardcores.py

raw
1 """
2 Some standard cores for services.
3
4 A core receives and "input table" (usually just containing the query
5 parameters in the doc rec) and returns an output thing, usually a table
6 (but see the src package docstring).
7 """
8
9 #c Copyright 2008-2025, the GAVO project <[email protected]>
10 #c
11 #c This program is free software, covered by the GNU GPL. See the
12 #c COPYING file in the source distribution.
13
14
15 import sys
16
17 from gavo import base
18 from gavo import rsc
19 from gavo import rscdef
20 from gavo.base import sqlsupport
21 from gavo.svcs import core
22 from gavo.svcs import inputdef
23 from gavo.svcs import outputdef
24
25
26 class Error(base.Error):
27 pass
28
29
30 MS = base.makeStruct
31
32
33 class PhraseMaker(rscdef.ProcApp):
34 """A procedure application for generating SQL expressions from input keys.
35
36 PhraseMaker code must *yield* SQL fragments that can occur in WHERE
37 clauses, i.e., boolean expressions (thus, they must be generator
38 bodies). The clauses yielded by a single condDesc are combined
39 with the joiner set in the containing CondDesc (default=OR).
40
41 The following names are available to them:
42
43 * inputKeys -- the list of input keys for the parent CondDesc
44 * inPars -- a dictionary mapping inputKey names to the values
45 provided by the user
46 * outPars -- a dictionary that is later used as the parameter
47 dictionary to the query.
48 * core -- the core to which this phrase maker's condDesc belongs
49
50 To get the standard SQL a single key would generate, say::
51
52 yield base.getSQLForField(inputKeys[0], inPars, outPars)
53
54 To insert some value into outPars, do not simply use some key into
55 outParse, since, e.g., the condDesc might be used multiple times.
56 Instead, use getSQLKey, maybe like this::
57
58 ik = inputKeys[0]
59 yield "%s BETWEEN %%(%s)s AND %%(%s)s"%(ik.name,
60 base.getSQLKey(ik.name, inPars[ik.name]-10, outPars),
61 base.getSQLKey(ik.name, inPars[ik.name]+10, outPars))
62
63 getSQLKey will make sure unique names in outPars are chosen and
64 enters the values there.
65 """
66 name_ = "phraseMaker"
67
68 requiredType = "phraseMaker"
69 formalArgs = "self, inputKeys, inPars, outPars, core"
70
71
72 class CondDesc(base.Structure):
73 """A query specification for cores talking to the database.
74
75 CondDescs define inputs as a sequence of InputKeys (see `Element InputKey`_).
76 Internally, the values in the InputKeys can be translated to SQL.
77 """
78 name_ = "condDesc"
79
80 _inputKeys = rscdef.ColumnListAttribute("inputKeys",
81 childFactory=inputdef.InputKey,
82 description="One or more InputKeys defining the condition's input.",
83 copyable=True)
84
85 _silent = base.BooleanAttribute("silent",
86 default=False,
87 description="Do not produce SQL from this CondDesc. This"
88 " can be used to convey meta information to the core. However,"
89 " in general, a service is a more appropriate place to deal with"
90 " such information, and thus you should prefer service InputKeys"
91 " to silent CondDescs.",
92 copyable=True)
93
94 _required = base.BooleanAttribute("required",
95 default=False,
96 description="Reject queries not filling the InputKeys of this CondDesc",
97 copyable=True)
98
99 _inputOptional = base.BooleanAttribute("inputOptional",
100 default=False,
101 description="Call the phrase maker even if no input to our input keys"
102 " is there (useful to provide built-in defaults).",
103 copyable=True)
104
105 _fixedSQL = base.UnicodeAttribute("fixedSQL",
106 default=None,
107 description="Always insert this SQL statement into the query. Deprecated.",
108 copyable=True)
109
110 _buildFrom = base.ReferenceAttribute("buildFrom",
111 description="A reference to a column or an InputKey to define"
112 " this CondDesc",
113 default=None)
114
115 _phraseMaker = base.StructAttribute("phraseMaker",
116 default=None,
117 description="Code to generate custom SQL from the input keys",
118 childFactory=PhraseMaker,
119 copyable=True)
120
121 _combining = base.BooleanAttribute("combining",
122 default=False,
123 description="Allow some input keys to be missing when others are given?"
124 " (you want this for pseudo-condDescs just collecting random input"
125 " keys)", # (and I wish I had a better idea)
126 copyable="True")
127
128 _group = base.StructAttribute("group",
129 default=None,
130 childFactory=rscdef.Group,
131 description="Group child input keys in the input table (primarily"
132 " interesting for web forms, where this grouping is shown graphically;"
133 " Set the style property to compact to have a one-line group there)")
134
135 _joiner = base.UnicodeAttribute("joiner",
136 default="OR",
137 description="When yielding multiple fragments, join them"
138 " using this operator (probably the only thing besides OR is"
139 " AND).",
140 copyable=True)
141
142 _original = base.OriginalAttribute()
143
144 def __init__(self, parent, **kwargs):
145 base.Structure.__init__(self, parent, **kwargs)
146 # copy parent's resolveName if present for buildFrom resolution
147 if hasattr(self.parent, "resolveName"):
148 self.resolveName = self.parent.resolveName
149
150 def __repr__(self):
151 return "<CondDesc %s>"%",".join(ik.name for ik in self.inputKeys)
152
153 @classmethod
154 def fromInputKey(cls, ik, **kwargs):
155 return base.makeStruct(CondDesc, inputKeys=[ik], **kwargs)
156
157 @classmethod
158 def fromColumn(cls, col, **kwargs):
159 return base.makeStruct(cls, buildFrom=col, **kwargs)
160
161 @property
162 def name(self):
163 """returns some key for uniqueness of condDescs.
164 """
165 # This is necessary for ColumnLists that are used
166 # for CondDescs as well. Ideally, we'd do this on an
167 # InputKeys basis and yield their names (because that's what
168 # formal counts on), but it's probably not worth the effort.
169 return "+".join([f.name for f in self.inputKeys])
170
171 def completeElement(self, ctx):
172 if self.buildFrom and not self.inputKeys:
173 # use the column as input key; special renderers may want
174 # to do type mapping, but the default is to have plain input
175 self.inputKeys = [inputdef.InputKey.fromColumn(self.buildFrom)]
176 super().completeElement(ctx)
177
178 def expand(self, *args, **kwargs):
179 """hands macro expansion requests (from phraseMakers) upwards.
180
181 This is to the queried table if the parent has one (i.e., we're
182 part of a core), or to the RD if not (i.e., we're defined within
183 an rd).
184 """
185 if hasattr(self.parent, "queriedTable"):
186 return self.parent.queriedTable.expand(*args, **kwargs)
187 else:
188 if self.parent:
189 return self.parent.rd.expand(*args, **kwargs)
190 else:
191 # we're most likely testing, so don't bother
192 return args[0]
193
194 def _makePhraseDefault(self, ignored, inputKeys, inPars, outPars, core):
195 # the default phrase maker uses whatever the individual input keys
196 # come up with.
197 for ik in self.inputKeys:
198 yield base.getSQLForField(ik, inPars, outPars)
199
200 # We only want to compile the phraseMaker if actually necessary.
201 # condDescs may be defined within resource descriptors (e.g., in
202 # scs.rd), and they can't be compiled there (since macros may
203 # be missing); thus, we dispatch on the first call.
204 def _getPhraseMaker(self):
205 try:
206 return self.__compiledPhraseMaker
207 except AttributeError:
208 if self.phraseMaker is not None:
209 val = self.phraseMaker.compile()
210 else:
211 val = self._makePhraseDefault
212 self.__compiledPhraseMaker = val
213 return self.__compiledPhraseMaker
214 makePhrase = property(_getPhraseMaker)
215
216 def _isActive(self, inPars):
217 """returns True if the dict inPars contains input to all our input keys.
218
219 This is different from whether there is input to these keys; keys with
220 no input are in inParse with a value of None. That means that
221 if _isActive is false, the core for some reason hasn't included
222 our input keys and hence we shouldn't run.
223 """
224 for f in self.inputKeys:
225 if f.name not in inPars:
226 return False
227 return True
228
229 def inputReceived(self, inPars, queryMeta):
230 """returns True if all inputKeys can be filled from inPars.
231
232 As a side effect, inPars will receive defaults form the input keys
233 if there are any.
234 """
235 if not self._isActive(inPars):
236 return False
237 if self.inputOptional:
238 return True
239 keysFound, keysMissing = [], []
240 for f in self.inputKeys:
241 if inPars.get(f.name) is None:
242 keysMissing.append(f)
243 else:
244 if f.value!=inPars.get(f.name): # non-defaulted
245 keysFound.append(f)
246 if not keysMissing:
247 return True
248
249 # keys are missing. That's ok if none were found and we're not required
250 if not self.required and not keysFound:
251 return False
252 if self.required:
253 raise base.ValidationError("is mandatory but was not provided.",
254 colName=keysMissing[0].name)
255
256 # we're optional, but a value was given and others are missing
257 if not self.combining:
258 raise base.ValidationError("When you give a value for %s,"
259 " you must give value(s) for %s, too"%(keysFound[0].getLabel(),
260 ", ".join(k.name for k in keysMissing)),
261 colName=keysMissing[0].name)
262 return True
263
264 def asSQL(self, inPars, sqlPars, queryMeta):
265 if self.silent or not self.inputReceived(inPars, queryMeta):
266 return ""
267 res = list(self.makePhrase(
268 self, self.inputKeys, inPars, sqlPars, self.parent))
269 sql = base.joinOperatorExpr(self.joiner, res)
270 if self.fixedSQL:
271 sql = base.joinOperatorExpr(self.joiner, [sql, self.fixedSQL])
272 return sql
273
274 def adaptForRenderer(self, renderer):
275 """returns a changed version of self if renderer suggests such a
276 change.
277
278 This only happens if buildFrom is non-None. The method must
279 return a "defused" version that has buildFrom None (or self,
280 which will do because core.adaptForRenderer stops adapting if
281 the condDescs are stable).
282
283 The adaptors may also raise a Replace exception and return a
284 full CondDesc; this is done, e.g., for spoints for the form
285 renderer, since they need two input keys and a completely modified
286 phrase.
287 """
288 if not self.buildFrom:
289 return self
290 adaptor = inputdef.getRendererAdaptor(renderer)
291 if adaptor is None:
292 return self
293
294 try:
295 newInputKeys = []
296 for ik in self.inputKeys:
297 newInputKeys.append(adaptor(ik))
298 if self.inputKeys==newInputKeys:
299 return self
300 else:
301 return self.change(inputKeys=newInputKeys, buildFrom=None)
302 except base.Replace as ex:
303 return ex.newOb
304
305
306 def mapDBErrors(excType, excValue, excTb):
307 """translates exception into something we can display properly.
308 """
309 # This is a helper to all DB-based cores -- it probably should go
310 # into TableBasedCore.
311 if getattr(excValue, "cursor", None) is not None:
312 base.ui.notifyWarning("Failed DB query: %s"%excValue.cursor.query)
313 if isinstance(excValue, sqlsupport.QueryCanceledError):
314 message = "Query timed out (took too long).\n"
315 if base.getConfig("maintainerAddress"):
316 message = message+("Unless you know why the query took that"
317 " long, please contact %s. Otherwise, use TAP's async mode.\n"%
318 base.getConfig("maintainerAddress"))
319 message += ("Meanwhile, if this failure happened with a cross match,"
320 " please try exchanging the large and the small catalog in POINT"
321 " and CIRCLE.\n")
322 raise base.ui.logOldExc(base.ValidationError(message, "query"))
323 elif isinstance(excValue, base.NotFoundError):
324 raise base.ui.logOldExc(base.ValidationError("Could not locate %s '%s'"%(
325 excValue.what, excValue.lookedFor), "query"))
326 elif isinstance(excValue, base.DBError):
327 raise base.ui.logOldExc(base.ValidationError(str(excValue), "query"))
328 else:
329 raise
330
331
332 class TableBasedCore(core.Core):
333 """A core knowing a DB table it operates on and allowing the definition
334 of condDescs.
335 """
336 _queriedTable = base.ReferenceAttribute("queriedTable",
337 default=base.Undefined, description="A reference to the table"
338 " this core queries.", copyable=True, callbacks=["_fixNamePath"])
339 _condDescs = base.StructListAttribute("condDescs", childFactory=CondDesc,
340 description="Descriptions of the SQL and input generating entities"
341 " for this core; if not given, they will be generated from the"
342 " table columns.", copyable=True)
343 _namePath = rscdef.NamePathAttribute(description="Id of an element"
344 " that will be used to located names in id references. Defaults"
345 " to the queriedTable's id.")
346
347 def _buildInputTableFromCondDescs(self):
348 groups, iks = [], []
349 for cd in self.condDescs:
350 for ik in cd.inputKeys:
351 iks.append(ik)
352 if cd.group:
353 groups.append(cd.group.change(
354 paramRefs=[MS(rscdef.ParameterReference, dest=ik.name)
355 for ik in cd.inputKeys],
356 parent_=None))
357 self.inputTable = MS(inputdef.InputTD,
358 inputKeys=iks,
359 groups=groups)
360
361 def completeElement(self, ctx):
362 # if no condDescs have been given, make them up from the table columns.
363 if not self.condDescs and self.queriedTable:
364 self.condDescs = [self.adopt(CondDesc.fromColumn(c))
365 for c in self.queriedTable]
366
367 # if an inputTable is given, trust it fits the condDescs, else
368 # build the input table
369 if self.inputTable is base.NotGiven:
370 self._buildInputTableFromCondDescs()
371
372 # if no outputTable has been given, make it up from the columns
373 # of the queried table unless a prototype is defined (which is
374 # handled by core itself).
375 if (self.outputTableXML is None
376 and self.outputTable is base.NotGiven
377 and self.queriedTable):
378 self.outputTable = outputdef.OutputTableDef.fromTableDef(
379 self.queriedTable, ctx)
380
381 super().completeElement(ctx)
382
383 def _fixNamePath(self, qTable):
384 # callback from queriedTable to make it the default for namePath as well
385 if self.namePath is None:
386 self.namePath = qTable.getFullId()
387
388 def _getSQLWhere(self, inputTable, queryMeta):
389 """returns a where fragment and the appropriate parameters
390 for the query defined by inputTable and queryMeta.
391 """
392 sqlPars = {}
393 return base.joinOperatorExpr("AND",
394 [cd.asSQL(inputTable.args, sqlPars, queryMeta)
395 for cd in self.condDescs]), sqlPars
396
397 def _addQueryStatus(self, resultTable, queryMeta):
398 """furnishes resultTable with a DALI-compatible _queryStatus meta item.
399
400 This will also add a _warning meta in case of overflows.
401 """
402 isOverflowed = len(resultTable.rows)>queryMeta.get("dbLimit", 1e10)
403 if isOverflowed:
404 del resultTable.rows[-1]
405 queryMeta["Matched"] = len(resultTable.rows)
406 if isOverflowed:
407 resultTable.addMeta("_warning",
408 "The query limit was reached. Increase it"
409 " to retrieve more matches. Note that unsorted truncated queries"
410 " are not reproducible (i.e., might return a different result set"
411 " at a later time).")
412 resultTable.setMeta("_queryStatus", "OVERFLOW")
413 else:
414 resultTable.setMeta("_queryStatus", "OK")
415
416 def adaptForRenderer(self, renderer, queryMeta):
417 """returns a core tailored to renderer renderers.
418
419 This mainly means asking the condDescs to build themselves for
420 a certain renderer. If no polymorphuous condDescs are there,
421 self is returned.
422 """
423 newCondDescs = []
424 for cd in self.condDescs:
425 newCondDescs.append(cd.adaptForRenderer(renderer))
426 if newCondDescs!=self.condDescs:
427 return self.change(condDescs=newCondDescs, inputTable=base.NotGiven
428 ).adaptForRenderer(renderer, queryMeta)
429 else:
430 return core.Core.adaptForRenderer(self, renderer, queryMeta)
431
432 def getRelevantTables(self):
433 return [self.queriedTable]
434
435
436 class FancyQueryCore(TableBasedCore, base.RestrictionMixin):
437 """A core executing a pre-specified query with fancy conditions.
438
439 Unless you select \\*, you *must* define the outputTable here;
440 Weird things will happen if you don't.
441
442 The queriedTable attribute is mandatory but only used for name resolution
443 (e.g., in outputTable). Instead, define your FROM in the query attribute
444 (and use a %s where the condDescs-generated WHERE clause should end up)
445 """
446 name_ = "fancyQueryCore"
447
448 _query = base.UnicodeAttribute("query", description="The query to"
449 " execute. It must contain exactly one %s where the generated"
450 " where clause is to be inserted. Do not write WHERE yourself."
451 " All other percents must be escaped by doubling them. This"
452 " string is macro-expanded in the core's service.",
453 default=base.Undefined,
454 copyable=True)
455 _timeout = base.FloatAttribute("timeout", default=5.,
456 description="Seconds until the query is aborted",
457 copyable=True)
458
459 def run(self, service, inputTable, queryMeta):
460 fragment, pars = self._getSQLWhere(inputTable, queryMeta)
461 with base.getTableConn() as conn:
462 if fragment:
463 fragment = " WHERE "+fragment
464 else:
465 fragment = ""
466 try:
467 res = rsc.TableForDef(
468 self.outputTable,
469 rows=list(conn.queryToDicts(
470 service.expand(self.query%fragment),
471 pars,
472 timeout=self.timeout,
473 caseFixer=self.outputTable.caseFixer)))
474 except:
475 mapDBErrors(*sys.exc_info())
476
477 self._addQueryStatus(res, queryMeta)
478 return res
479
480
481 class DBCore(TableBasedCore):
482 """A core performing database queries on one table or view.
483
484 DBCores ask the service for the desired output schema and adapt their
485 output. The DBCore's output table, on the other hand, lists all fields
486 available from the queried table.
487 """
488 name_ = "dbCore"
489
490 _sortKey = base.UnicodeAttribute("sortKey",
491 description="A pre-defined sort order (suppresses DB options widget)."
492 " The sort key accepts multiple columns, separated by commas.",
493 copyable=True)
494 _limit = base.IntAttribute("limit", description="A pre-defined"
495 " match limit (suppresses DB options widget).", copyable=True)
496 _distinct = base.BooleanAttribute("distinct", description="Add a"
497 " 'distinct' modifier to the query?", default=False, copyable=True)
498 _groupBy = base.UnicodeAttribute("groupBy", description=
499 "A group by clause. You shouldn't generally need this, and if"
500 " you use it, you must give an outputTable to your core.",
501 default=None)
502
503 def wantsTableWidget(self):
504 return self.sortKey is None and self.limit is None
505
506 def getQueryCols(self, service, queryMeta):
507 """returns the fields we need in the output table.
508
509 The normal DbBased core just returns whatever the service wants.
510 Derived cores, e.g., for special protocols, could override this
511 to make sure they have some fields in the result they depend on.
512 """
513 return service.getCurOutputFields(queryMeta)
514
515 def _runQuery(self, resultTableDef, fragment, pars, queryMeta,
516 **kwargs):
517 with base.getTableConn() as conn:
518 with conn.parameters([
519 ("statement_timeout", "%sms"%(int(1000*queryMeta["timeout"])))]):
520 queriedTable = rsc.TableForDef(self.queriedTable, nometa=True,
521 create=False, connection=conn)
522
523 if fragment and pars:
524 resultTableDef.addMeta("info", repr(pars),
525 infoName="queryPars", infoValue=fragment)
526
527 iqArgs = {"limits": queryMeta.asSQL(), "distinct": self.distinct,
528 "groupBy": self.groupBy}
529 iqArgs.update(kwargs)
530
531 try:
532 res = queriedTable.getTableForQuery(
533 resultTableDef, fragment, pars, **iqArgs)
534 except:
535 mapDBErrors(*sys.exc_info())
536
537 self._addQueryStatus(res, queryMeta)
538 return res
539
540 def _makeResultTableDef(self, service, inputTable, queryMeta):
541 """returns an OutputTableDef object for querying our table with queryMeta.
542 """
543 resTD = base.makeStruct(outputdef.OutputTableDef,
544 id="result",
545 onDisk=False,
546 parent_=self.queriedTable.parent,
547 columns=self.getQueryCols(service, queryMeta),
548 params=self.queriedTable.params)
549 return resTD
550
551 def run(self, service, inputTable, queryMeta):
552 """does the DB query and returns an InMemoryTable containing
553 the result.
554 """
555 resultTableDef = self._makeResultTableDef(
556 service, inputTable, queryMeta)
557
558 resultTableDef.copyMetaFrom(self.queriedTable)
559 if not resultTableDef.columns:
560 raise base.ValidationError("No output columns with these settings."
561 "_OUTPUT")
562
563 sortKeys = None
564 if self.sortKey:
565 sortKeys = self.sortKey.split(",")
566
567 queryMeta.overrideDbOptions(limit=self.limit, sortKeys=sortKeys,
568 sortFallback=self.getProperty("defaultSortKey", None))
569 try:
570 fragment, pars = self._getSQLWhere(inputTable, queryMeta)
571 except base.LiteralParseError as ex:
572 raise base.ui.logOldExc(base.ValidationError(str(ex),
573 colName=ex.attName))
574 queryMeta["sqlQueryPars"] = pars
575 return self._runQuery(resultTableDef, fragment, pars, queryMeta)
576
577
578 class FixedQueryCore(core.Core, base.RestrictionMixin):
579 """A core executing a predefined query.
580
581 This usually is not what you want, unless you want to expose the current
582 results of a specific query, e.g., for log or event data.
583 """
584 name_ = "fixedQueryCore"
585
586 _timeout = base.FloatAttribute("timeout", default=15.,
587 description="Seconds until the query is aborted", copyable=True)
588 _query = base.UnicodeAttribute("query", default=base.Undefined,
589 description="The query to be executed. You must define the"
590 " output fields in the core's output table. The query will"
591 " be macro-expanded in the resource descriptor.")
592 _writable = base.BooleanAttribute("writable", default=False,
593 description="Use a writable DB connection?")
594
595 def completeElement(self, ctx):
596 if self.inputTable is base.NotGiven:
597 self.inputTable = base.makeStruct(inputdef.InputTD)
598 super().completeElement(ctx)
599
600 def run(self, service, inputTable, queryMeta):
601 if self.writable:
602 connFactory = base.getWritableTableConn
603 else:
604 connFactory = base.getTableConn
605
606 with connFactory() as conn:
607 try:
608 rows = list(conn.queryToDicts(
609 self.rd.expand(self.query), timeout=self.timeout,
610 caseFixer=self.outputTable.caseFixer))
611 res = rsc.TableForDef(self.outputTable, rows=rows)
612 except TypeError:
613 # This, we guess, is just someone executing a non-selecting
614 # query (rows = list(None))
615 res = rsc.TableForDef(self.outputTable, rows=[])
616 except:
617 mapDBErrors(*sys.exc_info())
618 queryMeta["Matched"] = len(res.rows)
619 return res
620
621
622 class NullCore(core.Core):
623 """A core always returning None.
624
625 This core will not work with the common renderers. It is really
626 intended to go with coreless services (i.e. those in which the
627 renderer computes everything itself and never calls service.runX).
628 As an example, the external renderer could go with this.
629 """
630
631 name_ = "nullCore"
632
633 inputTableXML = "<inputTable/>"
634 outputTableXML = "<outputTable/>"
635
636 def run(self, service, inputTable, queryMeta):
637 return None