Debian Codegraph @

gavo/utils/typeconversions.py

raw
1 """
2 Conversions between type systems.
3
4 The DC software has to deal with a quite a few type systems (see
5 base.typesystems). In general, we keep metadata in the SQL type system;
6 in particular, column's and param's type attribute takes values in that.
7
8 In fact, we use a couple of extensions:
9
10 - file -- this corresponds to a file upload from the web (i.e., a pair
11 (filename, file object)). It would be conceivable to turn this into
12 blobs at some point, but right now we simply don't touch it.
13 - vexpr-float, -text, -date, -mjd -- vizier-like expressions coming in from
14 the web. These are always strings.
15 - pql-X as vexpr, just for DALI-like arguments
16 - raw -- handed right through, whatever it is. For target formats that
17 can't do this, usually strings are used.
18 - unicode -- this is TEXT in the database, but while normal text will
19 be rendered as byte strings in VOTables (with non-ASCII-characters
20 replaced by ?), unicode will become an array of unicodeChars.
21 - geometry types (see utils.pgsphere)
22 -
23
24 This module contains a base class and the VOTable type system conversion,
25 as the VOTable module (that should not depend on base) depends on it.
26 The remaining actual converters are in base.typesystems, as they may depend
27 on details of base. Even the SQL converters should be taken from there
28 when code can rely on gavo.base; this module should be considered an
29 implementation detail.
30 """
31
32 #c Copyright 2008-2025, the GAVO project <[email protected]>
33 #c
34 #c This program is free software, covered by the GNU GPL. See the
35 #c COPYING file in the source distribution.
36
37
38 # XXX TODO: Think how this can be "inverted" by just defining types and
39 # collecting all their aspects in a single class
40
41 import re
42
43 from gavo.utils import excs
44 from gavo.utils.dachstypes import (Dict, Optional, Tuple, Union)
45
46
47 class ConversionError(excs.Error):
48 pass
49
50
51 class FromSQLConverter:
52 """is an abstract base class for type converters from the SQL type system.
53
54 Implementing classes have to provide a dict simpleMap mapping SQL type
55 strings to target types, and a method mapComplex that receives a type
56 and a length (both strings, derived from SQL array types) and either
57 returns None (no matching type) or the target type.
58
59 Implementing classes should also provide a typeSystem attribute giving
60 a short name of the type system they convert to.
61 """
62 _charTypes = set(["character varying", "varchar", "character", "char"])
63
64 simpleMap: Dict = {}
65
66 typeSystem = "<not overridden>"
67
68 def _parseSQLDim(self, subscript: str) -> str:
69 """returns a VOTable-style arraysize specifiation for a SQL subscript
70 expression.
71 """
72 parts = re.findall(r"[\[(](\d*|\*)[\])]", subscript)
73 # In VOTable, we can only have * on the last dimension; we'll error out
74 # for now if we are supposed to make some other type
75 for part in parts[:-1]:
76 if part in ("", "*"):
77 raise ValueError(
78 "Arrays may only have variable length in the last dimension")
79
80 if parts[-1]=="":
81 parts[-1] = "*"
82
83 return "x".join(parts)
84
85 def convert(self, sqlType: str) -> Union[
86 Tuple[str, Optional[str], Optional[str]], # VOTable type, arrsz, xtype
87 Optional[str]]: # Most other type systems have just a single string
88 res = None
89 if sqlType in self.simpleMap:
90 res = self.simpleMap[sqlType]
91 else:
92 # TODO: the RE is too permissive and will let through things
93 # _parseSQLDim cannot parse. Perhaps change the whole thing
94 # to pyparsing?
95 mat = re.match(r"([^[(]*)([\[(]([0-9*\[\]()]*)[\])])$", sqlType)
96 if mat:
97 res = self.mapComplex(mat.group(1), self._parseSQLDim(mat.group(2)))
98
99 if res is None:
100 if sqlType=="raw":
101 return "raw"
102 raise ConversionError("No %s type for %s"%(self.typeSystem, sqlType))
103 return res
104
105 def mapComplex(self, type: str, length: str):
106 return
107
108
109 class ToVOTableConverter(FromSQLConverter):
110 typeSystem = "VOTable"
111
112 simpleMap = {
113 "smallint": ("short", None, None),
114 "integer": ("int", None, None),
115 "bigint": ("long", None, None),
116 "real": ("float", None, None),
117 "boolean": ("boolean", None, None),
118 "double precision": ("double", None, None),
119 "text": ("char", "*", None),
120 "char": ("char", "1", None), # Note: "1" is TOPCAT workaround of 2018.
121 "date": ("char", "*", None),
122 "timestamp": ("char", "19", "timestamp"),
123 "time": ("char", "*", None),
124 "box": ("double", "*", None),
125 "vexpr-mjd": ("char", "*", None),
126 "vexpr-string": ("char", "*", None),
127 "vexpr-date": ("char", "*", None),
128 "vexpr-float": ("char", "*", None),
129 "file": ("bytea", "*", None), # this is for (lame) metadata generation
130 "pql-float": ("char", "*", None),
131 "pql-string": ("char", "*", None),
132 "pql-date": ("char", "*", None),
133 "pql-int": ("char", "*", None),
134 "pql-upload": ("char", "*", None), # (the upload parameter)
135 "raw": ("unsignedByte", "*", None),
136 "bytea": ("unsignedByte", None, None),
137 "spoint": ("double", "2", "point"),
138 "scircle": ("double", "3", "circle"),
139 "spoly": ("double", "*", "polygon"),
140 "smoc": ("char", "*", "moc"),
141 "sbox": ("double", "4", "x-box"),
142 "unicode": ("unicodeChar", "*", None),
143 "int4range": ("int", "2", "interval"),
144 "json": ("char", "*", "json"),
145 "jsonb": ("char", "*", "json"),
146 }
147
148 def mapComplex(self, type: str, length: Optional[str]
149 ) -> Tuple[str, Optional[str], Optional[str]]:
150 if length=='':
151 length = '*'
152
153 if type in self._charTypes:
154 return "char", length, None
155
156 # consequence of TOPCAT workaround as of 2018
157 if type=="char" and length=='1':
158 length = None
159
160 # timestamp and interval both need xtype, and that's not really defined.
161 # Oh, madness. Do a secret handshake with the encoder for custom
162 # behaviour.
163 if type=="timestamp" and length=="2":
164 return "char", "19x2", "timestamp-interval"
165
166 if length is not None:
167 # Special handling for arrays of something
168 if type=="bytea":
169 return ("unsignedByte", '*', None)
170 # we may leave a leading * there, which upstream would have
171 # to fix (oh, madness)
172
173 try:
174 t, l, xtype = self.simpleMap[type]
175 except KeyError:
176 raise excs.StructureError(
177 f"Cannot infer a VOTable type for '{type}'")
178
179 if l is None:
180 newLength = length
181 else:
182 newLength = "%sx%s"%(l, length)
183
184 return (t, newLength, xtype)
185
186 raise NotImplementedError(
187 "VOTable mapComplex cannot handle %s[%s]"%(type, length))
188
189
190 class FromVOTableConverter(object):
191 typeSystem = "db"
192
193 simpleMap = {
194 ("short", '1'): "smallint",
195 ("int", '1'): "integer",
196 ("long", '1'): "bigint",
197 ("float", '1'): "real",
198 ("boolean", '1'): "boolean",
199 ("double", '1'): "double precision",
200 ("char", "*"): "text",
201 ("char", '1'): "char",
202 ("unsignedByte", '1'): "smallint",
203 ("raw", '1'): "raw",
204 }
205
206 xtypeMap: Dict[str, str] = {
207 "adql:POINT": "spoint",
208 "adql:REGION": "spoly",
209 "adql:TIMESTAMP": "timestamp",
210 "timestamp": "timestamp",
211 "point": "spoint",
212 "circle": "scircle",
213 "polygon": "spoly",
214 "moc": "smoc",
215 "x-box": "sbox",
216 "json": "json",
217 "jsonb": "json",
218 }
219
220 def convert(self,
221 type: str,
222 arraysize: Optional[str],
223 xtype: Optional[str] = None) -> str:
224 if xtype is not None and xtype in self.xtypeMap:
225 return self.xtypeMap[xtype]
226 if arraysize=="1" or arraysize=="" or arraysize is None:
227 arraysize = "1"
228 if (type, arraysize) in self.simpleMap:
229 return self.simpleMap[type, arraysize]
230 else:
231 return self.mapComplex(type, arraysize)
232
233 def mapComplex(self, type: str, arraysize: str) -> str:
234 if arraysize=="*":
235 arraysize = ""
236 if type=="char":
237 return "text"
238 if type=="unicodeChar":
239 return "unicode"
240 if type=="unsignedByte" and arraysize!="1":
241 return "bytea[]"
242 if (type, '1') in self.simpleMap:
243 return "%s[%s]"%(self.simpleMap[type, '1'], arraysize)
244 raise ConversionError("No SQL type for %s, %s"%(type, arraysize))
245
246
247 sqltypeToVOTable = ToVOTableConverter().convert
248 voTableToSQLType = FromVOTableConverter().convert