Debian Codegraph @

gavo/rsc/data.py

raw
1 """
2 Making data out of descriptors and sources.
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 itertools
12 import operator
13 import sys
14
15 from gavo import base
16 from gavo import rscdef
17 from gavo import utils
18 from gavo.rsc import common
19 from gavo.rsc import dbtable
20 from gavo.rsc import table
21 from gavo.rsc import tables
22 from functools import reduce
23
24
25 MS = base.makeStruct
26
27
28 class _DataFeeder(table._Feeder):
29 """is a feeder for data (i.e., table collections).
30
31 This is basically a collection of all feeders of the tables belonging
32 to data, except it will also call the table's mappers, i.e., add
33 expects source rows from data's grammars.
34
35 Feeders can be dispatched; this only works if the grammar returns
36 pairs of role and row rather than only the row. Dispatched
37 feeders only pass rows to the makes corresponding to the role.
38
39 If you pass in a connection, the data feeder will manage it (i.e.
40 commit if all went well, rollback otherwise).
41 """
42 def __init__(self, data, batchSize=1024, dispatched=False,
43 runCommit=True, connection=None, dumpIngestees=False):
44 self.data, self.batchSize = data, batchSize
45 self.runCommit = runCommit
46 self.nAffected = 0
47 self.connection = connection
48 self.dumpIngestees = dumpIngestees
49 if dispatched:
50 makeAdders = self._makeFeedsDispatched
51 else:
52 makeAdders = self._makeFeedsNonDispatched
53
54 addersDict, parAddersDict, self.feeders = self._getAdders()
55 self.add, self.addParameters = makeAdders(addersDict, parAddersDict)
56
57 def _getAdders(self):
58 """returns a triple of (rowAdders, parAdders, feeds) for the data we
59 feed to.
60
61 rowAdders contains functions to add raw rows returned from a grammar,
62 parAdders the same for parameters returned by the grammar, and
63 feeds is a list containing all feeds the adders add to (this
64 is necessary to let us exit all of them.
65 """
66 adders, parAdders, feeders = {}, {}, []
67 for make in self.data.makes:
68 table = self.data.tables[make.table.id]
69 feeder = table.getFeeder(batchSize=self.batchSize)
70 makeRow = make.rowmaker.compileForTableDef(table.tableDef)
71
72 def addRow(srcRow, feeder=feeder, makeRow=makeRow, table=table):
73 try:
74 procRow = makeRow(srcRow, table)
75 if self.dumpIngestees:
76 print("PROCESSED ROW:", procRow)
77 feeder.add(procRow)
78 except rscdef.IgnoreThisRow:
79 pass
80
81 if make.rowSource=="parameters":
82 parAdders.setdefault(make.role, []).append(addRow)
83 else:
84 adders.setdefault(make.role, []).append(addRow)
85
86 if make.parmaker:
87 parAdders.setdefault(make.role, []).append(
88 lambda row, m=make, t=table: m.runParmakerFor(row, t))
89
90 feeders.append(feeder)
91 return adders, parAdders, feeders
92
93 def _makeFeedsNonDispatched(self, addersDict, parAddersDict):
94 adders = reduce(operator.add, list(addersDict.values()), [])
95 parAdders = reduce(operator.add, list(parAddersDict.values()), [])
96 def add(row):
97 for adder in adders:
98 adder(row)
99 def addParameters(row):
100 for adder in parAdders:
101 adder(row)
102 return add, addParameters
103
104 def _makeFeedsDispatched(self, addersDict, parAddersDict):
105 def add(roleRow):
106 role, row = roleRow
107 if role not in addersDict:
108 raise base.ReportableError("Grammar tries to feed to role '%s',"
109 " but there is no corresponding make"%role)
110 for adder in addersDict[role]:
111 adder(row)
112
113 # for parameters, allow broadcast
114 def addParameters(roleRow):
115 try:
116 role, row = roleRow
117 except ValueError:
118 # assume we only got a row, broadcast it
119 for adder in itertools.chain(*list(parAddersDict.values())):
120 adder(roleRow)
121 else:
122 for adder in parAddersDict[role]:
123 adder(row)
124
125 return add, addParameters
126
127 def flush(self):
128 for feeder in self.feeders:
129 feeder.flush()
130
131 def reset(self):
132 for feeder in self.feeders:
133 feeder.reset()
134
135 def __enter__(self):
136 for feeder in self.feeders:
137 feeder.__enter__()
138 return self
139
140 def _breakCycles(self):
141 del self.feeders
142 del self.add
143 del self.addParameters
144
145 def _exitFailing(self, *excInfo):
146 """calls all subordinate exit methods when there was an error in
147 the controlled block.
148
149 This ignores any additional exceptions that might come out of
150 the exit methods.
151
152 The connection is rolled back, and we unconditionally propagate
153 the exception.
154 """
155 for feeder in self.feeders:
156 try:
157 feeder.__exit__(*excInfo)
158 except:
159 base.ui.notifyError("Ignored exception while exiting data feeder"
160 " on error.")
161 if self.connection and self.runCommit:
162 self.connection.rollback()
163 self._breakCycles()
164
165 def _exitSuccess(self):
166 """calls all subordinate exit methods when the controlled block
167 exited successfully.
168
169 If one of the exit methods fails, we run _exitFailing and re-raise
170 the exception.
171
172 If all went well and we control a connection, we commit it (unless
173 clients explicitly forbid it).
174 """
175 affected = []
176 for feeder in self.feeders:
177 try:
178 feeder.__exit__(None, None, None)
179 except:
180 self._exitFailing(*sys.exc_info())
181 raise
182 affected.append(feeder.getAffected())
183
184 if self.connection and self.runCommit:
185 self.connection.commit()
186
187 self._breakCycles()
188 if affected:
189 self.nAffected = max(affected)
190
191 def __exit__(self, *excInfo):
192 if excInfo and excInfo[0]:
193 return self._exitFailing(*excInfo)
194 else:
195 self._exitSuccess()
196
197 def getAffected(self):
198 return self.nAffected
199
200
201 class Data(base.MetaMixin, common.ParamMixin):
202 """A collection of tables.
203
204 ``Data``, in essence, is the instantiation of a ``DataDescriptor``.
205
206 It is what ``makeData`` returns. In typical one-table situations,
207 you just want to call the ``getPrimaryTable()`` method to obtain the
208 table built.
209
210 These also have an attribute contributingMetaCarriers, a list of
211 base.MetaCarrier-s used by votablewrite to create Data Origin INFO-s. By
212 default, that's the first table. You can add to that attribute
213 """
214 def __init__(self,
215 dd,
216 tables,
217 parseOptions=common.parseNonValidating,
218 overrideMakes=None):
219 base.MetaMixin.__init__(self) # we're not a structure
220 self.dd, self.parseOptions = dd, parseOptions
221 self.makes = overrideMakes or self.dd.makes
222 self.tables = tables
223 self.contributingMetaCarriers = []
224 self.setMetaParent(self.dd)
225 self._initParams(self.dd)
226
227 def __iter__(self):
228 for make in self.makes:
229 # it may be useful to suppress the serialisation of a table by
230 # deleting it from self.tables; hence, let's check for the
231 # table's existence before yielding it.
232 if make.table.id in self.tables:
233 yield self.tables[make.table.id]
234
235 @classmethod
236 def create(cls, dd, parseOptions=common.parseNonValidating,
237 connection=None):
238 """returns a new data instance for dd.
239
240 Existing tables on the database are not touched. To actually
241 re-create them, call recrateTables.
242 """
243 controlledTables = {}
244 res = cls(dd, controlledTables, parseOptions)
245 for make in dd.makes:
246 controlledTables[make.table.id
247 ] = make.create(connection,
248 parseOptions,
249 tables.TableForDef,
250 parent=res)
251 return res
252
253 @classmethod
254 def drop(cls, dd, parseOptions=common.parseNonValidating, connection=None):
255 """drops all tables made by dd if necessary.
256 """
257 controlledTables = {}
258 for make in dd.makes:
259 controlledTables[make.table.id
260 ] = tables.TableForDef(
261 make.table,
262 create=False,
263 connection=connection,
264 make=make)
265 data = cls(dd, controlledTables, parseOptions)
266 data.dropTables(parseOptions)
267 return data
268
269 @classmethod
270 def createWithTable(cls,
271 dd,
272 tableDef,
273 parseOptions=common.parseNonValidating):
274 """builds a table for tableDef with this data item.
275
276 This is for when there are many rather similar table structures
277 that can all be built with the same data item.
278
279 This can only work if dd only has one make.
280 """
281 if len(dd.makes)!=1:
282 raise base.ReportableError("Data.create_table is only"
283 " allowed on one-make DDs")
284 if tableDef.onDisk:
285 raise base.ReportableError("Data.create_table so far"
286 " doesn't allow onDisk tables (this is because nobody"
287 " has thought about it; it would probably be harmless).")
288
289 controlledTables = {tableDef.id: tables.TableForDef(tableDef)}
290 res = cls(dd, controlledTables, parseOptions,
291 overrideMakes=[dd.makes[0].change(table=tableDef)])
292 res.contributingMetaCarriers.append(tableDef)
293
294 return res
295
296 def dbCatalogChanged(self):
297 """returns true if a database table has been newly created by
298 this class.
299 """
300 return any([
301 isinstance(t, dbtable.DBTable)
302 and t.newlyCreated for t in list(self.tables.values())])
303
304 def validateParams(self):
305 """raises a ValidationError if any required parameters within
306 this data's tables are still None.
307 """
308 for t in self:
309 t.validateParams()
310
311 def dropTables(self, parseOptions):
312 for t in self:
313 if t.tableDef.onDisk:
314 if not parseOptions.systemImport and t.tableDef.system:
315 continue
316 t.drop()
317
318 def updateMeta(self):
319 for t in self:
320 if hasattr(t, "updateMeta"):
321 t.updateMeta()
322
323 def recreateTables(self, connection):
324 """drops and recreates all table that are onDisk.
325
326 System tables are only recreated when the systemImport parseOption
327 is true.
328 """
329 if self.dd.updating:
330 if self.parseOptions.dropIndices:
331 for t in self:
332 if t.tableDef.onDisk:
333 t.dropIndices()
334
335 for t in self:
336 if t.newlyCreated:
337 t.runScripts("preImport")
338
339 return
340
341 for t in self:
342 if t.tableDef.system and not self.parseOptions.systemImport:
343 continue
344 if t.tableDef.onDisk and not t.newlyCreated:
345 t.recreate()
346 t.runScripts("preImport")
347
348 def getParam(self, paramName, default=base.NotGiven):
349 """returns self's parameter of paramName, or, failing that, paramName
350 from self's primaryTable.
351 """
352 try:
353 return common.ParamMixin.getParam(self, paramName, default)
354 except base.NotFoundError:
355 try:
356 return self.getPrimaryTable().getParam(paramName, default)
357 except (base.DataError, base.NotFoundError):
358 # param not in primary table, or no primary table:
359 # raise first exception
360 pass
361 raise
362
363 def getPrimaryTable(self):
364 """returns the table contained if there is only one, or the one
365 with the role primary.
366
367 If no matching table can be found, raise a DataError.
368 """
369 if len(self.tables)==1:
370 return list(self.tables.values())[0]
371
372 try:
373 return self.tables[self.dd.getPrimary().id]
374 except (KeyError, base.StructureError):
375 raise base.DataError(
376 "No primary table in this data")
377
378 def getTableWithRole(self, role):
379 try:
380 return self.tables[self.dd.getTableDefWithRole(role).id]
381 except (KeyError, base.StructureError):
382 raise base.DataError(
383 "No table with role %s known here"%repr(role))
384
385 def getFeeder(self, **kwargs):
386 return _DataFeeder(self, **kwargs)
387
388 def runScripts(self, phase, **kwargs):
389 for make in self.makes:
390 make.getRunner()(self.tables[make.table.id], phase, **kwargs)
391
392
393 class _EnoughRows(base.ExecutiveAction):
394 """is an internal exception that allows processSource to tell makeData
395 to stop handling more sources.
396 """
397
398
399 def _pipeRows(srcIter, feeder, opts):
400 pars = srcIter.getParameters()
401 if opts.dumpIngestees:
402 print("PROCESSED PARAMS:", pars)
403 feeder.addParameters(pars)
404
405 for srcRow in srcIter:
406
407 if srcRow is common.FLUSH:
408 feeder.flush()
409 continue
410
411 if srcIter.notify:
412 base.ui.notifyIncomingRow(srcRow)
413 if opts.dumpRows:
414 print(srcRow)
415
416 feeder.add(srcRow)
417 if opts.maxRows:
418 if base.ui.totalRead>=opts.maxRows:
419 raise _EnoughRows
420
421
422 def _processSourceReal(data, source, feeder, opts):
423 """helps processSource.
424 """
425 if data.dd.grammar is None:
426 raise base.ReportableError("The data descriptor %s cannot be used"
427 " to make data since it has no defined grammar."%data.dd.id)
428 data.runScripts("newSource", sourceToken=source)
429 srcIter = data.dd.grammar.parse(source, data)
430 if hasattr(srcIter, "getParameters"): # is a "normal" grammar
431 try:
432 _pipeRows(srcIter, feeder, opts)
433 except (base.Error,base.ExecutiveAction):
434 raise
435 except Exception as msg:
436 raise base.ui.logOldExc(
437 base.SourceParseError(repr(msg),
438 source=utils.makeLeftEllipsis(repr(source), 80),
439 location=srcIter.getLocator()))
440 else: # magic grammars (like those of boosters) return a callable
441 srcIter(data)
442 data.runScripts("sourceDone", sourceToken=source, feeder=feeder)
443
444
445 def processSource(data, source, feeder, opts, connection=None):
446 """ingests source into the Data instance data.
447
448 If this builds database tables, you must pass in a connection object.
449
450 If opts.keepGoing is True,the system will continue importing
451 even if a particular source has caused an error. In that case,
452 everything contributed by the bad source is rolled back (this will
453 only work when filling database tables).
454 """
455 if not opts.keepGoing:
456 # simple shortcut if we don't want to recover from bad sources
457 _processSourceReal(data, source, feeder, opts)
458
459 else: # recover from bad sources, be more careful
460 if connection is None:
461 raise base.ReportableError("Can only ignore source errors"
462 " when filling database tables.",
463 hint="The -c flag on dachs imp and its friends builds on database"
464 " savepoints. You can thus only meaningfully use it when your"
465 " table has onDisk='True'.")
466 try:
467 with connection.savepoint():
468 _processSourceReal(data, source, feeder, opts)
469 feeder.flush()
470 except base.ExecutiveAction:
471 raise
472 except Exception as ex:
473 feeder.reset()
474 base.ui.notifyError("Error while importing source %s; changes from"
475 " this source will be rolled back, processing will continue."
476 " (%s)"%(
477 utils.makeSourceEllipsis(source),
478 utils.safe_str(ex)))
479
480
481 class _TableCornucopeia(object):
482 """a scaffolding class instances of which return something (eventually
483 table-like) for all keys it is asked for.
484 """
485 def __getitem__(self, key):
486 return None
487
488 def __len__(self):
489 # is is mainly a signal to getPrimaryTable to try a bit harder
490 # when we stand in for data.tables.
491 return 0
492
493
494 class MultiForcedSources:
495 """This lets you pass in arbitrary sequences as forceSource in makeData.
496
497 Without this, the list will be interpreted as a single source.
498 """
499 def __init__(self, seq):
500 self.seq = seq
501
502 def iterSources(self, connection):
503 return iter(self.seq)
504
505
506 def makeData(dd, parseOptions=common.parseNonValidating,
507 forceSource=None, connection=None, data=None, runCommit=True):
508 """returns a data instance built from ``dd``.
509
510 It will arrange for the parsing of all tables generated from dd's grammar.
511
512 If database tables are being made, you *must* pass in a connection.
513 The entire operation will then run within a single transaction within
514 this connection (except for building dependents; they will be built
515 in separate transactions).
516
517 The connection will be rolled back or committed depending on the
518 success of the operation (unless you pass ``runCommit=False``, in
519 which case even a successful import will not be committed)..
520
521 You can pass in a data instance created by yourself in data. This
522 makes sense if you want to, e.g., add some meta information up front.
523
524 makeData will usually iterate over the sources given in dd. You
525 can override this with forceSource, which can contain a single
526 source passed to a grammar. If you need to pass in multiple
527 sources, use a MultiForcedSources object (or anything that has
528 an iterSources(dbConnection) method).
529 """
530 # Some proc setup does expensive things like actually building data.
531 # We don't want that when validating and return some empty data thing.
532 if getattr(base, "VALIDATING", False):
533 return Data(dd, _TableCornucopeia())
534
535 if data is None:
536 res = Data.create(dd, parseOptions, connection=connection)
537 else:
538 res = data
539 res.recreateTables(connection)
540
541 feederOpts = {"batchSize": parseOptions.batchSize, "runCommit": runCommit,
542 "dumpIngestees": parseOptions.dumpIngestees}
543 if dd.grammar and dd.grammar.isDispatching:
544 feederOpts["dispatched"] = True
545
546 with res.getFeeder(connection=connection, **feederOpts) as feeder:
547 if forceSource is None:
548 sources = dd.iterSources(connection)
549 else:
550 if hasattr(forceSource, "iterSources"):
551 sources = forceSource.iterSources(connection)
552 else:
553 sources = [forceSource]
554
555 for source in sources:
556 try:
557 processSource(res, source, feeder, parseOptions, connection)
558 except _EnoughRows:
559 base.ui.notifyWarning("Source hit import limit, import aborted.")
560 break
561 except base.SkipThis:
562 continue
563
564 res.validateParams()
565 res.nAffected = feeder.getAffected()
566
567 if parseOptions.buildDependencies:
568 makeDependentsFor(
569 [dd],
570 parseOptions,
571 connection,
572 res.dbCatalogChanged())
573
574 return res
575
576
577 class DDDependencyGraph(object):
578 """a graph giving the dependency structure between DDs.
579
580 This is constructed with a list of DDs.
581
582 From it, you can get a build sequence (least-depending thing build first) or
583 a destroy sequence (most-depending things built first).
584
585 If you pass spanRDs=True, only DDs residing within the first DD's RD are
586 considered.
587 """
588 def __init__(self, dds, spanRDs=True):
589 self.limitToRD = None
590 if not spanRDs and dds:
591 self.limitToRD = dds[0].rd
592
593 self._edges, self._seen = set(), set()
594 self._gather(dds)
595
596 def _gatherOne(self, dd):
597 for dependentId in dd.dependents:
598 try:
599 dependentDD = base.resolveId(dd.rd, dependentId)
600 if self.limitToRD and self.limitToRD!=dependentDD.rd:
601 continue
602
603 self._edges.add((dd, dependentDD))
604 if dependentDD not in self._seen:
605 self._seen.add(dependentDD)
606 self._gatherOne(dependentDD)
607 except (base.StructureError, base.NotFoundError) as msg:
608 base.ui.notifyWarning("Ignoring dependent %s of %s (%s)"%(
609 dependentId, dd.getFullId(), str(msg)))
610
611 def _gather(self, dds):
612 for dd in dds:
613 self._gatherOne(dd)
614
615 def getBuildSequence(self):
616 return utils.topoSort(self._edges)
617
618 def getDestroySequence(self):
619 inverted = [(b,a) for a, b in self._edges]
620 return utils.topoSort(inverted)
621
622
623 def makeDependentsFor(dds, parseOptions, connection, sysCatChanged):
624 """rebuilds all data dependent on one of the DDs in the dds sequence.
625 """
626 if parseOptions.buildDependencies:
627 parseOptions = parseOptions.change(buildDependencies=False)
628
629 try:
630 buildSequence = DDDependencyGraph(dds).getBuildSequence()
631 except ValueError as ex:
632 raise utils.logOldExc(base.ReportableError("Could not sort"
633 " dependent DDs topologically (use --hints to learn more).",
634 hint="This is most likely because there's a cyclic dependency."
635 " Please check your dependency structure. The original message"
636 " is: %s"%utils.safe_str(ex)))
637
638 # remove DDs passed in from the build sequence, as long as nothing
639 # is built in between (which might necessitate a re-build of something
640 # we already did)
641 for dd in buildSequence[:]:
642 if dd in dds:
643 buildSequence.pop(0)
644 else:
645 break
646
647 if parseOptions.metaOnly:
648 # TODO: Is metaOnly just a special case of sysCatChange=False?
649 if buildSequence:
650 base.ui.notifyWarning("Only importing metadata, not rebuilding"
651 " dependencies. Depending on your changes, it may be"
652 " necessary to manually re-make one of these: %s"%
653 ", ".join(dd.getFullId() for dd in buildSequence))
654 else:
655 for dd in buildSequence:
656 if sysCatChanged or dd.remakeOnDataChange:
657 base.ui.notifyInfo("Making dependent %s"%dd.getFullId())
658 makeData(dd, parseOptions=parseOptions, connection=connection)
659
660
661 def makeDataById(ddId, parseOptions=common.parseNonValidating,
662 connection=None, inRD=None):
663 """returns the data set built from the DD with ddId (which must be
664 fully qualified).
665 """
666 dd = base.resolveId(inRD, ddId)
667 return makeData(dd, parseOptions=parseOptions, connection=connection)
668
669
670 def wrapTable(table, rdSource=None, resTypeDefault="results"):
671 """returns a Data instance containing only table (or table if it's already
672 a data instance).
673
674 If table has no rd, you must pass rdSource, which must be an object having
675 and rd attribute (rds, tabledefs, etc, work).
676
677 resTypeDefault will be used as the new data item's _type meta. If you
678 want to override that later, use setMeta("_type"...) rather than addMeta.
679
680 This will grab info meta from the table.
681 """
682 if hasattr(table, "dd"):
683 # we trust it's already a Data instance (don't want to use isinstance
684 # here since people may pass in fakes).
685 return table
686
687 if rdSource is None:
688 rd = table.tableDef.rd
689 elif hasattr(rdSource, "rd"):
690 rd = rdSource.rd
691 else:
692 raise TypeError("Invalid RD source: %s"%rdSource)
693 newDD = MS(rscdef.DataDescriptor, makes=[
694 MS(rscdef.Make, table=table.tableDef, rowmaker=None)], parent_=rd)
695 if rdSource:
696 newDD.adopt(table.tableDef)
697
698 newDD.setMetaParent(table.tableDef.rd)
699
700 res = Data(newDD, tables={table.tableDef.id: table})
701 res.contributingMetaCarriers.append(table)
702 res.setMeta("_type", resTypeDefault)
703
704 for infoMeta in table.iterMeta("info"):
705 res.addMeta("info", infoMeta)
706 for mi in table.iterMeta("_votableRootAttributes", propagate=False):
707 res.addMeta("_votableRootAttributes", mi)
708
709 return res
710
711
712 def makeCombinedData(baseDD, tablesForRoles):
713 """returns a Data instance containing all of tablesForRoles.
714
715 A DD is being generated based on baseDD; if baseDD has any tables, they are
716 discarded.
717
718 tablesForRoles is a mapping from strings (one of which should be "primary")
719 to tables; the strings end up as roles.
720 """
721 newDD = baseDD.change(
722 makes=[MS(rscdef.Make, table=t.tableDef, rowmaker=None, role=role)
723 for role, t in tablesForRoles.items()])
724 newDD.meta_ = baseDD._metaAttr.getCopy(baseDD, newDD, None)
725 return Data(newDD, tables=dict((t.tableDef.id, t)
726 for t in list(tablesForRoles.values())))