Debian Codegraph @

gavo/utils/serializers.py

raw
1 """
2 A framework for pluggable serialisation of (python) values.
3
4 This module collects a set of basic (looking primarily towards
5 VOTables) serialiser factories. These are just functions receiving
6 AnnotatedColumn objects and returning either None ("not responsible")
7 or a function taking a value and returning a string. They may change
8 the AnnotatedColumn objects, for instance, when an MJD (float)
9 becomes a datetime.
10
11 These factories are registered in ValueMapperFactoryRegistry classes;
12 the one used for "normal" VOTables is the defaultMFRegistry.
13
14 Most factories are created here. However, some depend on advance
15 functionality not available here; they will be registered on import of the
16 respective modules (for instance, stc).
17
18 In DaCHS, a second such factory registry is created in web.htmltable.
19 """
20
21 #c Copyright 2008-2025, the GAVO project <[email protected]>
22 #c
23 #c This program is free software, covered by the GNU GPL. See the
24 #c COPYING file in the source distribution.
25
26
27 import datetime
28 import re
29
30 from gavo.utils import algotricks
31 from gavo.utils import typeconversions
32 from gavo.utils.pgsphere import SPoint
33 from gavo.utils.pgsphere import SCircle
34
35 from gavo.utils.dachstypes import (Any, Callable, List, Optional, Tuple,
36 Union)
37
38
39 class AnnotatedColumn(object):
40 """A collection of annotations for a column.
41
42 ColumnAnntotations are constructed with columns and retain a
43 reference to them ("original").
44
45 In addition, they provide a getitem/setitem interface to a
46 dictionary that contains "digested" information on the column.
47 This dictionary serves as an accumulator for information useful
48 during the serialization process.
49
50 The main reason for this class is that Columns are supposed to be
51 immutable; thus, any ephemeral information needs to be kept in a
52 different place. In particular, the mapper factories receive such
53 annotations.
54
55 As a special service to coerce internal tables to external standards,
56 you can pass a votCast dictionary to AnnotatedColumn. Give any
57 key/value pairs in there to override what AnnotatedColumn guesses
58 or infers. This is used to force the sometimes a bit funky
59 SCS/SIAP types to standard values.
60
61 The castMapperFactory enabled by default checks for the presence of
62 a castFunction in an AnnotatedColumn. If it is there, it will be used
63 for mapping the values, so this is another thing you can have in votCast.
64
65 The SerManager tries to obtain votCasts from a such-named
66 attribute on the table passed in.
67
68 Though of course clients can access original, the mapping facets should
69 only be accessed through getitem/setitem since they may be updated
70 wrt what is in original.
71
72 Attributes available via the setitem/getitem interface include:
73
74 - nullvalue -- a suitable nullvalue for this column, if provided by the
75 column's values or otherwise obtained
76 - name -- a name for the column
77 - dbtype -- the column's database type
78 - xtype -- the column's xtype (e.g., "timestamp")
79 - datatype, arraysize -- a VOTable type for the column
80 - displayHint -- a parsed display hint
81 - note -- a reference to a table not (these get entered by SerManager)
82 - ucd, utype, unit, description -- as for column
83 - id -- a string suitable as XML id (externally managed)
84 - votablewrite would evaluate min and max (but right now nothing adds
85 this)
86 """
87 # I would really like to have column as rscdef.Column, but I don't
88 # want to import rscdef from here. Use ABCs or something here?
89 def __init__(self, column: Any, votCast: Optional[Any] = None) -> None:
90 self.original = column
91 self._initAnnotation()
92 if votCast is not None:
93 self.annotations.update(votCast)
94
95 def _initAnnotation(self) -> None:
96 type, size, xtype = typeconversions.sqltypeToVOTable(
97 self.original.type) # type: ignore
98
99 # the interval xtype clashes with other xtypes (right now, in particular
100 # timestamp; the others aren't orderable). Hence, we need to
101 # be clever with the computation of the new xtype (analogous
102 # code in rscdef.column; we should fix that)
103 if self.original.xtype=="interval":
104 xtype = xtype or self.original.xtype
105 else:
106 xtype = self.original.xtype or xtype
107
108 self.annotations = {
109 "nullvalue": self.original.values and
110 self.original.values.nullLiteral,
111 "name": self.original.key,
112 "dbtype": self.original.type,
113 "xtype": xtype,
114 "datatype": type,
115 "arraysize": size,
116 "displayHint": self.original.displayHint,
117 "note": None,
118 "ucd": self.original.ucd,
119 "utype": self.original.utype,
120 "unit": self.original.unit,
121 "description": self.original.description,
122 # id is managed by SerManager
123 "id": None,
124 "ref": None, # used for legacy COOSYS only
125 }
126
127 def __getitem__(self, key: str) -> dict:
128 return self.annotations[key]
129
130 def __setitem__(self, key: str, value: Any) -> None:
131 self.annotations[key] = value
132
133 def __contains__(self, key: str) -> bool:
134 return key in self.annotations
135
136 def get(self, key: str, default: Optional[Any] = None) -> Any:
137 return self.annotations.get(key, default)
138
139
140 # it would be a lot nicer if we guaranteed certain types from the mappers;
141 # a string, say. But that doesn't work because we have richly typed
142 # formats (VOTable) that want to serialise complex types themselves.
143 # Also, think about DALI geometry mappings: these produce arrays which
144 # may have special syntax even in more naive formats.
145 Mapper = Callable[[Any], Any]
146 MapperFactory = Callable[[AnnotatedColumn], Optional[Mapper]]
147
148
149 class ValueMapperFactoryRegistry(object):
150 """An object clients can ask for functions fixing up values
151 for encoding.
152
153 A mapper factory is just a function that takes an AnnotatedColumn instance.
154 It must return either None (for "I don't know how to make a function for this
155 combination these column properties") or a callable that takes a value
156 of the given type and returns a mapped value.
157
158 To add a mapper, call registerFactory. To find a mapper for a
159 set of column properties, call getMapper -- column properties should
160 be an instance of AnnotatedColumn, but for now a dictionary with the
161 right keys should mostly do.
162
163 Mapper factories are tried in the reverse order of registration,
164 and the first that returns non-None wins, i.e., you should
165 register more general factories first. If no registered mapper declares
166 itself responsible, getMapper returns an identity function. If
167 you want to catch such a situation, you can use something like
168 res = vmfr.getMapper(...); if res is utils.identity ...
169 """
170 def __init__(self, factories: List[MapperFactory] = []) -> None:
171 self.factories = factories[:]
172
173 def clone(self) -> "ValueMapperFactoryRegistry":
174 """returns a clone of the factory.
175
176 This is a copy, i.e., factories added will not change the original.
177 """
178 return self.__class__(self.factories)
179
180 def getFactories(self) -> List[MapperFactory]:
181 """returns the list of factories.
182
183 This is *not* a copy. It may be manipulated to remove or add
184 factories.
185 """
186 return self.factories
187
188 def registerFactory(self, factory: MapperFactory) -> None:
189 self.factories.insert(0, factory)
190
191 def appendFactory(self, factory: MapperFactory) -> None:
192 self.factories.append(factory)
193
194 def getMapper(self, colDesc: AnnotatedColumn) -> Mapper:
195 """returns a mapper for values with the python value instance,
196 according to colDesc.
197
198 This method may change colDesc.
199
200 We do a linear search here, so you shouldn't call this function too
201 frequently.
202 """
203 for factory in self.factories:
204 mapper = factory(colDesc)
205 if mapper:
206 colDesc["winningFactory"] = factory
207 break
208 else:
209 mapper = algotricks.identity
210 return mapper
211
212
213 defaultMFRegistry = ValueMapperFactoryRegistry()
214 registerDefaultMF = defaultMFRegistry.registerFactory
215
216
217 def _timeMapperFactory(annCol: AnnotatedColumn) -> Optional[Mapper]:
218 # XXX TODO: Unify with analogous code in web.htmltable
219 if (annCol["dbtype"]=="time"
220 or annCol["displayHint"].get("type")=="humanTime"):
221 sf = int(annCol["displayHint"].get("sf", 0))
222 fmtStr = "%%02d:%%02d:%%0%d.%df"%(sf+3, sf)
223
224 def mapper(val: Any) -> Optional[str]:
225 if val is None:
226 return val
227 elif isinstance(val, (datetime.time, datetime.datetime)):
228 res = fmtStr%(val.hour, val.minute, val.second)
229 elif isinstance(val, datetime.timedelta):
230 hours = val.seconds//3600
231 minutes = (val.seconds-hours*3600)//60
232 seconds = (val.seconds-hours*3600-minutes*60)+val.microseconds/1e6
233 res = fmtStr%(hours, minutes, seconds)
234 else:
235 return val
236 annCol["datatype"], annCol["arraysize"] = "char", "*"
237 return res
238
239 return mapper
240
241 return None
242 registerDefaultMF(_timeMapperFactory)
243
244
245 def _byteaMapperFactory(colDesc: AnnotatedColumn) -> Optional[Mapper]:
246 if colDesc["dbtype"]=="bytea":
247 # psycopg2 here returns buffers which are painful in some situations.
248 def _(val: str) -> Optional[bytes]:
249 if val is None:
250 return None
251 elif isinstance(val, str):
252 # that's legacy at best, but I don't want to break it just yet
253 return val.encode("iso-8859-1")
254 return bytes(val)
255 return _
256
257 return None
258 registerDefaultMF(_byteaMapperFactory)
259
260
261 GEOMETRY_TYPES = set(["spoint", "spoly", "scircle", "sbox", "smoc"])
262
263 def _pgSphereMapperFactory(colDesc: AnnotatedColumn) -> Optional[Mapper]:
264 """A factory for functions turning pgsphere types to DALI arrays.
265 """
266 # even though the VOTable library can and will do this natively,
267 # we still map this manually right now in order to help non-VOTable
268 # output formats; this will not work (properly) when the output
269 # format doesn't have array support. For these, just create
270 # a new mapper factory for GEOMETRY_TYPES.
271 if not colDesc["dbtype"] in GEOMETRY_TYPES:
272 return None
273
274 def mapper(val: Optional[SPoint]) -> Optional[Tuple[float, float]]:
275 if val is None:
276 return None
277 return val.asDALI()
278
279 colDesc["datatype"], colDesc["arraysize"], colDesc["xtype"
280 ] = typeconversions.sqltypeToVOTable(colDesc["dbtype"]) # type: ignore
281
282 return mapper
283 registerDefaultMF(_pgSphereMapperFactory)
284
285
286 def _legacyGeometryMapperFactory(colDesc: AnnotatedColumn
287 ) -> Optional[Mapper]:
288 """A factory to support TAP 1.0-style (STC-S) geometry maps.
289
290 These are requested through the semi-custom, legacy adql:REGION xtype.
291 """
292 if not colDesc["xtype"] in ["adql:REGION", "adql:POINT"]:
293 return None
294
295 systemString = "UNKNOWNFrame"
296 if colDesc.original.stc:
297 systemString = colDesc.original.stc.astroSystem.spaceFrame.refFrame
298
299 def mapper(val: Union[None, SCircle, SPoint]) -> Optional[str]:
300 if val is None:
301 return None
302 return val.asSTCS(systemString)
303
304 colDesc["datatype"], colDesc["arraysize"] = "char", "*"
305 return mapper
306 registerDefaultMF(_legacyGeometryMapperFactory)
307
308
309 def _castMapperFactory(colDesc: AnnotatedColumn) -> Optional[Mapper]:
310 """is a factory that picks up castFunctions set up by user casts.
311 """
312 if "castFunction" in colDesc:
313 # We probably could tell mypy that castFunction must be a mapper
314 # and that would even be beneficial because that's user-visible
315 # API, but I don't want to enter into typed dicts just yet.
316 return colDesc["castFunction"] # type: ignore
317 return None
318 registerDefaultMF(_castMapperFactory)
319
320
321 def _htmlScrubMapperFactory(colDesc: AnnotatedColumn) -> Optional[Mapper]:
322 if colDesc["displayHint"].get("type")!="keephtml":
323 return None
324 tagPat = re.compile("<[^>]*>")
325 def coder(data):
326 if data:
327 return tagPat.sub("", data)
328 return ""
329 return coder
330 registerDefaultMF(_htmlScrubMapperFactory)
331
332
333 def getMapperRegistry() -> ValueMapperFactoryRegistry:
334 """returns a copy of the default value mapper registry.
335 """
336 return ValueMapperFactoryRegistry(
337 defaultMFRegistry.getFactories())