Debian Codegraph @

gavo/adql/fieldinfo.py

raw
1 """
2 Field Infos -- annotations to ADQL parse nodes carrying values.
3
4 To do this, we have a set of naive heuristics how types, ucds, and units
5 behave when such "fields" are combined. Since right now, we don't parse
6 out enough and, at least for ucds and units we don't have enough data
7 to begin with, much of this is conjecture.
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 re
18
19
20 class _CoercNode(object):
21 """An entry in the coercion tree.
22 """
23 def __init__(self, name, children=(), aliases=()):
24 self.name, self.aliases = name, aliases
25 self.parent, self.children = None, children
26 for child in self.children:
27 child.parent = self
28
29 def getAncestorNames(self):
30 if self.parent is None:
31 return [self.name]
32 res = self.parent.getAncestorNames()
33 res.append(self.name)
34 return res
35
36
37 class Coercions(object):
38 """A tree of types that can be used to infer common types.
39
40 The tree is passed in as nested sequences.
41
42 >>> c = Coercions(_CoercNode('bar', (_CoercNode('foo'), _CoercNode('baz',
43 ... (_CoercNode('quux'),)))))
44 >>> c.getSubsuming([])
45 'bar'
46 >>> c.getSubsuming(['foo'])
47 'foo'
48 >>> c.getSubsuming(['foo', 'foo'])
49 'foo'
50 >>> c.getSubsuming(['foo', 'quux'])
51 'bar'
52 >>> c.getSubsuming(['foo', 'weird'])
53 'bar'
54 """
55 def __init__(self, typeTree):
56 self.typesIndex = {}
57 self.root = typeTree
58 def index(node):
59 self.typesIndex[node.name] = node
60 for a in node.aliases:
61 self.typesIndex[a] = node
62 for c in node.children:
63 index(c)
64 index(self.root)
65
66 def _unify(self, n1, n2):
67 """returns the first node that is an ancestor to both n1 and n2.
68 """
69 ancestors = set(n1.getAncestorNames())
70 while n2:
71 if n2.name in ancestors:
72 return n2
73 n2 = n2.parent
74 return self.root
75
76 def getSubsuming(self, typeSeq):
77 """returns the least general type being able to represent all types
78 within typeSeq.
79
80 The method returns the root type for both an empty typeSeq or
81 a typeSeq containing an unknown type. We don't want to fail here,
82 and the "all-encompassing" type should handle any crap.
83 """
84 try:
85 startNodes = [self.typesIndex[t] for t in typeSeq]
86 except KeyError: # don't know at least one type
87 return self.root.name
88 try:
89 return functools.reduce(self._unify, startNodes).name
90 except TypeError: # startNodes is empty
91 return self.root.name
92
93
94 N = _CoercNode
95 _coercions = Coercions(
96 N('raw', (
97 N('unicode', (
98 N('text', (
99 N("double precision", aliases=("double",), children=(
100 N("real", aliases=("float",), children=(
101 N("bigint", (
102 N("integer", aliases=("int",), children=(
103 N("smallint", (
104 N('bytea'),
105 N('boolean'),)),)),)),)),)),
106 N('timestamp', (
107 N('date'),
108 N('time'),)),
109 N('file'),
110 N('box'),
111 N('spoint'),
112 N('scircle'),
113 N('spoly', (
114 N('sbox'),)),
115 ),),),),)))
116 del N
117
118
119 _stringRE = re.compile(r"(?:character varying|varchar|char)\(\d*\)")
120 _arrayRE = re.compile(r"([^[]*)(?:\s*\[[0-9 ]*\])+")
121
122
123 def isArray(type):
124 return _arrayRE.match(type)
125
126
127 def getSubsumingType(sqlTypes):
128 """returns an approximate sql type for a value composed of the types
129 mentioned in the sequence sqlTypes.
130
131 Basically, we have the coercion sequence int -> float -> text,
132 where earlier types get clobbered by later ones. And then there's
133 messy stuff like dates. We don't want to fail here, so if all else
134 fails, we just make it a text.
135
136 Since we don't know what operation is being performed, this can never
137 be accurate; the idea is to come up with something usable to generate
138 VOTables from ADQL results.
139
140 We do arrays (and subsume them by subsuming all types and gluing a []
141 to the result; the char(x) and friends are all subsumed to text.
142
143 All input is supposed to be lower case.
144
145 >>> getSubsumingType(["smallint", "integer"])
146 'integer'
147 >>> getSubsumingType(["real[]", "double precision[]"])
148 'double precision[]'
149 >>> getSubsumingType(["real [ ]", "integer[5]"])
150 'real[]'
151 >>> getSubsumingType(["double precision", "integer[5]"])
152 'double precision[]'
153 """
154 cleanedTypes, wasArray = [], False
155 for type in sqlTypes:
156 if _stringRE.match(type):
157 return "text"
158 mat = _arrayRE.match(type)
159 if mat:
160 type = mat.group(1)
161 wasArray = True
162 cleanedTypes.append(type.strip())
163
164 subsType = _coercions.getSubsuming(cleanedTypes)
165
166 if wasArray:
167 return subsType+"[]"
168 else:
169 return subsType
170
171
172 class FieldInfo(object):
173 """a container for meta information on columns.
174
175 It is constructed with a unit, a ucd and userData. UserData is
176 a sequence of opaque objects. A FieldInfo combined from more than
177 one FieldInfo will have all userDatas of the combined FieldInfos in
178 its userData attribute.
179
180 There's an attribute ignoreTableStats that should be set when table
181 statistics on user data is likely to be off; as of this writing,
182 this is only done for CTEs; if we ever do more sophisticated planning,
183 I expect we'll have to do that whenever there is a SELECT.
184
185 There's also a properties dictionary you can use to set arbitrary
186 keys in. These should in general not be combined but just discarded
187 as a whole when a field info is touched.
188
189 - xtype -- where applicable, write an ADQL xtype.
190 - src.expression -- flattened ADQL this was made from
191 """
192 def __init__(self, type, unit, ucd, userData=(), tainted=False, stc=None,
193 sqlName=None, ignoreTableStats=False):
194 self.type = type
195 self.ucd = ucd
196 self.unit = unit
197 self.stc = stc
198 self.sqlName = sqlName
199 self.userData = userData
200 self.tainted = tainted
201 self.ignoreTableStats = ignoreTableStats
202 self.properties = {}
203
204 def __eq__(self, other):
205 try:
206 return (self.type==other.type
207 and self.ucd==other.ucd
208 and self.unit==other.unit
209 and self.stc==other.stc
210 and self.tainted==other.tainted)
211 except AttributeError:
212 return False
213
214 def __ne__(self, other):
215 return not self==other
216
217 def __repr__(self):
218 return "FieldInfo(%s, %s, %s, %s)"%(
219 repr(self.type),
220 repr(self.unit),
221 repr(self.ucd),
222 repr(self.userData))
223
224 def __hash__(self):
225 # this is used to decide whether two fieldinfos reference the
226 # same thing; our repr is close enough for that decision
227 return hash(repr(self))
228
229 @staticmethod
230 def combineUserData(fi1, fi2):
231 return fi1.userData+fi2.userData
232
233 @staticmethod
234 def combineSTC(fi1, fi2):
235 """tries to find a common STC system for fi1 and fi2.
236
237 Two STC systems are compatible if at least one is None or if they
238 are equal.
239
240 If this method discovers incompatible systems, it will set the
241 stc attribute to "BROKEN".
242 """
243 if fi1.stc is None and fi2.stc is None:
244 return None
245 elif fi2.stc is None or fi1.stc==fi2.stc:
246 return fi1.stc
247 elif fi1.stc is None:
248 return fi2.stc
249 else: # Trouble: stcs not equal but given, warn and blindly return
250 # fi1's stc
251 res = fi1.stc.change()
252 res.broken = ("This STC info is bogus. It is the STC from an"
253 " expression combining two different systems.")
254 return res
255
256 @classmethod
257 def fromMulExpression(cls, opr, fi1, fi2):
258 """returns a new FieldInfo built from the multiplication-like operator opr
259 and the two field infos.
260
261 The unit is unit1 opr unit2 unless we have a dimless (empty unit), in
262 which case we keep the unit but turn the tainted flag on, unless both
263 are empty.
264
265 The ucd is always empty unless it's a simple dimless multiplication,
266 in which case the ucd of the non-dimless is kept (but the info is
267 tainted).
268 """
269 unit1, unit2 = fi1.unit, fi2.unit
270 newUserData = cls.combineUserData(fi1, fi2)
271 stc = cls.combineSTC(fi1, fi2)
272 newType = getSubsumingType([fi1.type, fi2.type])
273
274 if unit1=="" and unit2=="":
275 return cls(newType, "", "", newUserData, stc=stc, tainted=True)
276 elif unit1=="":
277 return cls(newType, unit2, fi2.ucd, newUserData, tainted=True, stc=stc)
278 elif unit2=="":
279 return cls(newType, unit1, fi1.ucd, newUserData, tainted=True, stc=stc)
280 else:
281 if opr=="/":
282 unit2 = "(%s)"%unit2
283 if opr=="*":
284 opr = "."
285 return cls(newType, unit1+opr+unit2, "", newUserData,
286 tainted=True, stc=stc,
287 ignoreTableStats=fi1.ignoreTableStats or fi2.ignoreTableStats)
288
289 @classmethod
290 def fromAddExpression(cls, opr, fi1, fi2, forceType=None):
291 """returns a new FieldInfo built from the addition-like operator
292 opr and the two field infos.
293
294 If both UCDs and units are the same, they are kept. Otherwise,
295 they are cleared and the fieldInfo is tainted.
296 """
297 unit, ucd, taint = "", "", True
298 stc = cls.combineSTC(fi1, fi2)
299 if fi1.unit==fi2.unit:
300 unit = fi1.unit
301 else:
302 # if there's no unit on one but there is one on the other, we're
303 # tentatively accepting the unit given (but it's tainted either way)
304 if fi1.unit and not fi2.unit:
305 unit = fi1.unit
306 elif fi2.unit and not fi1.unit:
307 unit = fi2.unit
308 taint = True
309
310 if fi1.ucd==fi2.ucd:
311 ucd = fi1.ucd
312 else:
313 taint = True
314
315 if forceType is not None:
316 newType = forceType
317 else:
318 newType = getSubsumingType([fi1.type, fi2.type])
319 return cls(newType, unit, ucd, cls.combineUserData(fi1, fi2), taint, stc,
320 ignoreTableStats=fi1.ignoreTableStats or fi2.ignoreTableStats)
321
322 def change(self, **kwargs):
323 consArgs = {"type": self.type, "unit": self.unit, "ucd": self.ucd,
324 "userData": self.userData, "tainted": self.tainted, "stc": self.stc,
325 "ignoreTableStats": self.ignoreTableStats}
326 consArgs.update(kwargs)
327 res = FieldInfo(**consArgs)
328 res.properties = self.properties.copy()
329 return res
330
331
332 def _test(): # pragma: no cover
333 import doctest
334 doctest.testmod()
335
336
337 if __name__=="__main__": # pragma: no cover
338 _test()