Debian Codegraph @

gavo/registry/tableset.py

raw
1 """
2 Generation of VODataService 1.1 tablesets from resources.
3
4 Fudge note: sprinkled in below are lots of lower()s for column names and the
5 like. These were added for the convenience of TAP clients that may
6 want to use these names quoted. Quoted identifiers match regular identifiers
7 only if case-normalized (i.e., all-lower in DaCHS).
8 """
9
10 #c Copyright 2008-2025, the GAVO project <[email protected]>
11 #c
12 #c This program is free software, covered by the GNU GPL. See the
13 #c COPYING file in the source distribution.
14
15
16 import functools
17 import itertools
18 import math
19
20 from gavo import base
21 from gavo import rscdef
22 from gavo import svcs
23 from gavo import utils
24 from gavo.registry.model import VS
25
26
27 _VOTABLE_TO_SIMPLE_TYPE_MAP = {
28 "char": "char",
29 "bytea": "char",
30 "unicodeChar": "char",
31 "short": "integer",
32 "int": "integer",
33 "long": "integer",
34 "float": "real",
35 "double": "real",
36 }
37
38 def simpleDataTypeFactory(dbType, declaredXtype=None):
39 type, length, xtype = base.sqltypeToVOTable(dbType)
40 if length=='1':
41 length = None
42 return VS.dataType(arraysize=length, xsi_type="vs:SimpleDataType")[
43 _VOTABLE_TO_SIMPLE_TYPE_MAP.get(type, "char")]
44
45
46 def voTableDataTypeFactory(dbType, declaredXtype=None):
47 type, length, xtype = base.sqltypeToVOTable(dbType)
48 # the following hack is mirrored in //tap; any similar hacks
49 # would have to go there, too.
50 if declaredXtype=="adql:REGION":
51 type, length, xtype = "char", "*", "adql:REGION"
52 return VS.voTableDataType(arraysize=length)[type](extendedType=xtype)
53
54
55 def getForeignKeyForForeignKey(fk, namesInSet):
56 """returns a VS.foreignKey for a rscdef.ForeignKey.
57
58 If the target table's name is not in nameInSet, the foreign key
59 is not created.
60 """
61 targetName = fk.destTableName.lower()
62 if "no-fks-in-tableset" in base.getConfig("future"):
63 if targetName not in namesInSet:
64 return
65 return VS.foreignKey[
66 VS.targetTable[targetName], [
67 VS.fkColumn[
68 VS.fromColumn[fromColName.lower()],
69 VS.targetColumn[toColName.lower()]]
70 for fromColName,toColName in zip(fk.source, fk.dest)]]
71
72
73 def _serializeFloats(stats):
74 """human-format float-typed values in stats.
75
76 Background: XSLT 1 doesn't know about scientific notation, so we can't
77 use format-number when displaying our column statistics through XSL
78 (in vosi.xslt. So, we give out ready-made floats (precision isn't
79 a matter in the statistics values this is used for).
80 """
81 res = {}
82 for k, v in stats.items():
83 try:
84 res[k] = utils.formatFloat(float(v))
85 except ValueError:
86 res[k] = v
87 return res
88
89
90 _STATS_KEY_MAP = {
91 "minValue": "min",
92 "maxValue": "max",
93 }
94 _STATS_FLOATABLE_TYPES = {"double precision", "real"}
95 def getStats(column):
96 """returns a vs:stats element for any statistics annotation found on column.
97 """
98 res = VS.stats()
99
100 stats = column.getStatistics()
101
102 if column.isEnumerated():
103 for opt in column.values.options:
104 res[VS.option(freq=opt.freq)[str(opt.content_)]]
105
106 elif not stats:
107 return None
108
109 for k, v in stats.items():
110 k = _STATS_KEY_MAP.get(k, k)
111 if v is not None:
112 if column.type in _STATS_FLOATABLE_TYPES:
113 asFloat = float(v)
114 if not math.isfinite(asFloat):
115 continue
116 serialised = utils.formatFloat(asFloat)
117 else:
118 serialised = v
119 res[getattr(VS, k)[serialised]]
120
121 return res
122
123
124 def getTableColumnFromColumn(column, typeFactory, vodsStats=True):
125 """returns a VS.column instance for an rscdef.Column instance.
126
127 typeElement is a factory for types that has to accept an internal (SQL)
128 type as child and generate whatever is necessary from that.
129
130 This module contains simpleDataTypeFactory and voTableDataTypeFactory.
131 I'm considering TAP types as deprecated and won't bother with them.
132
133 vodsStats is a temporary thing until the RofR has VODataService
134 1.3 support; remove this argument and the _serializeFloats thing below
135 then.
136 """
137 flags = []
138 if column.isIndexed():
139 flags.append("indexed")
140 if column.isPrimary():
141 flags.append("primary")
142 elif not column.required:
143 flags.append("nullable")
144
145 res = VS.column[
146 VS.name[column.getTAPName()],
147 VS.description[column.description],
148 VS.unit[column.unit],
149 VS.ucd[column.ucd],
150 VS.utype[column.utype],
151 getStats(column) if vodsStats else None,
152 typeFactory(column.type, column.xtype),
153 [VS.flag[f] for f in flags]]
154
155 if not vodsStats:
156 res(**_serializeFloats(column.getStatistics()))
157
158 return res
159
160
161 def getEffectiveTableName(tableDef):
162 """returns the "effective name" of tableDef.
163
164 This is mainly for fudging the names of output tables since,
165 by default, they're ugly (and meaningless on top of that).
166 """
167 if isinstance(tableDef, svcs.OutputTableDef):
168 return "output"
169 else:
170 return tableDef.getQName().lower()
171
172
173 def getTableForTableDef(
174 tableDef, namesInSet, rootElement=VS.table, suppressBodies=False):
175 """returns a VS.table instance for a rscdef.TableDef.
176
177 namesInSet is a set of lowercased qualified table names; we need this
178 to figure out which foreign keys to create.
179 """
180 name = getEffectiveTableName(tableDef)
181
182 # Fake type=output on the basis of the table name. We'll have
183 # to do something sensible here if this "type" thing ever becomes
184 # more meaningful.
185 type = None
186 if name=="output":
187 type = "output"
188
189 res = rootElement(type=type)[
190 VS.name[name],
191 VS.title[base.getMetaText(tableDef, "title", propagate=False)],
192 VS.description[base.getMetaText(tableDef, "description", propagate=True)],
193 VS.utype[base.getMetaText(tableDef, "utype")],
194 VS.nrows[str(tableDef.nrows or "")]]
195
196 vodsStats = "vodataservice13-stats" in base.getConfig("future")
197
198 if not suppressBodies:
199 res[[
200 getTableColumnFromColumn(col, voTableDataTypeFactory, vodsStats)
201 for col in tableDef if not col.hidden], [
202 getForeignKeyForForeignKey(fk, namesInSet)
203 for fk in tableDef.foreignKeys]]
204
205 return res
206
207
208 @functools.lru_cache(1)
209 def _getObscoreStub():
210 """returns a fake table definition for ivoa.obscore used to
211 declare that a data collection is listed in obscore, too.
212 """
213 td = base.makeStruct(rscdef.TableDef, id="obscore",
214 parent_=base.caches.getRD("//obscore"))
215 td.setMeta("description", "This data collection is queryable in"
216 " %s's obscore table."%base.getConfig("web", "sitename"))
217 return td
218
219
220 def _getSchemaRank(rdAndSchema):
221 """returns the rank of a schemas entry.
222
223 This is for sorting the tableset. There's a default of 100000 when
224 there is no rank.
225 """
226 return rdAndSchema[0].getSchemaRank()
227
228
229 def _getTableRank(td):
230 """returns the rank of a table definition.
231
232 This is for sorting the tableset. There's a default of 100000 when
233 there is no rank.
234 """
235 m = td.getMeta("table-rank")
236 if m:
237 return int(m.getContent())
238 return 100000
239
240
241 def _getSchemaMeta(rd):
242 """returns VOResource for the schema metadata of rd.
243 """
244 return [
245 VS.name[rd.schema],
246 VS.title[base.getMetaText(rd, "title")],
247 VS.description[base.getMetaText(rd, "description")],
248 VS.utype[base.getMetaText(rd, "utype", None)],]
249
250
251 def getTablesetForSchemaCollection(
252 schemas, rootElement=VS.tableset, suppressBodies=False):
253 """returns a vs:tableset element from a sequence of (rd, tables) pairs.
254
255 In each pair, rd is used to define a VODataService schema, and tables is
256 a sequence of TableDefs that define the tables within that schema.
257 """
258 # we originalls did not want to report foreign keys into tables
259 # that are not part of the service's tableset. That turned out to
260 # be a bad idea. We still collect the table names given, but feel
261 # free to drop that if it becomes inconvenient.
262 #
263 # While doing that, we also see if we have obscore-published tables.
264 # If so, we want to add an ivoa.obscore stub unless we have obscore
265 # in the tableset already. That, too, is probably a bad idea, and
266 # "obscore published" should be expressed through a relationship
267 # one day.
268 namesInSet, obscorePublished = set(), False
269 for td in itertools.chain(*(tables for rd, tables in schemas)):
270 namesInSet.add(getEffectiveTableName(td).lower())
271 if td.hasProperty("obscoreClause"):
272 obscorePublished = True
273
274 # adding ivoa.obscore at this point is tricky since we want to
275 # avoid having multiple ivoa schemas or obscore tables.
276 # (really, only the last "else" will count in practice)
277 if obscorePublished:
278 for rd, tables in schemas:
279 if rd.schema=='ivoa':
280 for td in tables:
281 if td.getQName().lower()=='ivoa.obscore':
282 break
283 else:
284 tables.append(_getObscoreStub())
285 break
286 else:
287 schemas.append((base.caches.getRD('//obscore'), [_getObscoreStub()]))
288
289 res = rootElement()
290 for rd, tables in sorted(schemas, key=_getSchemaRank):
291 res[VS.schema[
292 _getSchemaMeta(rd),
293 [getTableForTableDef(td, namesInSet, suppressBodies=suppressBodies)
294 for td in sorted(tables, key=_getTableRank)]]]
295 return res
296
297
298 def getTablesetForRD(rd):
299 """returns a VOSI tableset for an entire RD.
300
301 For now, we just publish tables that are ADQL-published. If we need more
302 control here, we should have a property like publishedRenderers on service.
303 """
304 namesInSet = {td.id for td in rd.tables
305 if td.adql and td.adql!="hidden"}
306 if namesInSet:
307 return VS.tableset[
308 VS.schema[
309 _getSchemaMeta(rd),
310 [getTableForTableDef(td, namesInSet)
311 for td in sorted(rd.tables, key=_getTableRank)
312 if td.adql and td.adql!="hidden"]]]
313 return []
314
315
316 class _InternalSchemaStandin(base.MetaMixin):
317 """a place-holder for the RD of a schema-less table (which doesn't
318 have an RD).
319 """
320 schema = "internal"
321 def __init__(self):
322 base.MetaMixin.__init__(self)
323 self.setMeta("title", "Not a Schema")
324 self.setMeta("description",
325 "A helper for virtual and temporary tables")
326
327 def getSchemaRank(self):
328 return 10000
329
330 _INTERNAL_SCHEMA = _InternalSchemaStandin()
331
332
333 def getTablesetForService(
334 resource, rootElement=VS.tableset, suppressBodies=False):
335 """returns a VS.tableset for a service or a published data resource.
336
337 This is for VOSI queries and the generation of registry records.
338 Where it actually works on services, it uses the service's getTableset
339 method to find out the service's table set; if it's passed a TableDef
340 of a DataDescriptor, it will turn these into tablesets.
341
342 Sorry about the name.
343 """
344 if isinstance(resource, rscdef.TableDef):
345 tables = [resource]
346
347 elif isinstance(resource, rscdef.DataDescriptor):
348 tables = [td for td in resource.iterTableDefs()
349 if td.adql and td.adql!="hidden"]
350
351 else:
352 tables = resource.getTableSet()
353
354 if not tables:
355 return rootElement[
356 VS.schema[
357 VS.name["default"]]]
358
359 # it's possible that multiple RDs define the same schema (don't do
360 # that, it's going to cause all kinds of pain). To avoid
361 # generating bad tablesets in that case, we have the separate
362 # account of schema names; the schema meta is random when
363 # more than one RD exists for the schema.
364 bySchema, rdForSchema = {}, {}
365 for t in tables:
366 if t.rd:
367 # it's a DB table that actually is in a schema
368 bySchema.setdefault(t.rd.schema, []).append(t)
369 rdForSchema[t.rd.schema] = t.rd
370 else:
371 # it's some sort of generated thing. Stuff it into "internal";
372 # by VODataService, schema needs a name, and we won't cheat
373 # by making it empty.
374 bySchema.setdefault("internal", []).append(t)
375 rdForSchema["internal"] = _INTERNAL_SCHEMA
376
377 schemas = []
378 for schemaName, tables in sorted(bySchema.items()):
379 schemas.append((rdForSchema[schemaName], tables))
380
381 return getTablesetForSchemaCollection(
382 schemas,
383 rootElement,
384 suppressBodies=suppressBodies)