Debian Codegraph @

gavo/rscdef/tabledef.py

raw
1 """
2 Description and definition of tables.
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 functools
12 import re
13
14 from gavo import adql
15 from gavo import base
16 from gavo import dm
17 from gavo import stc
18 from gavo import utils
19 from gavo.rscdef import column
20 from gavo.rscdef import common
21 from gavo.rscdef import group
22 from gavo.rscdef import mixins
23 from gavo.rscdef import rmkfuncs
24 from gavo.rscdef import scripting
25
26
27 MS = base.makeStruct
28
29
30 @functools.total_ordering
31 class DBIndex(base.Structure):
32 """A description of an index in the database.
33
34 In real databases, indices may be fairly complex things; still, the
35 most common usage here will be to just index a single column::
36
37 <index columns="my_col"/>
38
39 To index over functions, use the character content; you will have
40 to put parentheses when using expressions. An explicit specification
41 of the index expression is also necessary to allow RE pattern matches using
42 indices in character columns (outside of the C locale). That would be::
43
44 <index columns="uri">uri text_pattern_ops</index>
45
46 (you still want to give columns so the metadata engine is aware of the
47 index). See section "Operator Classes and Operator Families" in
48 the Postgres documentation for details.
49
50 For pgsphere-valued columns, you at the time of writing need to specify
51 the method::
52
53 <index columns="coverage" method="GIST"/>
54
55 To define q3c indices, use the ``//scs#q3cindex`` mixin; if you're
56 devious enough to require something more flexible, have a look at
57 that mixin's definition.
58
59 If indexed columns take part in a DaCHS-defined view, DaCHS will not
60 notice. You should still declare the indices so users will see them
61 in the metadata; writing::
62
63 <index columns="col1, col2, col3"/>
64
65 is sufficient for that.
66
67 If you really cannot avoid having columns with delimited ("quoted")
68 identifiers, you need to refer to them with a quoted/ prefix as in
69 columns's name attribute. And yes, that won't work for delimited
70 identifiers with commas in them. Just don't do delimited identifiers
71 in the first place.
72 """
73 name_ = "index"
74
75 _name = base.UnicodeAttribute("name", default=base.Undefined,
76 description="Name of the index. Defaults to something computed from"
77 " columns; the name of the parent table will be prepended in the DB."
78 " The default will *not* work if you have multiple indices on one"
79 " set of columns.",
80 copyable=True)
81 _columns = base.StringListAttribute("columns", description=
82 "Table columns taking part in the index (must be given even if there"
83 " is an expression building the index and mention all columns taking"
84 " part in the index generated by it", copyable=True)
85 _cluster = base.BooleanAttribute("cluster", default=False,
86 description="Cluster the table according to this index?",
87 copyable=True)
88 _code = base.DataContent(copyable=True, description=
89 "Raw SQL specifying an expression the table should be"
90 " indexed for. If not given, the expression will be generated from"
91 " columns (which is what you usually want).")
92 _method = base.UnicodeAttribute("method", default=None,
93 description="The indexing method, like an index type. In the 8.x,"
94 " series of postgres, you need to set method=GIST for indices"
95 " over pgsphere columns; otherwise, you should not need to"
96 " worry about this.", copyable=True)
97 _kind = base.UnicodeAttribute("kind", default="straight",
98 description="A tag on the index; this is used by the ADQL translation"
99 " engine in some situations. Consider it a DaCHS implementation"
100 " detail and ignore it for now.",
101 copyable=True)
102 _metaOnly = base.UnicodeAttribute("metaOnly", default=False,
103 description="Do not tell the database to actually create the index,"
104 " just declare it in the metadata. This is for when you want"
105 " to tell users of the ADQL engine that columns in, say, a view"
106 " are indexed when the database cannot actually create the"
107 " index but the underlying tables provide one.",
108 copyable=True)
109 _options = base.ListOfAtomsAttribute("options",
110 itemAttD=base.UnicodeAttribute("option"),
111 default=[],
112 description="Index modifiers. For DaCHS, this is free text,"
113 " except that DaCHS will order INCLUDE, WITH, TABLESPACE, and"
114 " WHERE clauses it recognises to yield a syntactically correct"
115 " postgres statement.")
116
117 def completeElement(self, ctx):
118 if getattr(ctx, "restricted", False) and (
119 self.content_ or self.options):
120 raise base.RestrictedElement("index", hint="Free-form SQL on indices"
121 " is not allowed in restricted mode")
122
123 super().completeElement(ctx)
124
125 if not self.columns and not self.content_:
126 raise base.StructureError("Index without columns is verboten.")
127
128 if self.name is base.Undefined:
129 self.name = "%s"%(re.sub(r"[^\w]+", "_", "_".join(
130 str(c) for c in self.columns)))
131
132 if not self.content_:
133 self.content_ = "%s"%(",".join(
134 str(utils.QuotedName.parse(c)) for c in self.columns))
135
136 # indices are sorted by table; this should put them in an order
137 # optimal for importing. Right now, we only make sure indices
138 # with CLUSTER go as early as possible.
139 def __eq__(self, other):
140 return id(self)==id(other)
141
142 def __lt__(self, other):
143 othercluster = getattr(other, "cluster", None)
144 if ((self.cluster and othercluster)
145 or (not self.cluster and not othercluster)):
146 return id(self)<id(other)
147 else:
148 if self.cluster:
149 return True
150 else:
151 return False
152
153 # a mapping of index options prefixes to relative positions in the create
154 # index statement.
155 _optionPrefixMap = {
156 "include": 1,
157 "with": 2,
158 "tablespace": 3,
159 "where": 4}
160
161 def _collateOptions(self):
162 """returns values of options sorted such that they'll hopefully
163 work in a CREATE INDEX statement.
164
165 This does not perform deeper inspection and just looks at the start of
166 the option fragments.
167
168 Anything we don't recognise is sorted to the front.
169 """
170 parts = []
171 for phrase in self.options:
172 relPos = self._optionPrefixMap.get(
173 re.search(r"\w+", phrase).group(0).lower(), 0)
174 parts.append((relPos, phrase))
175
176 parts.sort()
177 return [p[1] for p in parts]
178
179 def iterCode(self):
180 destTableName = self.parent.getQName()
181
182 usingClause = ""
183 if self.method is not None:
184 usingClause = " USING %s"%self.method
185
186 options = ""
187 if self.options:
188 options = " "+" ".join(self._collateOptions())
189
190 yield self.parent.expand(
191 f"CREATE INDEX {self.dbname} ON {destTableName}{usingClause}"
192 f" ({self.content_}){options}")
193
194 if self.cluster:
195 yield self.parent.expand(
196 "CLUSTER %s ON %s"%(self.dbname, destTableName))
197
198 def create(self, querier, notify=True):
199 """creates the index on the parent table if necessary.
200
201 querier is an object mixing in the DBMethodsMixin, usually the
202 DBTable object the index should be created on.
203 """
204 if not querier.hasIndex(self.parent.getQName(), self.dbname):
205 if notify and not self.parent.system:
206 base.ui.notifyIndexCreation(
207 self.parent.expand(self.dbname))
208 for statement in self.iterCode():
209 querier.connection.execute(statement)
210
211 def drop(self, querier):
212 """drops the index if it exists.
213
214 querier is an object mixing in the DBMethodsMixin, usually the
215 DBTable object the index possibly exists on.
216 """
217 iName = self.parent.expand(self.dbname)
218 if querier.hasIndex(self.parent.getQName(), iName):
219 querier.connection.execute(
220 "DROP INDEX %s.%s"%(self.parent.rd.schema, iName))
221
222 @property
223 def dbname(self):
224 return "%s_%s"%(self.parent.id, self.name)
225
226
227 class ColumnTupleAttribute(base.StringListAttribute):
228 """is a tuple of column names.
229
230 In a validate method, it checks that the names actually are in parent's
231 fields.
232 """
233 def iterParentMethods(self):
234 """adds a getPrimaryIn method to the parent class.
235
236 This function will return the value of the primary key in a row
237 passed. The whole thing is a bit dense in that I want to compile
238 that method to avoid having to loop every time it is called. This
239 compilation is done in a descriptor -- ah well, probably it's a waste
240 of time anyway.
241 """
242 def makeGetPrimaryFunction(instance):
243 funcSrc = ('def getPrimaryIn(row):\n'
244 ' return (%s)')%(" ".join(['row["%s"],'%name
245 for name in getattr(instance, self.name_)]))
246 return utils.compileFunction(funcSrc, "getPrimaryIn")
247
248 def getPrimaryIn(self, row):
249 try:
250 return self.__getPrimaryIn(row)
251 except AttributeError:
252 self.__getPrimaryIn = makeGetPrimaryFunction(self)
253 return self.__getPrimaryIn(row)
254 yield "getPrimaryIn", getPrimaryIn
255
256 def validate(self, parent):
257 for colName in getattr(parent, self.name_):
258 try:
259 parent.getColumnByName(colName)
260 except base.NotFoundError:
261 raise base.ui.logOldExc(base.LiteralParseError(self.name_, colName,
262 hint="Column tuple component %s is not in parent table"%colName))
263
264
265 class ForeignKey(base.Structure):
266 """A description of a foreign key relation between this table and another
267 one.
268 """
269 name_ = "foreignKey"
270
271 _inTable = base.ReferenceAttribute("inTable", default=base.Undefined,
272 description="Reference to the table the foreign key points to.",
273 copyable=True)
274 _source = base.UnicodeAttribute("source", default=base.Undefined,
275 description="Comma-separated list of local columns corresponding"
276 " to the foreign key. No sanity checks are performed here.",
277 copyable=True)
278 _dest = base.UnicodeAttribute("dest", default=base.NotGiven,
279 description="Comma-separated list of columns in the target table"
280 " belonging to its key. No checks for their existence, uniqueness,"
281 " etc. are done here. If not given, defaults to source.")
282 _metaOnly = base.BooleanAttribute("metaOnly", default=False,
283 description="Do not tell the database to actually create the foreign"
284 " key, just declare it in the metadata. This is for when you want"
285 " to document a relationship but don't want the DB to actually"
286 " enforce this. This is typically a wise thing to do when you have, say"
287 " a gigarecord of flux/density pairs and only several thousand metadata"
288 " records -- you may want to update the latter without having"
289 " to tear down the former.")
290
291 def getDescription(self):
292 return "%s:%s -> %s:%s"%(self.parent.getQName(), ",".join(self.source),
293 self.destTableName, ".".join(self.dest))
294
295 def _parseList(self, raw):
296 if isinstance(raw, list):
297 # we're being copied
298 return raw
299 return [s.strip() for s in raw.split(",") if s.strip()]
300
301 def onElementComplete(self):
302 self.destTableName = self.inTable.getQName()
303 self.isADQLKey = self.inTable.adql and self.inTable.adql!='hidden'
304
305 self.source = self._parseList(self.source)
306 if self.dest is base.NotGiven:
307 self.dest = self.source
308 else:
309 self.dest = self._parseList(self.dest)
310 super().onElementComplete()
311
312 def create(self, querier):
313 if self.metaOnly:
314 return
315
316 if not querier.foreignKeyExists(self.parent.getQName(),
317 self.destTableName,
318 self.source,
319 self.dest):
320 return querier.connection.execute("ALTER TABLE %s ADD FOREIGN KEY (%s)"
321 " REFERENCES %s (%s)"
322 " ON DELETE CASCADE"
323 " DEFERRABLE INITIALLY DEFERRED"%(
324 self.parent.getQName(),
325 ",".join(self.source),
326 self.destTableName,
327 ",".join(self.dest)))
328
329 def delete(self, querier):
330 if self.metaOnly:
331 return
332
333 try:
334 constraintName = querier.getForeignKeyName(self.parent.getQName(),
335 self.destTableName, self.source, self.dest)
336 except (ValueError, base.DBError): # key does not exist.
337 return
338 querier.connection.execute(
339 "ALTER TABLE %s DROP CONSTRAINT %s"%(self.parent.getQName(),
340 constraintName))
341
342 def getAnnotation(self, roleName, container, instance):
343 """returns a dm annotation for this foreign key.
344 """
345 return dm.ForeignKeyAnnotation(roleName, self, instance)
346
347
348 class STCDef(base.Structure):
349 """A definition of a space-time coordinate system using STC-S.
350 """
351 # Programmatically, you have
352 # * compiled -- an AST of the entire specification
353 # * iterColTypes -- iterates over column name/utype pairs, for the
354 # embedding table only; all others must not touch it
355
356 name_ = "stc"
357
358 _source = base.DataContent(copyable=True, description="An STC-S string"
359 " with column references (using quote syntax) instead of values")
360
361 # the following mapping translates legacy STC utypes to paths suitable
362 # for modern STC annotation in onElementComplete
363 # These are a bit sanitised in that the stupid indications of dimensionality
364 # are gone. To compare these, use the sanitizeUtype class method
365 # below. Aw, what madness!
366 _utypeToModern = {
367 "stc:AstroCoordSystem.SpaceFrame.CoordRefFrame":
368 "/space/frame/orientation",
369 "stc:AstroCoordSystem.SpaceFrame.ReferencePosition":
370 "/space/frame/refPosition",
371 "stc:AstroCoordSystem.SpaceFrame.CoordRefFrame.Equinox":
372 "/space/frame/equinox",
373 "stc:AstroCoordSystem.SpaceFrame.CoordFlavor":
374 "!!!flavor!!!",
375 "stc:AstroCoords.Position.Value.C1":
376 "/space/longitude",
377 "stc:AstroCoords.Position.Value.C2":
378 "/space/latitude",
379 "stc:AstroCoords.Position.Value.C3":
380 "/space/distance",
381 "stc:AstroCoords.Position.Value":
382 "/space/location",
383 "stc:AstroCoordArea.Polygon":
384 "/space/location",
385 "stc:AstroCoords.Velocity.Value.C1":
386 "/space/pm_longitude",
387 "stc:AstroCoords.Velocity.Value.C2":
388 "/space/pm_latitude",
389 "stc:AstroCoords.Velocity.Value.C3":
390 "/space/rv",
391 "stc:AstroCoords.Position.Epoch":
392 "/space/frame/epoch",
393 "stc:AstroCoords.Position.Epoch.yearDef":
394 "!!!yearDef!!!",
395 "stc:AstroCoords.Time.TimeInstant":
396 "/time/location",
397 "stc:AstroCoordSystem.TimeFrame.ReferencePosition":
398 "/time/frame/refPosition",
399 "stc:AstroCoordSystem.TimeFrame.TimeScale":
400 "/time/frame/timescale",
401 }
402
403 _sanitizer = re.compile(r"(Position|Value|Velocity)\dD?")
404
405 @classmethod
406 def sanitizeUtype(cls, utype):
407 """returns utypes without the stupid 2D/3D qualifications.
408 """
409 return cls._sanitizer.sub(r"\1", utype)
410
411 def completeElement(self, ctx):
412 super().completeElement(ctx)
413 try:
414 self.compiled = stc.parseQSTCS(self.content_)
415 except stc.STCSParseError as msg:
416 raise base.ui.logOldExc(base.StructureError(
417 "Bad stc definition: %s"%str(msg)))
418 self.compiled.stripUnits()
419 self._origFields = dict((value.dest, utype)
420 for utype, value in stc.getUtypes(self.compiled)
421 if isinstance(value, stc.ColRef))
422
423 def iterColTypes(self):
424 return iter(self._origFields.items())
425
426 def onParentComplete(self):
427 """produces new-style STC annotation from the utypes.
428
429 This is being called as an onParentCompleted function from the tables'
430 stc attribute. It makes <stc> declarations work with new-style
431 COOSYS and perhaps one day with mivot-based annotation.
432 """
433 translated = {}
434
435 for utype, value in stc.getUtypes(self.compiled):
436 utype = self.sanitizeUtype(utype)
437 if utype in self._utypeToModern:
438 translated[self._utypeToModern[utype]] = value
439 else:
440 pass # no match in the new data model --
441 if not translated:
442 return
443
444 # Ok, we can build a votable:Coords annotation
445 dm.buildAdhocSTC(self.parent, translated)
446
447
448 class ADQLVisibilityAttribute(base.BooleanAttribute):
449 """An attribute that has values True/False and hidden.
450 """
451 typeDesc_ = "boolean or 'hidden'"
452
453 # This can be hacked to hidden by dachs imp's --hide-adql option.
454 trueValue = True
455
456 def feedObject(self, instance, value):
457 if value=='hidden':
458 instance._readProfiles.feed(None, instance, "defaults,untrustedquery")
459 value = False
460 base.BooleanAttribute.feedObject(self, instance, value)
461
462 def parse(self, value):
463 if value.lower()=="hidden":
464 return "hidden"
465 return base.BooleanAttribute.parse(self, value) and self.trueValue
466
467 def unparse(self, value):
468 if value=="hidden":
469 return value
470 return base.BooleanAttribute.unparse(self, value)
471
472
473 class PublishableDataMixin(base.StructCallbacks):
474 """A mixin with a few methods and attributes for data that can be
475 published to the VO registry.
476
477 In particular, this contains the publish element (registration attribute).
478 """
479 _registration = base.StructAttribute("registration",
480 default=None,
481 childFactory=common.Registration,
482 copyable=False,
483 aliases=["register"],
484 description="A registration (to the VO registry) of this table"
485 " or data collection.")
486
487 def getPublicationsForSet(self, setNames, includeDatalink=True):
488 """returns a sequence of publication elements for the data, suitable
489 for OAI responses for the sets setNames.
490
491 Essentially: if registration is None, or its sets don't match
492 setNames, return an empty sequence.
493
494 If the registration mentions services, we turn their publications
495 into auxiliary publications and yield them
496
497 Otherwise, if we're published for ADQL, return the TAP service
498 as an auxiliary publication.
499 """
500 if (self.registration is None
501 or not self.registration.sets & setNames):
502 return
503
504 services = self.registration.services
505 if not services:
506 services = [base.resolveCrossId("//tap#run")]
507
508 for service in services:
509 # we only want the "primary" publication here, which means: no
510 # VOSI or other synthesized crap. The logic for now is:
511 # Discard all publications with a renderer not named in allowed.
512 for pub in service.getPublicationsForSet(setNames):
513 if pub.render in service.allowed:
514 copy = pub.change(parent_=self, auxiliary=True)
515 copy.meta_ = self.registration.meta_
516 yield copy
517
518
519 @base.buildstructure
520 class TableDef(base.Structure, base.ComputedMetaMixin, common.PrivilegesMixin,
521 common.IVOMetaMixin, base.StandardMacroMixin, PublishableDataMixin,
522 scripting.ScriptingMixin):
523 """A definition of a table, both on-disk and internal.
524
525 Some attributes are ignored for in-memory tables, e.g., roles or adql.
526
527 Properties for tables:
528
529 * supportsModel -- a short name of a data model supported through this
530 table (for TAPRegExt dataModel); you can give multiple names separated
531 by commas.
532 * supportsModelURI -- a URI of a data model supported through this table.
533 You can give multiple URIs separated by blanks.
534 * forceStats -- if present (with any value), dachs limits on the
535 embedding RD will obtain statistics of this even if it is a view.
536
537 If you give multiple data model names or URIs, the sequences of names and
538 URIs must be identical (in particular, each name needs a URI). But,
539 really, both of these are on the way out.
540
541 Somewhat inconsistently, to set a table's utype if you have to, set
542 its ``utype`` meta.
543
544 Tables within a schema can have a rank, with lower ranks displayed first in
545 clients that support that. So set that rank, put a positive number into
546 the ``table-rank`` meta (since version 2.9.3).
547 """
548 name_ = "table"
549
550 resType = "table"
551
552 acceptedScriptTypes = {"preIndex", "preCreation",
553 "postCreation", "beforeDrop", "afterMeta"}
554
555 # We don't want to force people to come up with an id for all their
556 # internal tables but want to avoid writing default-named tables to
557 # the db. Thus, the default is not a valid sql identifier.
558 _id = base.IdAttribute("id",
559 default=base.NotGiven,
560 description="Name of the table (must be SQL-legal for onDisk tables)")
561
562 _cols = common.ColumnListAttribute("columns",
563 childFactory=column.Column,
564 description="Columns making up this table.",
565 copyable=True)
566
567 _params = common.ColumnListAttribute("params",
568 childFactory=column.Param,
569 description='Param ("global columns") for this table.',
570 copyable=True)
571
572 _viewStatement = base.UnicodeAttribute("viewStatement",
573 default=None,
574 description="A single SQL statement to create a view. Setting this"
575 " makes this table a view. The statement will typically be something"
576 " like CREATE VIEW \\\\qName AS (SELECT \\\\colNames FROM...).",
577 copyable=True)
578
579 # onDisk must not be copyable since queries might copy the tds and havoc
580 # would result if the queries were to end up on disk.
581 _onDisk = base.BooleanAttribute("onDisk",
582 default=False,
583 description="Table in the database rather than in memory?")
584
585 _temporary = base.BooleanAttribute("temporary",
586 default=False,
587 description="If this is an onDisk table, make it temporary?"
588 " This is mostly useful for custom cores and such.",
589 copyable=True)
590
591 _adql = ADQLVisibilityAttribute("adql",
592 default=False,
593 description="Should this table be available for ADQL queries? In"
594 " addition to True/False, this can also be 'hidden' for tables"
595 " readable from the TAP machinery but not published in the"
596 " metadata; this is useful for, e.g., tables contributing to a"
597 " published view. Warning: adql=hidden is incompatible with setting"
598 " readProfiles manually.")
599
600 _system = base.BooleanAttribute("system",
601 default=False,
602 description="Is this a system table? If it is, it will not be"
603 " dropped on normal imports, and accesses to it will not be logged.")
604
605 _forceUnique = base.BooleanAttribute("forceUnique",
606 default=False,
607 description="Ignored legacy attribute.")
608
609 _dupePolicy = base.EnumeratedUnicodeAttribute("dupePolicy",
610 default=None,
611 validValues=["check", "drop", "overwrite", "dropOld"],
612 description= "Handle duplicate rows with identical primary keys manually"
613 " by raising an error if existing and new rows are not identical (check),"
614 " dropping the new one (drop), updating the old one (overwrite), or"
615 " dropping the old one and inserting the new one (dropOld)? Note that"
616 " if you change this, you will have to re-create the table to make"
617 " it take effect. The default is to have no special handling (which,"
618 " if a primary key is there at all, is like check, except an error"
619 " will be raised even if new and old row are identical).")
620
621 _primary = ColumnTupleAttribute("primary",
622 default=(),
623 description="Comma separated names of columns making up the primary key.",
624 copyable=True)
625
626 _indices = base.StructListAttribute("indices",
627 childFactory=DBIndex,
628 description="Indices defined on this table",
629 copyable=True)
630
631 _foreignKeys = base.StructListAttribute("foreignKeys",
632 childFactory=ForeignKey,
633 description="Foreign keys used in this table",
634 copyable=False)
635
636 _groups = base.StructListAttribute("groups",
637 childFactory=group.Group,
638 description="Groups for columns and params of this table",
639 copyable=True)
640
641 _nrows = base.IntAttribute("nrows",
642 description="Approximate number of rows in this table. While you"
643 " can hard-code this here, running dachs limits will put"
644 " an estimate into the database.")
645
646 # this actually induces an attribute annotations with the DM
647 # annotation instances
648 _annotations = dm.DataModelRolesAttribute()
649
650 _properties = base.PropertyAttribute()
651
652 # don't copy stc -- columns just keep the reference to the original
653 # stc on copy, and nothing should rely on column stc actually being
654 # defined in the parent tableDefs.
655 _stcs = base.StructListAttribute("stc", description="STC-S definitions"
656 " of coordinate systems.", childFactory=STCDef)
657
658 _rd = common.RDAttribute()
659 _mixins = mixins.MixinAttribute()
660 _original = base.OriginalAttribute()
661 _namePath = common.NamePathAttribute()
662
663 fixupFunction = None
664
665 metaModel = ("creationDate(1), description(1),"
666 "subject, referenceURL(1)")
667
668 @classmethod
669 def fromColumns(cls, columns, **kwargs):
670 """returns a TableDef from a sequence of columns.
671
672 You can give additional constructor arguments. makeStruct is used
673 to build the instance, the mixin hack is applied.
674
675 Columns with identical names will be disambiguated.
676 """
677 res = MS(cls,
678 columns=common.ColumnList(cls.disambiguateColumns(columns)),
679 **kwargs)
680 return res
681
682 def __iter__(self):
683 return iter(self.columns)
684
685 def __contains__(self, name):
686 try:
687 self.columns.getColumnByName(name)
688 except base.NotFoundError:
689 return False
690 return True
691
692 def __repr__(self):
693 try:
694 return "<Table definition of %s>"%self.getQName()
695 except base.Error:
696 return "<Non-RD table %s>"%self.id
697
698 def completeElement(self, ctx):
699 # Make room for DM annotations (these are currently filled by
700 # gavo.dm.dmrd.DataModelRoles, but we might reconsider this)
701 self.annotations = []
702
703 if self.viewStatement and getattr(ctx, "restricted", False):
704 raise base.RestrictedElement("table", hint="tables with"
705 " view creation statements are not allowed in restricted mode")
706
707 if self.registration:
708 if self.id is base.NotGiven:
709 raise base.StructureError("Published tables need an assigned id.")
710 else:
711 try:
712 self.setMeta("_metadataUpdated",
713 ctx.getInjected("resprop:%s#%s"%(self.rd.sourceId, self.id
714 ))["rectimestamp"])
715 except (KeyError, AttributeError):
716 # fallback to RD meta isn't a disaster here
717 pass
718
719 if not self.id:
720 self._id.feed(ctx, self, utils.intToFunnyWord(id(self)))
721
722 # allow iterables to be passed in for columns and convert them
723 # to a ColumnList here
724 if not isinstance(self.columns, common.ColumnList):
725 self.columns = common.ColumnList(self.columns)
726 self._resolveSTC()
727
728 if ctx and not self.nrows:
729 self.nrows = ctx.getInjected("table:%s"%self.id, {"nrows": None}
730 ).get("nrows")
731
732 super().completeElement(ctx)
733 self.columns.withinId = self.params.tableName = "table "+self.id
734
735 if ctx:
736 # this pushes min/max/median etc from the context to column/values
737 for col in self:
738 col.updateFromContext(self.id, col.name, ctx)
739
740 def validate(self):
741 if self.id.upper() in adql.ALL_RESERVED_WORDS:
742 raise base.StructureError("Reserved word %s is not allowed as a table"
743 " name"%self.id)
744
745 if self.scripts and not self.onDisk:
746 if self.rd and self.rd.schema=="test":
747 # for testing, we want to feed, say, obscore tables into memory
748 pass
749 else:
750 raise base.StructureError("Scripts are only supported for onDisk"
751 " tables")
752
753 super().validate()
754
755 def onElementComplete(self):
756 if self.adql:
757 self.readProfiles = (self.readProfiles |
758 base.getConfig("db", "adqlProfiles"))
759 self.dictKeys = [c.key for c in self]
760
761 self.indexedColumns = {}
762 for index in self.indices:
763 for col in index.columns:
764 if "\\" in col:
765 try:
766 col = self.expand(col)
767 except (base.Error, ValueError):
768 # cannot expand yet, ignore rather than pollute indexedColumns
769 continue
770
771 self.indexedColumns.setdefault(col, set()).add(index.kind)
772
773 if self.primary:
774 for col in self.primary:
775 self.indexedColumns.setdefault(col, set()).add("primary")
776
777 self._defineFixupFunction()
778
779 super().onElementComplete()
780
781 if self.registration:
782 self.registration.register()
783
784 # if there's no DM annotation yet, there's still a chance that our
785 # columns and params brought some with them. Try that.
786 if not self.annotations:
787 self.updateAnnotationFromChildren()
788
789 # we sort the indices for better performance (and possibly,
790 # one day, so things work at all, if there's dependencies).
791 # Right now, this only sorts indices to be clustered to the front.
792 self.indices.sort()
793
794 def getElementForName(self, name):
795 """returns the first of column and param having name name.
796
797 The function raises a NotFoundError if neither column nor param with
798 name exists.
799 """
800 try:
801 try:
802 return self.columns.getColumnByName(name)
803 except base.NotFoundError:
804 return self.params.getColumnByName(name)
805 except base.NotFoundError as ex:
806 ex.within = "table %s"%self.id
807 raise
808
809 def _resolveSTC(self):
810 """adds STC related attributes to this tables' columns.
811 """
812 for stcDef in self.stc:
813 for name, type in stcDef.iterColTypes():
814 destCol = self.getColumnByName(name)
815 if destCol.stc is not None:
816 # don't warn -- this kind of annotation is done for the future,
817 # when we can handle it properly.
818 continue
819 # base.ui.notifyWarning("Column %s is referenced twice from STC"
820 # " in table %s is referenced twice in STC groups. This"
821 # " is currently not supported, the second reference is"
822 # " ignored."%(name, self.getQName()))
823 destCol.stc = stcDef.compiled
824 destCol.stcUtype = type
825
826 def _defineFixupFunction(self):
827 """defines a function to fix up records from column's fixup attributes.
828
829 This will leave a fixupFunction attribute which will be None if
830 no fixups are defined.
831 """
832 fixups = []
833 for col in self:
834 if col.fixup is not None:
835 fixups.append((col.name, col.fixup))
836 if fixups:
837 assignments = []
838 for key, expr in fixups:
839 expr = expr.replace("___", "row['%s']"%key)
840 assignments.append(" row['%s'] = %s"%(key, expr))
841 source = self.expand(
842 "def fixup(row):\n%s\n return row"%("\n".join(assignments)))
843 self.fixupFunction = rmkfuncs.makeProc(
844 "fixup", source, "", None, self.getSourcePosition())
845
846 def getQName(self):
847 if self.temporary or not hasattr(self, "parent"):
848 return self.id
849 else:
850 if self.rd is None:
851 raise base.Error("TableDefs without resource descriptor"
852 " have no qualified names")
853 return "%s.%s"%(self.rd.schema, self.id)
854
855 def validateRow(self, row):
856 """checks that row is complete and complies with all known constraints on
857 the columns
858
859 The function raises a ValidationError with an appropriate message
860 and the relevant field if not.
861 """
862 for col in self:
863 if col.key not in row:
864 raise base.ValidationError("%s not bound in row"%col.name,
865 col.name, row, hint="The table %s has a column named '%s',"
866 " but the input row %s does not give it. This typically means"
867 " bad input or a rowmaker failing on some corner case."%(
868 self.id, col.name, row))
869 try:
870 col.validateValue(row[col.key])
871 except base.ValidationError as ex:
872 ex.row = row
873 raise
874
875 def getFieldIndex(self, fieldName):
876 """returns the index of the field named fieldName.
877 """
878 return self.columns.getFieldIndex(fieldName)
879
880 def getParamByName(self, name):
881 return self.params.getColumnByName(name)
882
883 def getColumnByName(self, name):
884 return self.columns.getColumnByName(name)
885
886 def getColumnById(self, id):
887 return self.columns.getColumnById(id)
888
889 def getColumnsByUCD(self, ucd):
890 return self.columns.getColumnsByUCD(ucd)
891
892 def getColumnByUCD(self, ucd):
893 return self.columns.getColumnByUCD(ucd)
894
895 def getColumnByUCDs(self, *ucds):
896 return self.columns.getColumnByUCDs(*ucds)
897
898 def getColumnsByUCDs(self, *ucds):
899 res = []
900 for ucd in ucds:
901 res.extend(self.columns.getColumnsByUCD(ucd))
902 return res
903
904 def getByUtype(self, utype):
905 """returns the column or param with utype.
906
907 This is supposed to be unique, but the function will just return
908 the first matching item it finds.
909 """
910 try:
911 return self.params.getColumnByUtype(utype)
912 except base.NotFoundError:
913 return self.columns.getColumnByUtype(utype)
914
915 def getByUtypes(self, *utypes):
916 """returns the first param or column matching the first utype
917 matching anything.
918 """
919 for utype in utypes:
920 try:
921 return self.getByUtype(utype)
922 except base.NotFoundError:
923 pass
924 raise base.NotFoundError(", ".join(utypes),
925 what="param or column with utype in",
926 within="table %s"%self.id)
927
928 def getByName(self, name):
929 """returns the column or param with name.
930
931 There is nothing keeping you from having both a column and a param with
932 the same name. If that happens, you will only see the column. But
933 don't do it.
934 """
935 try:
936 return self.columns.getColumnByName(name)
937 except base.NotFoundError:
938 return self.params.getColumnByName(name)
939
940 def makeRowFromTuple(self, dbTuple):
941 """returns a row (dict) from a row as returned from the database.
942 """
943 preRes = dict(list(zip(self.dictKeys, dbTuple)))
944 if self.fixupFunction:
945 return self.fixupFunction(preRes)
946 return preRes
947
948 def getDefaults(self):
949 """returns a mapping from column names to defaults to be used when
950 making a row for this table.
951 """
952 defaults = {}
953 for col in self:
954 if col.values:
955 defaults[col.name] = col.values.default
956 elif not col.required:
957 defaults[col.name] = None
958 return defaults
959
960 def getSTCDefs(self):
961 """returns a set of all STC specs referenced in this table as ASTs.
962 """
963 # Do not use our stc attribute -- the columns may come from different
964 # tables and carry stc from there.
965 stcObjects = utils.uniqueItems(col.stc for col in self)
966 if None in stcObjects:
967 stcObjects.remove(None)
968 return stcObjects
969
970 def getNote(self, noteTag):
971 """returns the table note meta value for noteTag.
972
973 This will raise a NotFoundError if we don't have such a note.
974
975 You will not usually use this to retrieve meta items since columns
976 have the meta values in their note attributes. Columns, of course,
977 use this to get their note attribute value.
978 """
979 mi = self.getMeta("note") or []
980 for mv in mi:
981 if mv.tag==noteTag:
982 return mv
983 else:
984 raise base.NotFoundError(noteTag, what="note tag",
985 within="table %s"%self.id)
986
987 def getURL(self, rendName, absolute=True):
988 """returns the URL DaCHS will show the table info page for this table
989 under.
990
991 Of course the URL is only valid for imported tables.
992 """
993 basePath = "%stableinfo/%s"%(
994 base.getConfig("web", "nevowRoot"),
995 self.getQName())
996 if absolute:
997 basePath = base.makeAbsoluteURL(basePath)
998 return basePath
999
1000 def getDDL(self):
1001 """returns an SQL statement that creates the table.
1002 """
1003 preTable = ""
1004 if self.temporary:
1005 preTable = "TEMP "
1006 statement = "CREATE %sTABLE %s (%s)"%(
1007 preTable,
1008 self.getQName(),
1009 ", ".join(column.getDDL() for column in self))
1010 return statement
1011
1012 def getSimpleQuery(self,
1013 selectClause=None,
1014 fragments="",
1015 postfix=""):
1016 """returns a query against this table.
1017
1018 selectClause is a list of column names (in which case the names
1019 are validated against the real column names and you can use
1020 user input) or a literal string (in which case you must not provide
1021 user input or have a SQL injection hole).
1022
1023 fragments (the WHERE CLAUSE) and postfix are taken as literal strings (so
1024 they must not contain user input).
1025
1026 This is purely a string operation, so you'll have your normal
1027 value references in fragments and postfix, and should maintain
1028 the parameter dictionaries as usual.
1029
1030 All parts are optional, defaulting to pulling the entire table.
1031 """
1032 parts = ["SELECT"]
1033
1034 if selectClause is None:
1035 parts.append("*")
1036 elif isinstance(selectClause, list):
1037 parts.append(", ".join(
1038 self.getColumnByName(colName).name for colName in selectClause))
1039 else:
1040 parts.append(selectClause)
1041
1042 parts.append("FROM %s"%self.getQName())
1043
1044 if fragments:
1045 parts.append("WHERE %s"%fragments)
1046
1047 if postfix:
1048 parts.append(postfix)
1049
1050 return " ".join(parts)
1051
1052 @property
1053 def caseFixer(self):
1054 return dict((col.name.lower(), col.name) for col in self)
1055
1056 def doSimpleQuery(self,
1057 selectClause=None,
1058 fragments="",
1059 params=None,
1060 postfix=""):
1061 """runs a query generated via getSimpleQuery and returns a list
1062 of rowdicts.
1063
1064 This uses a table connection and queryToDicts; the keys in the
1065 dictionaries will have the right case for this table's columns, though.
1066
1067 params is a dictionary of fillers for fragments and postfix.
1068 """
1069 with base.getTableConn() as conn:
1070 return list(
1071 conn.queryToDicts(
1072 self.getSimpleQuery(
1073 selectClause,
1074 fragments,
1075 postfix),
1076 params,
1077 caseFixer=self.caseFixer))
1078
1079 def macro_colNames(self):
1080 """returns an SQL-ready list of column names of this table.
1081 """
1082 return ", ".join(c.name for c in self.columns)
1083
1084 def macro_curtable(self):
1085 """returns the qualified name of the current table.
1086
1087 (this is identical to the `macro qName`_, which you should prefer
1088 in new RDs.)
1089 """
1090 return self.getQName()
1091
1092 def macro_qName(self):
1093 """returns the qualified name of the current table.
1094 """
1095 return self.getQName()
1096
1097 def macro_tablename(self):
1098 """returns the unqualified name of the current table.
1099
1100 In most contexts, you will probably need to use the `macro qName`_
1101 instead of this.
1102 """
1103 return self.id
1104
1105 def macro_nameForUCD(self, ucd):
1106 """returns the (unique!) name of the field having ucd in this table.
1107
1108 If there is no or more than one field with the ucd in this table,
1109 we raise a ValueError.
1110 """
1111 return self.getColumnByUCD(ucd).name
1112
1113 def macro_nameForUCDs(self, ucds):
1114 """returns the (unique!) name of the field having one
1115 of ucds in this table.
1116
1117 Ucds is a selection of ucds separated by vertical bars
1118 (|). The rules for when this raises errors are so crazy
1119 you don't want to think about them. This really is
1120 only intended for cases where "old" and "new" standards
1121 are to be supported, like with pos.eq.*;meta.main and
1122 POS_EQ_*_MAIN.
1123
1124 If there is no or more than one field with the ucd in
1125 this table, we raise an exception.
1126 """
1127 return self.getColumnByUCDs(*(s.strip() for s in ucds.split("|"))).name
1128
1129 def macro_getParam(self, parName, default=""):
1130 """returns the string representation of the parameter parName.
1131
1132 This is the parameter as given in the table definition. Any changes
1133 to an instance are not reflected here.
1134
1135 If the parameter named does not exist, an empty string is returned.
1136 NULLs/Nones are rendered as NULL; this is mainly a convenience
1137 for obscore-like applications and should not be exploited otherwise,
1138 since it's ugly and might change at some point.
1139
1140 If a default is given, it will be returned for both NULL and non-existing
1141 params.
1142 """
1143 try:
1144 param = self.params.getColumnByName(parName)
1145 except base.NotFoundError:
1146 return default
1147 if param.content_ is base.NotGiven or param.value is None:
1148 return default or "NULL"
1149 else:
1150 return param.content_
1151
1152 @staticmethod
1153 def disambiguateColumns(columns):
1154 """returns a sequence of columns without duplicate names.
1155 """
1156 newColumns, seenNames = [], set()
1157 for c in columns:
1158 while c.name in seenNames:
1159 c.name = c.name+"_"
1160 newColumns.append(c)
1161 seenNames.add(c.name)
1162 return newColumns
1163
1164 def _meta_howtociteLink(self):
1165 """returns a link to a how-to-cite page for this service as an URL
1166 meta.
1167 """
1168 if self.onDisk:
1169 # we assume we're sufficiently long-lived to merit a tableinfo if
1170 # we're on disk
1171 return base.META_CLASSES_FOR_KEYS["_related"](
1172 self.getURL(None, True)+"#ti-citing",
1173 title="Advice on citing this resource")
1174
1175 def _meta_referenceURL(self):
1176 """returns a link to the table-info page.
1177 """
1178 return base.META_CLASSES_FOR_KEYS["_related"](
1179 self.getURL(None, True),
1180 title="Table information")
1181
1182 def _meta_shortName(self):
1183 """makes the shortName default to the (possibly shortened) table name.
1184
1185 This is so simply published tables have a proper short name without
1186 any further action.
1187 """
1188 return self.getQName()[:16]
1189
1190
1191 def makeTDForColumns(name, cols, **moreKWs):
1192 """returns a TableDef object named names and having the columns cols.
1193
1194 cols is some sequence of Column objects. You can give arbitrary
1195 table attributes in keyword arguments.
1196 """
1197 kws = {"id": name, "columns": common.ColumnList(cols)}
1198 kws.update(moreKWs)
1199 return base.makeStruct(TableDef, **kws)