Debian Codegraph @

gavo/adql/fieldinfos.py

raw
1 """
2 FieldInfos are collections of inferred metadata on the columns present
3 within ADQL relations.
4
5 In generation, this module distinguishes between query-like (select...)
6 and table-like (from table references) field infos. The functions
7 here are called from the addFieldInfo methods of the respective
8 nodes classes.
9 """
10
11 #c Copyright 2008-2025, the GAVO project <[email protected]>
12 #c
13 #c This program is free software, covered by the GNU GPL. See the
14 #c COPYING file in the source distribution.
15
16
17 import weakref
18
19 # TODO: This is a horrible mess. Carefully read the SQL specification,
20 # figure out the actual rules for name resolution and then write an
21 # actual namespace management in annotations.py
22
23 from gavo.adql import common
24
25 def tableNamesMatch(table, toName):
26 """returns true when table could be referred to by toName.
27
28 This means that either the name matches or toName is table's original
29 name.
30
31 toName is a qualified name (i.e., including schema), table is some
32 node that has a tableName.
33 """
34 if not hasattr(table, "tableName"): # the root query specifiation
35 return toName==""
36
37 return (table.tableName.qName==toName.qName
38 or (
39 table.originalTable
40 and
41 table.originalTable==toName.qName))
42
43
44 class FieldInfos:
45 """
46 A base class for field annotations.
47
48 Subclasses of those are attached to physical tables, joins, and
49 subqueries.
50
51 The information on columns is kept in two places:
52
53 - seq -- a sequence of attributes of the columns in the
54 order in which they are selected
55 - columns -- maps column names to attributes or None if a column
56 name is not unique. Column names are normalized by lowercasing here
57 (which, however, does not affect L{utils.QuotedName}s).
58
59 A FieldInfos object is instantiated with the object it will annotate,
60 and the annotation (i.e., setting of the fieldInfos attribute on
61 the parent) will happen during instantiation.
62 """
63 def __init__(self, parent, context):
64 self.seq, self.columns = [], {}
65 self.parent = weakref.proxy(parent)
66
67 def __repr__(self):
68 return "<Column information %s>"%(repr(self.seq))
69
70 def __iter__(self):
71 return iter(self.seq)
72
73 def locateTable(self, refName):
74 """returns a table instance matching the node.TableName refName.
75
76 If no such table is in scope, the function raises a TableNotFound.
77 """
78 if tableNamesMatch(self.parent, refName):
79 return self.parent
80 for t in self.subTables:
81 if tableNamesMatch(t, refName):
82 return t
83 raise common.TableNotFound(refName.qName)
84
85 def addColumn(self, label, info):
86 """adds a new visible column to this info.
87
88 This entails both entering it in self.columns and in self.seq.
89 """
90 label = label.lower()
91 if label in self.columns:
92 if self.columns[label]!=info:
93 self.columns[label] = None # Sentinel for ambiguous names
94 else:
95 self.columns[label] = info
96
97 # we rename database-reserved column names (oid and friends)
98 # these will still be referenced by their original names in the
99 # queries, and these will need to resolve so the translations
100 # can be done. For these columns, we keep their original names
101 # in the column index, too. I've not quite thought through all
102 # cases in which that could fail. Let's hope it's exotic enough
103 # that people won't probe all the dark corners...
104 if info.userData and getattr(info.userData[0], "originalName", None):
105 col = info.userData[0]
106 self.columns[col.originalName] = info
107
108 self.seq.append((label, info))
109
110 def getFieldInfo(self, colName, refName=None):
111 """returns a FieldInfo object for colName.
112
113 Unknown columns result in a ColumnNotFound exception.
114
115 refName is ignored here; we may check that it's identical with
116 parent's name later.
117 """
118 colName = colName.lower()
119 fi = self.columns.get(colName, common.Absent)
120 if fi is common.Absent:
121 raise common.ColumnNotFound(colName)
122 if fi is None:
123 # This can happen on joined tables
124 if refName is not None:
125 return self.locateTable(refName).getFieldInfo(colName)
126 raise common.AmbiguousColumn(colName)
127 return fi
128
129 def assertIsCompatible(self, other):
130 """raises an IncompatibleTables if the FieldInfos other
131 have different length or names from self.
132 """
133 if len(self.seq)!=len(other.seq):
134 raise common.IncompatibleTables("Operands in set operation"
135 " have differing result tuple lengths.", "query")
136
137 for ownCol, otherCol in zip(self.seq, other.seq):
138 if ownCol[0]!=otherCol[0]:
139 raise common.IncompatibleTables("Operands if set operation"
140 " have differing names. First differing name: %s vs. %s"%(
141 ownCol[0], otherCol[0]))
142
143 def copy(self, newParent):
144 """returns a deep copy self, parented to newParent.
145 """
146 newFI = FieldInfos(newParent, None)
147 for label, info in self:
148 newFI.addColumn(label, info.change())
149 return newFI
150
151
152 class TableFieldInfos(FieldInfos):
153 """FieldInfos coming from something that's basically a table in the DB.
154
155 This includes joins.
156
157 To instantiate those, use the makeForNode class method below.
158 """
159 def __init__(self, parent, context):
160 FieldInfos.__init__(self, parent, context)
161 self._collectSubTables(parent, context)
162
163 @classmethod
164 def makeForNode(cls, tableNode, context):
165 """returns a TableFieldInfos instance for an ADQL tableNode.
166
167 context is an AnnotationContext.
168
169 Whatever tableNode actually is, it needs an originalTable
170 attribute which is used to retrieve the column info.
171 """
172 result = cls(tableNode, context)
173
174 if tableNode.originalTable:
175 # add infos for a host table if that's what this is
176 for colName, fieldInfo in context.retrieveFieldInfos(
177 tableNode.originalTable):
178 result.addColumn(colName, fieldInfo)
179
180 # add infos for joined tables as necessary; since we to a postorder
181 # traversal, those have already been annotated.
182 commonColumns = common.computeCommonColumns(tableNode)
183 emittedCommonColumns = set()
184 for jt in getattr(tableNode, "joinedTables", ()):
185 for label, info in jt.fieldInfos.seq:
186 if label in commonColumns:
187 if label not in emittedCommonColumns:
188 result.addColumn(label, info)
189 emittedCommonColumns.add(label)
190 else:
191 result.addColumn(label, info)
192
193 # annotate any join specs present
194 with context.customResolver(result.getFieldInfo):
195 _annotateNodeRecurse(tableNode, context)
196 return result
197
198 def _collectSubTables(self, node, context):
199 self.subTables = list(node.getAllTables())
200
201
202 def _annotateNodeRecurse(node, context):
203 """helps QueryFieldInfos.
204 """
205 for c in node.iterNodeChildren():
206 _annotateNodeRecurse(c, context)
207 if hasattr(node, "addFieldInfo") and node.fieldInfo is None:
208 node.addFieldInfo(context)
209
210
211 class QueryFieldInfos(FieldInfos):
212 """FieldInfos inferred from a FROM clause.
213
214 To instantiate those, use the makeForNode class method below.
215 """
216
217 # enclosingQuery is set non-None when a whereClause is found in the
218 # ancestors in _collectSubTables. It then refers to the query spec
219 # the where clause is a child from. All names from that qs are
220 # also immediately accessible from the current qs.
221 enclosingQuery = None
222
223 def __init__(self, parent, context):
224 FieldInfos.__init__(self, parent, context)
225 self._collectSubTables(parent, context)
226
227 @classmethod
228 def makeForNode(cls, queryNode, context):
229 """cf. TableFieldInfos.makeForNode.
230 """
231 result = cls(queryNode, context)
232
233 # annotate the children of the select clause, using info
234 # from queryNode's queried tables; we must manipulate the context's
235 # name resolution.
236 with context.customResolver(result.getFieldInfoFromSources):
237 for selField in queryNode.getSelectFields():
238 _annotateNodeRecurse(selField, context)
239
240 # annotate the children of the where clause, too -- their types
241 # and such may be needed by morphers
242 with context.customResolver(result.getFieldInfo):
243 if queryNode.whereClause:
244 _annotateNodeRecurse(queryNode.whereClause, context)
245
246 for col in queryNode.getSelectFields():
247 result.addColumn(col.name, col.fieldInfo)
248
249 with context.customResolver(result.getFieldInfo):
250 if queryNode.having:
251 _annotateNodeRecurse(queryNode.having, context)
252 if queryNode.groupby:
253 _annotateNodeRecurse(queryNode.groupby, context)
254
255 return result
256
257 def _getEnclosingQuery(self, context):
258 """returns the enclosing query specification if this is a subquery within
259 a where clause.
260 """
261 ancs = context.ancestors
262 index = len(ancs)-1
263 while index>=0:
264 if ancs[index].type=="whereClause":
265 return ancs[index-1]
266 index -= 1
267
268 def _collectSubTables(self, queryNode, context):
269 self.subTables = list(
270 queryNode.fromClause.tableReference.getAllTables())
271 self.tableReference = queryNode.fromClause.tableReference
272
273 # if we are in a from clause, add its querySpecification, too
274 # (for things like exists(select * from x where a=q.b))
275 encQS = self._getEnclosingQuery(context)
276 if encQS:
277 self.subTables.append(encQS)
278 self.subTables.extend(
279 encQS.fromClause.tableReference.getAllTables())
280 self.enclosingQuery = encQS
281
282 def getFieldInfoFromSources(self, colName, refName=None):
283 """returns a field info for colName from anything in the from clause.
284
285 That is, the columns in the select clause are ignored. Use this to
286 resolve expressions from the queries' select clause.
287
288 See getFieldInfo for refName
289 """
290 colName = colName.lower()
291 matched = []
292 if refName is None:
293 # no explicit table reference, in immediate table
294 subCols = self.tableReference.fieldInfos.columns
295 if colName in subCols and subCols[colName]:
296 matched.append(subCols[colName])
297 if self.enclosingQuery:
298 subCols = (self.enclosingQuery.fromClause.
299 tableReference.fieldInfos.columns)
300 if colName in subCols and subCols[colName]:
301 matched.append(subCols[colName])
302
303 else:
304 # locate an appropriate table
305 subCols = self.locateTable(refName).fieldInfos.columns
306 if colName in subCols and subCols[colName]:
307 matched.append(subCols[colName])
308
309 # TODO: make qualified names here and use them in JoindTable.getAllFields
310 return common.getUniqueMatch(matched, colName)
311
312 def getFieldInfo(self, colName, refName=None):
313 """returns a field info for colName in self or any tables this
314 query takes columns from.
315
316 To do that, it collects all fields of colName in self and subTables and
317 returns the matching field if there's exactly one. Otherwise, it
318 will raise ColumnNotFound or AmbiguousColumn.
319
320 If the node.TableName instance refName is given, the search will be
321 restricted to the matching tables.
322 """
323 ownMatch = None
324 if refName is None:
325 ownMatch = self.columns.get(colName, None)
326 if ownMatch:
327 return ownMatch
328 else:
329 return self.getFieldInfoFromSources(colName, refName)