Debian Codegraph @

gavo/rsc/table.py

raw
1 """
2 Tables, base and in memory.
3
4 Basically, a table consists of a list of dictionaries (the rows) and a
5 table definition (resdef.TableDef).
6
7 You should, in general, not construct the tables directly but use
8 the tables.TableForDef factory. The reason is that some classes ignore
9 certain aspects of TableDefs (indices, uniqueForceness) or may not be
10 what TableDef requires at all (onDisk). Arguably there should be
11 different TableDefs for all these aspects, but then I'd have a plethora
12 of TableDef elements, which I think is worse than a factory function.
13 """
14
15 #c Copyright 2008-2025, the GAVO project <[email protected]>
16 #c
17 #c This program is free software, covered by the GNU GPL. See the
18 #c COPYING file in the source distribution.
19
20
21 import sys
22 import weakref
23
24 from gavo import base
25 from gavo import rscdef
26 from gavo.rsc import common
27
28
29 class Error(base.Error):
30 pass
31
32
33 class ColumnStat(object):
34 """Column statistics as exposed by Limits.
35
36 These have min, max, and values attributes, all of which can be None.
37 Otherwise, min and max are values of the column type, values is a set
38 of those.
39 """
40 def __init__(self):
41 self.min, self.max = None, None
42 self.values = None
43
44
45 class Limits(dict):
46 """Column statistics (min/max, values) for an in-memory table.
47
48 These are constructed with the rows attribute and a list each for
49 columns for which you want min/max and the values present. Note
50 that None in min/max indicates no non-None values were found. An
51 empty set in values indicates that all values were None.
52
53 This then exposes a dictionary interface
54 """
55 def __init__(self, rows, minmaxColumns, enumColumns):
56 dict.__init__(self)
57 self._addMinmax(rows, minmaxColumns)
58 self._addEnums(rows, enumColumns)
59
60 def _addMinmax(self, rows, minmaxColumns):
61 stats = [(name, ColumnStat()) for name in minmaxColumns]
62 self.update(dict(stats))
63
64 for row in rows:
65 for name, stat in stats:
66 val = row[name]
67 if val is None:
68 continue
69 if stat.min is None or stat.min>val:
70 stat.min = val
71 if stat.max is None or stat.max<val:
72 stat.max = val
73
74 def _addEnums(self, rows, enumColumns):
75 stats = [(name, self.get("name", ColumnStat())) for name in enumColumns]
76 self.update(dict(stats))
77 for _, stat in stats:
78 stat.values = set()
79
80 for row in rows:
81 for name, stat in stats:
82 if row[name] is not None:
83 stat.values.add(row[name])
84
85
86 class _Feeder(object):
87 """A device for getting data into a table.
88
89 A feeder is a context manager that rejects all action from without
90 the controlled section. Within the controlled section, you can use:
91
92 - add(row) -> None -- add row to table. This may raise all kinds
93 of crazy exceptions.
94 - flush() -> None -- flush out all data that may be cached to the table
95 (this is done automatically on a successful exit)
96 - reset() -> None -- discard any data that may still wait to be
97 flushed to the table
98
99 At the end of the controlled block, the importFinished or importFailed
100 methods or the parent table are called depending on whether all is
101 well or an exception happened. If importFinished raises and
102 exception, it is handed on to importFailed and re-raised if importFailed
103 returns False.
104
105 The batch size constructor argument is for the benefit of DBTables.
106
107 The flush and reset methods are necessary when you do explicit buffering and
108 connection management; you will need to call flush before committing a
109 transaction and reset before rolling one back.
110 """
111 def __init__(self, table, batchSize=1024):
112 self.table = table
113 self.nAffected = 0
114 self.active = False
115
116 def _assertActive(self):
117 if not self.active:
118 raise base.DataError("Trying to feed a dormant feeder.")
119
120 def getAffected(self):
121 return self.nAffected
122
123 def add(self, row):
124 self._assertActive()
125 if self.table.validateRows:
126 self.table.tableDef.validateRow(row)
127 self.table.addRow(row)
128 self.nAffected += 1
129
130 def flush(self):
131 self._assertActive()
132 # no-op for ram feeder
133
134 def reset(self):
135 self._assertActive()
136 # no-op for ram feeder
137
138 def __enter__(self):
139 self.active = True
140 return self
141
142 def __exit__(self, excType=None, excVal=None, excTb=None):
143 try:
144 if excType is None: # all ok
145 try:
146 self.table.importFinished(self.nAffected)
147 except:
148 if not self.table.importFailed(*sys.exc_info()):
149 raise
150 else: # exception occurred in controlled block
151 self.table.importFailed(excType, excVal, excTb)
152 finally:
153 self.active = False
154 return False
155
156
157 def _makeFailIncomplete(name):
158 def fail(self, *args, **kwargs):
159 raise NotImplementedError("%s is an incomplete Table implementation."
160 " No method '%s' defined."%(self.__class__.__name__, name))
161 return fail
162
163
164 class BaseTable(base.MetaMixin, common.ParamMixin):
165 """is a container for row data.
166
167 Tables consist of rows, where each row maps column names to their
168 value for that row. The rows are accessible at least by iterating
169 over a table.
170
171 Tables get constructed with a tableDef and keyword arguments. For
172 convenience, tables must accept any keyword argument and only pluck those
173 out it wants.
174
175 Here's a list of keywords used by BaseTables or known subclasses:
176
177 * validateRows -- have rows be validated by the tableDef before addition
178 (all Tables)
179 * rows -- a list of rows the table has at start (InMemoryTables; DbTables
180 will raise an error on these).
181 * connection -- a database connection to use for accessing DbTables.
182 * votCasts -- a dictionary mapping column names to dictionaries overriding
183 keys of valuemappers.AnnontatedColumn.
184 * params -- a dictionary mapping param keys to values, where python
185 values and literals allowed.
186
187 You can add rows using the addRow method. For bulk additions, however,
188 it may be much more efficient to call getFeeder (though for in-memory
189 tables, there is no advantage).
190
191 Initial Metadata is populated from the tableDef.
192
193 Tables have to implement the following methods:
194
195 - ``__iter__``
196 - ``__len__``
197 - ``__getitem__(n)`` -- returns the n-th row or raises an IndexError
198 - ``removeRow(row) removes a row from the table or raises an
199 IndexError if the row does not exist. This is a slow, O(n) operation.
200 - ``addRow(row)`` -- appends new data to the table
201 - ``getRow(*args)`` -- returns a row by the primary key. If no primary key
202 is defined, a ValueError is raised, if the key is not present, a
203 KeyError. An atomic primary key is accessed through its value,
204 for compound primary keys a tuple must be passed.
205 - ``getFeeder(**kwargs)`` -> feeder object -- returns an object with add and
206 exit methods. See feeder above.
207 - ``importFinished(nAffected)`` -> None -- called when a feeder exits
208 successfully
209 - ``importFailed(*excInfo)`` -> boolean -- called when feeding has failed;
210 when returning True, the exception that has caused the failure
211 is not propagated.
212 - ``close()`` -> may be called by clients to signify the table will no
213 longer be used and resources should be cleared (e.g., for DBTables
214 with private connections).
215
216 Tables also have several attributes:
217
218 - ``tableDef`` -- the TableDef that describes the table.
219 - ``newlyCreated`` -- true unless a pre-existing database table was
220 kept (e.g., in updating DDs).
221 """
222 def __init__(self, tableDef, **kwargs):
223 base.MetaMixin.__init__(self)
224 self.tableDef = tableDef
225 self.newlyCreated = True
226 self.setMetaParent(self.tableDef.getMetaParent())
227 self.meta_ = self.tableDef.meta_.copy()
228
229 self.validateRows = kwargs.pop("validateRows", False)
230 self.makeRunning = kwargs.pop("make", None)
231 self.votCasts = kwargs.pop("votCasts", {})
232
233 parent = kwargs.pop("parent", None)
234 self.parent = parent and weakref.proxy(parent)
235
236 self._initParams(self.tableDef, kwargs.pop("params", None))
237
238 __iter__ = _makeFailIncomplete("__iter__")
239 __len__ = _makeFailIncomplete("__len__")
240 removeRow = _makeFailIncomplete("removeRow")
241 addRow = _makeFailIncomplete("addRow")
242 getRow = _makeFailIncomplete("getRow")
243 getFeeder = _makeFailIncomplete("getFeeder")
244
245 def getPrimaryTable(self):
246 """returns the table itself.
247
248 This is just there so that code can blindly say .getPrimaryTable()
249 not worrying whether what it has is a data item or a table.
250 """
251 return self
252
253 def addTuple(self, tupRow):
254 self.addRow(self.tableDef.makeRowFromTuple(tupRow))
255
256 def importFinished(self, nAffected):
257 pass
258
259 def importFailed(self, *excInfo):
260 return False
261
262 def close(self):
263 pass
264
265 def validateParams(self):
266 """raises a ValidationError if any required parameters of this
267 tables are None.
268 """
269 for par in self.iterParams():
270 if par.required and par.value is None:
271 raise base.ValidationError(
272 "Value is required but was not provided", par.name)
273
274 def expand(self, s):
275 """macro-expands the string s within self's tableDef.
276 """
277 if "\\" in s:
278 s = self.tableDef.expand(s)
279 return s
280
281
282 class InMemoryTable(BaseTable):
283 """is a table kept in memory.
284
285 This table only keeps an index for the primary key. All other indices
286 are ignored.
287 """
288 def __init__(self, tableDef, **kwargs):
289 BaseTable.__init__(self, tableDef, **kwargs)
290 self.rows = kwargs.get("rows", [])
291
292 def __iter__(self):
293 return iter(self.rows)
294
295 def __len__(self):
296 return len(self.rows)
297
298 def __bool__(self):
299 return bool(self.rows)
300
301 def removeRow(self, row):
302 self.rows.remove(row)
303
304 def addRow(self, row):
305 if self.validateRows:
306 try:
307 self.tableDef.validateRow(row)
308 except rscdef.IgnoreThisRow:
309 return
310 self.rows.append(row)
311
312 def getRow(self, *args):
313 raise ValueError("Cannot use getRow in index-less table")
314
315 def getFeeder(self, **kwargs):
316 return _Feeder(self, **kwargs)
317
318 def getLimits(self):
319 """returns a limits instance for this table.
320
321 This is a characterisation of the ranges of things in this table,
322 pretty much as what dachs info does; if you fix things here, you probably
323 want to fix things there, too.
324 """
325 minmaxColumns, enumColumns = [], []
326 for col in self.tableDef:
327 if col.isEnumerated():
328 enumColumns.append(col.name)
329 elif col.type in base.ORDERED_TYPES or col.type.startswith("char"):
330 minmaxColumns.append(col.name)
331 return Limits(self.rows, minmaxColumns, enumColumns)
332
333
334 class InMemoryIndexedTable(InMemoryTable):
335 """is an InMemoryTable for a TableDef with a primary key.
336 """
337 def __init__(self, tableDef, **kwargs):
338 InMemoryTable.__init__(self, tableDef, **kwargs)
339 if not self.tableDef.primary:
340 raise Error("No primary key given for InMemoryIndexedTable")
341 self._makeRowIndex()
342
343 def removeRow(self, row):
344 # This remains slow since we do not keep the index of a row in self.rows
345 InMemoryTable.removeRow(self, row)
346 del self.rowIndex[self.tableDef.getPrimaryIn(row)]
347
348 def addRow(self, row):
349 if self.validateRows:
350 try:
351 self.tableDef.validateRow(row)
352 except rscdef.IgnoreThisRow:
353 return
354 self.rows.append(row)
355 self.rowIndex[self.tableDef.getPrimaryIn(row)] = row
356
357 def getRow(self, *args):
358 return self.rowIndex[args]
359
360 def _makeRowIndex(self):
361 """recreates the index of primary keys to rows.
362 """
363 self.rowIndex = {}
364 for r in self.rows:
365 self.rowIndex[self.tableDef.getPrimaryIn(r)] = r
366
367
368 class UniqueForcedTable(InMemoryIndexedTable):
369 """is an InMemoryTable with an enforced policy on duplicate
370 primary keys.
371
372 See resdef.TableDef for a discussion of the policies.
373 """
374 def __init__(self, tableDef, **kwargs):
375 # hide init rows (if present) in the next line to not let
376 # duplicate primaries slip in here.
377 rows = kwargs.pop("rows", [])
378 InMemoryIndexedTable.__init__(self, tableDef, **kwargs)
379 try:
380 self.resolveConflict = {
381 "check": self._ensureRowIdentity,
382 "drop": self._dropNew,
383 "overwrite": self._overwriteOld,
384 "dropOld": self._overwriteOld,
385 }[self.tableDef.dupePolicy]
386 except KeyError as msg:
387 raise base.ui.logOldExc(
388 Error("Invalid conflict resolution strategy: %s"%str(msg)))
389 for row in rows:
390 self.addRow(row)
391
392 def _ensureRowIdentity(self, row, key):
393 """raises an exception if row is not equivalent to the row stored
394 for key.
395
396 This is one strategy for resolving primary key conflicts.
397 """
398 storedRow = self.rowIndex[key]
399 if list(row.keys())!=list(storedRow.keys()):
400 raise Error("Differing rows for primary key %s: %s vs. %s"%(
401 key, self.rowIndex[key], row))
402 for colName in row:
403 if row[colName]!=storedRow[colName]:
404 raise base.ValidationError(
405 "Differing rows for primary key %s;"
406 " %s vs. %s"%(key, row[colName],
407 storedRow[colName]), colName=colName, row=row)
408
409 def _dropNew(self, row, key):
410 """does nothing.
411
412 This is for resolution of conflicting rows (the "drop" strategy).
413 """
414 pass
415
416 def _overwriteOld(self, row, key):
417 """overwrites the existing rows with key in table with rows.
418
419 This is for resolution of conflicting rows (the "overwrite"
420 strategy).
421
422 Warning: This is typically rather slow.
423 """
424 storedRow = self.rowIndex[key]
425 self.removeRow(storedRow)
426 return self.addRow(row)
427
428 def addRow(self, row):
429 if self.validateRows:
430 try:
431 self.tableDef.validateRow(row)
432 except rscdef.IgnoreThisRow:
433 return
434 key = self.tableDef.getPrimaryIn(row)
435 if key in self.rowIndex:
436 return self.resolveConflict(row, key)
437 else:
438 self.rowIndex[key] = row
439 return InMemoryIndexedTable.addRow(self, row)