Debian Codegraph @

gavo/rscdef/rmkdef.py

raw
1 """
2 Definition of rowmakers.
3
4 rowmakers are objects that take a dictionary of some kind and emit
5 a row suitable for inclusion into a table.
6 """
7
8 #c Copyright 2008-2025, the GAVO project <[email protected]>
9 #c
10 #c This program is free software, covered by the GNU GPL. See the
11 #c COPYING file in the source distribution.
12
13
14 import bisect
15 import fnmatch
16 import re
17 import sys
18 import traceback
19
20 from gavo import base
21 from gavo import utils
22 from gavo.rscdef import common
23 from gavo.rscdef import column
24 from gavo.rscdef import procdef
25 from gavo.rscdef import rmkfuncs
26 from gavo.rscdef import rowtriggers
27
28
29 __docformat__ = "restructuredtext en"
30
31
32 class Error(base.Error):
33 pass
34
35
36 class MappedExpression(base.Structure):
37 """a base class for map and var.
38
39 You must give a destDict class attribute to make these work.
40 """
41
42 destDict = None
43 restrictedMode = False
44
45 _dest = column.ColumnNameAttribute("key",
46 default=base.Undefined,
47 description="Name of the column the value is to end up in.",
48 copyable=True,
49 strip=True,
50 aliases=["dest", "name"])
51
52 _src = base.UnicodeAttribute("source",
53 default=None,
54 description="Source key name to convert to column value (either a grammar"
55 " key or a var).",
56 copyable=True,
57 strip=True,
58 aliases=["src"])
59
60 _nullExcs = base.UnicodeAttribute("nullExcs",
61 default=base.NotGiven,
62 description="Exceptions that should be caught and"
63 " cause the value to be NULL, separated by commas.")
64
65 _expr = base.DataContent(
66 description="A python expression giving the value for key.",
67 copyable=True,
68 strip=True)
69
70 _nullExpr = base.UnicodeAttribute("nullExpr",
71 default=base.NotGiven,
72 description="A python expression for a value that is mapped to"
73 " NULL (None). Equality is checked after building the value, so"
74 " this expression has to be of the column type. Use map with"
75 " the parseWithNull function to catch null values before type"
76 " conversion.")
77
78 def completeElement(self, ctx):
79 self.restrictedMode = getattr(ctx, "restricted", False)
80 if self.restrictedMode and (
81 self.content_
82 or self.nullExpr
83 or self.nullValue):
84 raise base.RestrictedElement("map", hint="In restricted mode, only"
85 " maps with a source attribute are allowed; nullExpr or nullValue"
86 " are out, too, since they can be used to inject raw code.")
87 if not self.content_ and not self.source:
88 self.source = self.key
89 if self.content_ and "\\" in self.content_:
90 self.content_ = self.parent.expand(self.content_)
91
92 def validate(self):
93 """checks that code content is a parseable python expression and that
94 the destination exists in the tableDef
95 """
96 super().validate()
97
98 if (self.content_ and self.source) or not (self.content_ or self.source):
99 raise base.StructureError("Map must have exactly one of source attribute"
100 " or element content")
101
102 if self.nullExpr is not base.NotGiven:
103 utils.ensureExpression(self.nullExpr)
104
105 if self.content_:
106 utils.ensureExpression(common.replaceProcDefAt(self.content_), self.name_)
107
108 if self.nullExcs is not base.NotGiven:
109 utils.ensureExpression(self.nullExcs, "%s.nullExcs"%(self.name_))
110
111 def getAutoMapper(self):
112 """returns an expression literal for turning what is self.source to a
113 value suitable for self.key.
114
115 This must be defined for concrete classes derived from this.
116 """
117 raise NotImplementedError("No automatic mappers defined here")
118
119 def getCode(self, columns):
120 """returns python source code for this map.
121 """
122 code = []
123
124 if isinstance(self.key, utils.QuotedName):
125 destIndex = '"%s"'%(self.key.name.replace('"', '\\"'))
126 else:
127 destIndex = '"%s"'%self.key
128
129 if self.content_:
130 code.append('%s[%s] = %s'%(self.destDict, destIndex, self.content_))
131 else:
132 code.append('%s[%s] = %s'%(self.destDict,
133 destIndex,
134 self.getAutoMapper(columns)))
135
136 if self.nullExpr is not base.NotGiven:
137 code.append('\nif %s[%s]==%s: %s[%s] = None'%(
138 self.destDict,
139 destIndex,
140 self.nullExpr,
141 self.destDict,
142 destIndex))
143 code = "".join(code)
144
145 if self.nullExcs is not base.NotGiven:
146 code = 'try:\n%s\nexcept (%s): %s[%s] = None'%(
147 re.sub("(?m)^", " ", code),
148 self.nullExcs,
149 self.destDict,
150 destIndex)
151 return code
152
153
154 class MapRule(MappedExpression):
155 """A mapping rule.
156
157 To specify the source of a mapping, you can either
158
159 - grab a value from what's emitted by the grammar or defined using var via
160 the source attribute. The value given for source is converted to a
161 python value and stored.
162 - or give a python expression in the body. In that case, no further
163 type conversion will be attempted.
164
165 If neither source or a body is given, map uses the key attribute as its
166 source attribute.
167
168 The map rule generates a key/value pair in the result record.
169 """
170 name_ = "map"
171 destDict = "result"
172
173 def getAutoMapper(self, columns):
174 """returns an expression to automatically map self.source to
175 a column in the destination table.
176 """
177 colDef = columns.getColumnByName(self.key)
178 try:
179 return base.sqltypeToPythonCode(colDef.type)%(
180 'vars["{}"]'.format(
181 self.source.replace("\\", r"\\").replace('"', '\\"')))
182 except base.ConversionError:
183 raise base.ui.logOldExc(base.LiteralParseError("map", colDef.type,
184 hint="Auto-mapping to %s is impossible since"
185 " no default map for %s is known"%(self.key, colDef.type)))
186
187
188 class VarDef(MappedExpression):
189 """A definition of a rowmaker variable.
190
191 It consists of a name and a python expression, including function
192 calls. The variables are entered into the input row coming from
193 the grammar.
194
195 var elements are evaluated before apply elements, in the sequence
196 they are in the RD. You can refer to keys defined by vars already
197 evaluated in the usual @key manner.
198 """
199 name_ = "var"
200 destDict = "vars"
201
202 def getAutoMapper(self, columns):
203 """returns var[self.source].
204
205 Having source with var doesn't make a lot of sense, but it's
206 a nifty way to introduce None-s for missing keys if one wants.
207 And it should do *something*.
208 """
209 return 'vars["{}"]'.format(
210 self.source.replace("\\", r"\\").replace('"', '\\"'))
211
212
213 class ApplyDef(procdef.ProcApp):
214 """A code fragment to manipulate the result row (and possibly more).
215
216 Apply elements allow embedding python code in rowmakers.
217
218 The current input fields from the grammar (including the rowmaker's vars)
219 are available in the vars dictionary and can be changed there. You can
220 also add new keys.
221
222 You can add new keys for shipping out in the result dictionary.
223
224 The active rowmaker is available as parent. It is also used to
225 expand macros.
226
227 The table that the rowmaker feeds to can be accessed as targetTable.
228 You probably only want to change meta information here (e.g., warnings
229 or infos).
230
231 As always in procApps, you can get the embedding RD as rd; this is
232 useful to, e.g., resolve references using rd.getByRD, and specify
233 resdir-relative file names using rd.getAbsPath.
234 """
235 name_ = "apply"
236 requiredType = "apply"
237 formalArgs = "vars, result, targetTable, _self"
238
239 def getFuncCode(self):
240 return common.replaceProcDefAt(procdef.ProcApp.getFuncCode(self))
241
242
243 class RowmakerMacroMixin(base.StandardMacroMixin):
244 """A collection of macros available to rowmakers.
245
246 NOTE: All macros should return only one single physical python line,
247 or they will mess up the calculation of what constructs caused errors.
248 """
249 def macro_standardPubDID(self):
250 r"""returns the "standard publisher DID" for the current product.
251
252 The publisher dataset identifier (PubDID) is important in protocols like
253 SSAP and obscore. If you use this macro, the PubDID will be your
254 authority, the path component ~, and the current value of @prodtblAccref.
255 It thus will only work where products#define (or a replacement) is in
256 action. If it isn't, a normal function call
257 getStandardPubDID(\\inputRelativePath) would be an obvious alternative.
258
259 You *can* of course define your PubDIDs in a different way.
260 """
261 return ('getStandardPubDID(vars["prodtblAccref"])')
262
263 def macro_dlMetaURI(self, dlId):
264 """returns a link to the datalink document for the current product.
265
266 This assumes you're assigning standard pubDIDs (see also standardPubDID,
267 which is used by this).
268
269 dlId is the XML id of the datalink service, which is supposed to
270 be in the sameRD as the rowmaker.
271 """
272 return ('"%%s?ID=%%s"%%('
273 'rd_.getById(%s).getURL("dlmeta", absolute=True),'%repr(dlId)+
274 'urllib.parse.quote(getStandardPubDID(vars["prodtblAccref"])))')
275
276 def macro_fullPath(self):
277 """returns an expression expanding to the full path of the current
278 input file.
279 """
280 return 'vars["parser_"].sourceToken'
281
282 def macro_inputRelativePath(self, liberalChars="True"):
283 """see grammars.common.GrammarMacroMixin
284 """
285 return ('str(getInputsRelativePath('
286 'vars["parser_"].sourceToken, liberalChars=%s))'
287 )%base.parseBooleanLiteral(liberalChars)
288
289 def macro_rowsProcessed(self):
290 """returns an expression giving the number of records already
291 delivered by the grammar.
292 """
293 return 'vars["parser_"].recNo'
294
295 def macro_rowsMade(self):
296 """returns an expression giving the number of records already
297 returned by this row maker.
298
299 This number excludes failed and skipped rows.
300 """
301 return '_self.rowsMade'
302
303 def macro_property(self, propName):
304 """returns an expression giving the value of the property propName
305 on the current DD.
306 """
307 return 'curDD_.getProperty("%s")'%propName
308
309 def macro_sourceDate(self):
310 """returns an expression giving the timestamp of the current source.
311
312 This is a timestamp of the modification date; use dateTimeToJdn or
313 dateTimeToMJD to turn this into JD or MJD (which is usually preferred
314 in database tables). See also the sourceCDate macro.
315 """
316 return ('datetime.datetime.utcfromtimestamp('
317 'os.path.getmtime(vars["parser_"].sourceToken))')
318
319 def macro_sourceCDate(self):
320 """returns an expression giving the timestamp for the create
321 date of the current source.
322
323 Use dateTimeToJdn or dateTimeToMJD to turn this into JD or MJD (which
324 is usually preferred in database tables). See also the sourceDate macro.
325 """
326 return ('datetime.datetime.utcfromtimestamp('
327 'os.path.getctime(vars["parser_"].sourceToken))')
328
329 def macro_srcstem(self):
330 """returns python code for the stem of the source file currently parsed in a rowmaker.
331
332 Example: if you're currently parsing /tmp/foo.bar.gz, the stem is foo.
333 """
334 return ('getFileStem(vars["parser_"].sourceToken)')
335
336 def macro_lastSourceElements(self, numElements):
337 """returns an expression calling rmkfuncs.lastSourceElements on
338 the current input path.
339 """
340 return 'lastSourceElements(vars["parser_"].sourceToken, %d)'%(
341 int(numElements))
342
343 def macro_rootlessPath(self):
344 """returns an expression giving the current source's path with
345 the resource descriptor's root removed.
346 """
347 return 'utils.getRelativePath(vars["parser_"].sourceToken, rd_.resdir)'
348
349 def macro_inputSize(self):
350 """returns an expression giving the size of the current source.
351 """
352 return 'os.path.getsize(vars["parser_"].sourceToken)'
353
354 def macro_docField(self, name):
355 """returns an expression giving the value of the column name in the
356 document row.
357 """
358 return '_parser.getParameters()[fieldName]'
359
360 def macro_qName(self):
361 """returns the qName of the table we are currently parsing into.
362 """
363 return "tableDef_.getQName()"
364
365
366 class RowmakerDef(base.Structure, RowmakerMacroMixin):
367 """A definition of the mapping between grammar input and finished rows
368 ready for shipout.
369
370 Rowmakers consist of variables, procedures and mappings. They
371 result in a python callable doing the mapping. In python code
372 within rowmaker elements, you can use a large number of functions.
373 See `Functions available for row makers`_ in the reference documentation.
374
375 RowmakerDefs double as macro packages for the expansion of various
376 macros. The standard macros will need to be quoted, the rowmaker macros
377 above yield python expressions.
378
379 Within map and var bodies as well as late apply pars and apply bodies,
380 you can refer to the grammar input as vars["name"] or, shorter @name.
381
382 To add output keys, use map or, in apply bodies, add keys to the
383 ``result`` dictionary.
384 """
385 name_ = "rowmaker"
386
387 _maps = base.StructListAttribute("maps", childFactory=MapRule,
388 description="Mapping rules.", copyable=True)
389 _vars = base.StructListAttribute("vars", childFactory=VarDef,
390 description="Definitions of intermediate variables.",
391 copyable=True)
392 _apps = base.StructListAttribute("apps",
393 childFactory=ApplyDef, description="Procedure applications.",
394 copyable=True)
395 _rd = common.RDAttribute()
396 _idmaps = base.StringListAttribute("idmaps", description="List of"
397 ' column names that are just "mapped through" (like map with key'
398 " only); you can use shell patterns to select multiple columns at once.",
399 copyable=True)
400 _simplemaps = base.IdMapAttribute("simplemaps", description=
401 "Abbreviated notation for <map source>; each pair is destination:source",
402 copyable=True)
403 _ignoreOn = base.StructAttribute("ignoreOn", default=None,
404 childFactory=rowtriggers.IgnoreOn, description="Conditions on the"
405 " input record coming from the grammar to cause the input"
406 " record to be dropped by the rowmaker, i.e., for this specific"
407 " table. If you need to drop a row for all tables being fed,"
408 " use a trigger on the grammar.", copyable=True)
409 _original = base.OriginalAttribute()
410
411 @classmethod
412 def makeIdentityFromTable(cls, table, **kwargs):
413 """returns a rowmaker that just maps input names to column names.
414 """
415 if "id" not in kwargs:
416 kwargs["id"] = "autogenerated rowmaker for table %s"%table.id
417 return base.makeStruct(cls, idmaps=[c.key for c in table], **kwargs)
418
419 @classmethod
420 def makeTransparentFromTable(cls, table, **kwargs):
421 """returns a rowmaker that maps input names to column names without
422 touching them.
423
424 This is for crazy cases in which the source actually provides
425 pre-parsed data that any treatment would actually ruin.
426 """
427 if "id" not in kwargs:
428 kwargs["id"] = "autogenerated rowmaker for table %s"%table.id
429 return base.makeStruct(cls, maps=[
430 base.makeStruct(MapRule, key=c.name, content_="vars[%s]"%repr(c.name))
431 for c in table],
432 **kwargs)
433
434 def completeElement(self, ctx):
435 if self.simplemaps:
436 for k,v in self.simplemaps.items():
437 nullExcs = base.NotGiven
438 if v.startswith("@"):
439 v = v[1:]
440 nullExcs = "KeyError,"
441 self.feedObject("maps", base.makeStruct(MapRule,
442 key=k, source=v, nullExcs=nullExcs))
443 super().completeElement(ctx)
444
445 def _getSourceFromColset(self, columns):
446 """returns the source code for a mapper to a column set.
447 """
448 lineMap, line = {}, 0
449 source = []
450
451 def appendToSource(srcLine, line, lineMarker):
452 source.append(srcLine)
453 line += 1
454 lineMap[line] = lineMarker
455 line += source[-1].count("\n")
456 return line
457
458 if self.ignoreOn:
459 line = appendToSource("if checkTrigger(vars):\n"
460 " raise IgnoreThisRow(vars)",
461 line, "Checking ignore")
462 for v in self.vars:
463 line = appendToSource(v.getCode(columns), line, "assigning "+str(v.key))
464 for a in self.apps:
465 line = appendToSource(
466 "%s(vars, result, targetTable, _self)"%a.name,
467 line, "executing "+a.name)
468 for m in self.maps:
469 line = appendToSource(m.getCode(columns), line, "building "+str(m.key))
470 return "\n".join(source), lineMap
471
472 def _getSource(self, tableDef):
473 """returns the source code for a mapper to tableDef's columns.
474 """
475 return self._getSourceFromColset(tableDef.columns)
476
477 def _getGlobals(self, tableDef):
478 globals = {}
479 for a in self.apps:
480 globals[a.name] = a.compile()
481 if self.ignoreOn:
482 globals["checkTrigger"] = self.ignoreOn
483 globals["tableDef_"] = tableDef
484 globals["rd_"] = tableDef.rd
485 globals["curDD_"] = tableDef.parent
486 return globals
487
488 def _resolveIdmaps(self, columns):
489 """adds mappings for self's idmap within column set.
490 """
491 existingMaps = set(m.key for m in self.maps)
492 baseNames = [c.key for c in columns]
493 for colName in self.idmaps:
494 matching = fnmatch.filter(baseNames, colName)
495 if not matching:
496 raise base.NotFoundError(colName, "columns matching", "unknown")
497 for dest in matching:
498 if dest not in existingMaps:
499 self.maps.append(MapRule(self, key=dest).finishElement(None))
500 self.idmaps = []
501
502 def _checkTable(self, columns, id):
503 """raises a LiteralParseError if we try to map to non-existing
504 columns.
505 """
506 for map in self.maps:
507 try:
508 columns.getColumnByName(map.key)
509 except KeyError:
510 raise base.ui.logOldExc(base.LiteralParseError(self.name_, map.key,
511 "Cannot map to '%s' since it does not exist in %s"%(
512 map.key, id)))
513
514 def _buildForTable(self, tableDef):
515 """returns a RowmakerDef with everything expanded and checked for
516 tableDef.
517
518 This may raise LiteralParseErrors if self's output is incompatible
519 with tableDef.
520 """
521 res = self.copyShallowly()
522 try:
523 res._resolveIdmaps(tableDef.columns)
524 res._checkTable(tableDef.columns, tableDef.id)
525 except base.NotFoundError as ex:
526 ex.within = "table %s's columns"%tableDef.id
527 raise
528 return res
529
530 def _realCompileForTableDef(self, tableDef):
531 """helps compileForTableDef.
532 """
533 rmk = self._buildForTable(tableDef)
534 source, lineMap = rmk._getSource(tableDef)
535 globals = rmk._getGlobals(tableDef)
536 return Rowmaker(common.replaceProcDefAt(source),
537 self.id or "<rowmaker without id>",
538 globals, tableDef.getDefaults(), lineMap)
539
540 def compileForTableDef(self, tableDef):
541 """returns a function receiving a dictionary of raw values and
542 returning a row ready for adding to a tableDef'd table.
543
544 To do this, we first make a rowmaker instance with idmaps resolved
545 and then check if the rowmaker result and the table structure
546 are compatible.
547 """
548 return utils.memoizeOn(tableDef, self, self._realCompileForTableDef,
549 tableDef)
550
551 def copyShallowly(self):
552 return base.makeStruct(self.__class__, maps=self.maps[:],
553 vars=self.vars[:], idmaps=self.idmaps[:],
554 apps=self.apps[:], ignoreOn=self.ignoreOn)
555
556
557 class ParmakerDef(RowmakerDef):
558 name_ = "parmaker"
559
560 def _buildForTable(self, tableDef):
561 res = self.copyShallowly()
562 try:
563 res._resolveIdmaps(tableDef.params)
564 res._checkTable(tableDef.params, tableDef.id)
565 except base.NotFoundError as ex:
566 ex.within = "table %s's params"%tableDef.id
567 raise
568 return res
569
570 def _getSource(self, tableDef):
571 """returns the source code for a mapper to tableDef's columns.
572 """
573 return self._getSourceFromColset(tableDef.params)
574
575
576 identityRowmaker = base.makeStruct(RowmakerDef, idmaps="*")
577
578
579 class Rowmaker:
580 """A callable that arranges for the mapping of key/value pairs to
581 other key/value pairs.
582
583 Within DaCHS, Rowmakers generate database rows (and parameter dictionaries)
584 from the output of grammars.
585
586 They are constructed with the source of the mapping function, a dictionary of
587 globals the function should see, a dictionary of defaults, giving keys to be
588 inserted into the incoming rowdict before the mapping function is called, and
589 a map of line numbers to names handled in that line.
590
591 It is called with a dictionary of locals for the functions (i.e.,
592 usually the result of a grammar iterRows).
593 """
594 def __init__(self, source, name, globals, defaults, lineMap):
595 try:
596 self.code = compile(source, "generated mapper code", "exec")
597 except SyntaxError as msg:
598 raise base.ui.logOldExc(
599 base.BadCode(source, "rowmaker", msg))
600 self.source, self.name = source, name
601 globals.update(rmkfuncs.__dict__)
602 self.globals, self.defaults = globals, defaults
603 self.keySet = set(self.defaults)
604 self.lineMap = sorted(lineMap.items())
605 self.rowsMade = 0
606
607 def _guessExSourceName(self, tb):
608 """returns an educated guess as to which mapping should have
609 caused that traceback in tb.
610
611 This is done by inspecting the second-topmost stackframe. It
612 must hold the generated line that, possibly indirectly, caused
613 the exception. This line should be in the lineMap generated by
614 RowmakerDef._getSource.
615 """
616 if tb.tb_next:
617 excLine = tb.tb_next.tb_lineno
618 base.ui.notifyDebug(
619 "Here's the traceback:\n%s"%"".join(traceback.format_tb(tb)))
620 else: # toplevel failure, internal
621 return "in toplevel (internal failure)"
622 destInd = min(len(self.lineMap)-1,
623 bisect.bisect_left(self.lineMap, (excLine, "")))
624 # If we're between lineMap entries, the one before the guessed one
625 # is the one we want
626 if self.lineMap[destInd][0]>excLine and destInd:
627 destInd -= 1
628 return self.lineMap[destInd][1]
629
630 def _guessError(self, ex, rowdict, tb):
631 """tries to shoehorn a ValidationError out of ex.
632 """
633 base.ui.notifyDebug("Rowmaker failed. Exception below. Failing source"
634 " is:\n%s"%self.source)
635 destName = self._guessExSourceName(tb)
636 if isinstance(ex, KeyError):
637 msg = "Key %s not found in a mapping."%str(ex)
638 hint = ("This probably means that your grammar did not yield the"
639 " field asked for. Alternatively, bugs in procs might also"
640 " cause this.")
641 else:
642 msg = str(ex)
643 hint = ("This is a failure in more-or-less user-provided code."
644 " If you run again with the global --debug flag, the source of"
645 " the failing code should be in the logs/dcInfos (but make"
646 " sure it's the source the error is reported for; with procs,"
647 " this might not be the case).")
648 raise base.ui.logOldExc(base.ValidationError("While %s in %s: %s"%(
649 destName, self.name, msg), destName.split()[-1], rowdict,
650 hint=hint))
651
652 def __call__(self, vars, table):
653 try:
654 locals = {
655 "result": {},
656 "_self": self,
657 "targetTable": table
658 }
659 # we stuff vars into globals so list comprehensions see them.
660 # This is a *bit* ugly in that they survive the call in this
661 # way; but at least self.globals belongs to us, so we don't
662 # leak our vars anywhere else.
663 self.globals["vars"] = vars
664 missingKeys = self.keySet-set(vars)
665 for k in missingKeys:
666 vars[k] = self.defaults[k]
667 exec(self.code, self.globals, locals)
668
669 self.rowsMade += 1
670 return locals["result"]
671 except base.ExecutiveAction: # pass these on
672 raise
673 except base.ValidationError: # hopefully downstream knows better than we
674 raise
675 except Exception as ex:
676 base.ui.notifyWarning(
677 "The source of the failing rowmaker:\n{}".format(self.source))
678 self._guessError(ex, self.globals["vars"], sys.exc_info()[2])