Debian Codegraph @

gavo/svcs/outputdef.py

raw
1 """
2 Output tables and their components.
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 fnmatch
12
13 from gavo import base
14 from gavo import rscdef
15 from gavo import utils
16
17 _EMPTY_TABLE = base.makeStruct(rscdef.TableDef, id="<builtin empty table>")
18 _EMPTY_TABLE.getFullId = lambda: None
19
20
21 class OutputField(rscdef.Column):
22 """A column for defining the output of a service.
23
24 It adds some attributes useful for rendering results, plus functionality
25 specific to certain cores.
26
27 The optional formatter overrides the standard formatting code in HTML
28 (which is based on units, ucds, and displayHints). You receive
29 the item from the database as data and must return a string or
30 t.w.template stan. In addition to the standard `Functions available for
31 row makers`_ you have queryMeta and t.w.template's tags in T.
32
33 Here's an example for generating a link to another service using this
34 facility::
35
36 <outputField name="more"
37 select="array[centerAlpha,centerDelta]" tablehead="More"
38 description="More exposures near the center of this plate">
39 <formatter><![CDATA[
40 return T.a(href=base.makeSitePath("/lswscans/res/positions/q/form?"
41 "POS=%s,%s&SIZE=1&INTERSECT=OVERLAPS&cutoutSize=0.5"
42 "&__nevow_form__=genForm"%tuple(data)
43 ))["More"] ]]>
44 </formatter>
45 </outputField>
46
47 Within the code, in addition to data, you see rd and queryMeta.
48 """
49 name_ = "outputField"
50
51 _formatter = base.UnicodeAttribute("formatter", description="Function"
52 " body to render this item to HTML.", copyable=True, expand=True)
53 _wantsRow = base.BooleanAttribute("wantsRow", description="Does"
54 " formatter expect the entire row rather than the column value only?",
55 copyable="True")
56 _select = base.UnicodeAttribute("select", description="Use this SQL"
57 " fragment rather than field name in the select list of a DB based"
58 " core.", default=base.Undefined, copyable=True, expand=True)
59 _sets = base.StringSetAttribute("sets", description=
60 "Output sets this field should be included in; ALL includes the field"
61 " in all output sets.",
62 copyable=True)
63
64 def __repr__(self):
65 return "<OutputField %s>"%repr(self.name)
66
67 def completeElement(self, ctx):
68 if self.restrictedMode and (
69 self.formatter
70 or self.select):
71 raise base.RestrictedElement(self.name_, hint="formatter and select"
72 " attributes on output fields are not allowed in restricted mode.")
73 if self.select is base.Undefined:
74 self.select = self.name
75 super().completeElement(ctx)
76
77 @classmethod
78 def fromColumn(cls, col):
79 res = cls(None, **col.getAttributes(rscdef.Column))
80 res.stc = col.stc
81 res.dmRoles = rscdef.OldRoles(col.dmRoles)
82 return res.finishElement()
83
84 def expand(self, *args, **kwargs):
85 return self.parent.expand(*args, **kwargs)
86
87
88 class OutputTableDef(rscdef.TableDef):
89 """A table that has outputFields for columns.
90
91 Cores always have one of these, but they are implicitly defined by
92 the underlying database tables in case of dbCores and such.
93
94 Services may define output tables to modify what is coming back from
95 the core. Note that this usually only affects the output to web browsers.
96 To use the output table also through VO protocols (and when producing
97 VOTables, FITS files, and the like), you need to set the service's
98 votableRespectsOutputTable property to True.
99 """
100 name_ = "outputTable"
101
102 # Don't validate meta for these -- while they are children
103 # of validated structures (services), they don't need any
104 # meta at all. This should go as soon as we have a sane
105 # inheritance hierarchy for tables.
106 metaModel = None
107
108 _cols = rscdef.ColumnListAttribute("columns",
109 childFactory=OutputField,
110 description="Output fields for this table.",
111 aliases=["column"],
112 copyable=True)
113
114 _verbLevel = base.IntAttribute("verbLevel",
115 default=None,
116 description="Copy over columns from fromTable not"
117 " more verbose than this.")
118
119 _autocols = base.StringListAttribute("autoCols",
120 description="Column names obtained from fromTable; you can use"
121 " shell patterns into the output table's parent table (in a table"
122 " core, that's the queried table; in a service, it's the core's"
123 " output table) here.")
124
125 def __init__(self, parent, **kwargs):
126 rscdef.TableDef.__init__(self, parent, **kwargs)
127 self.parentTable = None
128 try:
129 # am I in a table-based core?
130 self.parentTable = self.parent.queriedTable
131 except (AttributeError, base.StructureError):
132 # no.
133 pass
134
135 if not self.parentTable:
136 try:
137 # am I in a service with a core with output table?
138 self.parentTable = self.parent.core.outputTable
139 except (AttributeError, base.StructureError):
140 # no.
141 pass
142
143 if not self.parentTable:
144 # no suitable column source, use an empty table:
145 self.parentTable = _EMPTY_TABLE
146
147 self.namePath = None
148
149 def _adoptColumn(self, sourceColumn):
150 # Do not overwrite existing fields here to let the user
151 # override individually
152 try:
153 self.getColumnByName(sourceColumn.name)
154 except base.NotFoundError:
155 self.feedObject("outputField", OutputField.fromColumn(sourceColumn))
156
157 def _addNames(self, ctx, names):
158 # since autoCols is not copyable, we can require
159 # that _addNames only be called when there's a real parse context.
160 if ctx is None:
161 raise base.StructureError("outputTable autocols is"
162 " only available with a parse context")
163 for name in names:
164 self._addName(ctx, name)
165
166 def _addName(self, ctx, name):
167 """adopts a param or column name into the outputTable.
168
169 name may be a reference or a param or column name in the parent
170 table (as determined in the constructor, i.e., the queried table
171 of a core or the output table of a service's core.
172
173 You can also use shell patterns into parent columns.
174 """
175 if utils.identifierPattern.match(name):
176 refOb = ctx.resolveId(name, self)
177 if refOb.name_=="param":
178 self.feedObject("param", refOb.copy(self))
179 else:
180 self._adoptColumn(refOb)
181
182 else:
183 # it's a shell pattern into parent table
184 for col in self.parentTable:
185 if fnmatch.fnmatch(col.name, name):
186 self._adoptColumn(col)
187
188 def completeElement(self, ctx):
189 if self.autoCols:
190 self._addNames(ctx, self.autoCols)
191
192 if self.verbLevel:
193 table = self.parentTable
194 for col in table.columns:
195 if col.verbLevel<=self.verbLevel:
196 self._adoptColumn(col)
197 for par in table.params:
198 if par.verbLevel<=self.verbLevel:
199 self.feedObject("param", par.copy(self))
200
201 super().completeElement(ctx)
202
203 @classmethod
204 def fromColumns(cls, columns, **kwargs):
205 return rscdef.TableDef.fromColumns([OutputField.fromColumn(c)
206 for c in columns])
207
208 @classmethod
209 def fromTableDef(cls, tableDef, ctx=None):
210 res = cls(None, columns=[OutputField.fromColumn(c) for c in tableDef],
211 dupePolicy=tableDef.dupePolicy,
212 primary=tableDef.primary, params=tableDef.params).finishElement(ctx)
213 res.copyMetaFrom(tableDef)
214 return res
215
216 # TODO: we ought to somewhere have an API like
217 #
218 # def getTableForQuery(td, colNames, whereClause, conn):
219 # oTD = svcs.OutputTable.fromColumns(
220 # [td.getColumnByName(n) for n in colNames])
221 # return rsc.TableForDef(ot, rows
222 # =conn.queryToDicts(td.getSimpleQuery(oTD, whereClause))