Debian Codegraph @

gavo/adql/annotations.py

raw
1 """
2 Adding field infos to columns and other objects in an ADQL parse tree.
3
4 When we want to generate VOTables from ADQL queries, we must know types,
5 units, ucds, and the like, and we need to know STC information for
6 all columns in a query.
7
8 To do that, we traverse the parse tree postorder looking for nodes that have
9 an addFieldInfos method (note the plural). These then get called,
10 which causes one of the classes in adql.fieldinfos to be constructed
11 and assigned to the node's fieldInfos attribute. The source for
12 these infos is either an AnnotationContext (and thus typically
13 the user-supplied FieldInfoGetter function) or derived annotations.
14 These are computed by the nodes themselves, using their addFieldInfo
15 (singular!) method.
16 """
17
18 #c Copyright 2008-2025, the GAVO project <[email protected]>
19 #c
20 #c This program is free software, covered by the GNU GPL. See the
21 #c COPYING file in the source distribution.
22
23
24 import contextlib
25
26 from gavo import utils
27 from gavo import stc
28
29
30
31 class AnnotationContext(object):
32 """An context object for the annotation process.
33
34 It is constructed with a FieldInfoGetter implementation
35 and an equivalence policy for STC objects.
36
37 It has errors and warnings attributes consisting of user-exposable
38 error strings accrued during the annotation process.
39
40 The annotation context also manages the namespaces for column reference
41 resolution. It maintains a stack of getters; is is maintained
42 using the customResolver context manager.
43
44 withTables, if passed, must be a sequence of already annotated
45 WithQuery objects.
46
47 Finally, the annotation context provides a ancestors attribute that,
48 at any time, gives a list of the current node's ancestor nodes.
49 """
50 def __init__(self,
51 fieldInfoGetter,
52 equivalencePolicy=stc.defaultPolicy):
53 self.fieldInfoGetter = fieldInfoGetter
54 self.policy = equivalencePolicy
55 self.withTables = {}
56 self.colResolvers = []
57 self.errors, self.warnings = [], []
58 self.ancestors = []
59
60 @contextlib.contextmanager
61 def customResolver(self, getter):
62 """a context manager temporarily installing a different field info
63 getter.
64 """
65 self.colResolvers.append(getter)
66 try:
67 yield
68 finally:
69 self.colResolvers.pop()
70
71 def addWithTable(self, withTable):
72 """adds a nodes.WithQuery to use in column resolution.
73
74 withTable must already be annotated for this to work.
75 """
76 self.fieldInfoGetter.addExtraFieldInfos(
77 withTable.name,
78 withTable.fieldInfos.seq)
79
80 def getFieldInfo(self, colName, tableName):
81 """returns the (colName, fieldInfo) for colName within tableName
82 in the current context.
83 """
84 res = self.colResolvers[-1](colName, tableName)
85 if res is None: # pragma: no cover
86 raise utils.ReportableError("Internal Error: resolver returned NULL for"
87 " %s.%s. Please report this to the [email protected]"
88 " together with the failed query."%(tableName, colName))
89 return res
90
91 def retrieveFieldInfos(self, tableName):
92 """returns a sequence of (column name, adql.FieldInfo) pairs for
93 the table tableName or raises a NotFoundError.
94
95 Really, this calls just the FieldInfoGetter that was passed into
96 the annotation context and hence shares its interface.
97 """
98 return self.fieldInfoGetter(tableName)
99
100
101 def _annotateTraverse(node, context):
102 """does the real tree traversal for annotate.
103 """
104 context.ancestors.append(node)
105 for c in node.iterNodeChildren():
106 _annotateTraverse(c, context)
107 context.ancestors.pop()
108 if hasattr(node, "addFieldInfos"):
109 node.addFieldInfos(context)
110
111
112 def annotate(node, context):
113 """adds annotations to all nodes wanting some.
114
115 This is done by a postorder traversal of the tree, identifying all
116 annotable objects.
117
118 context can be an AnnotationContext instance. You can also just
119 pass in a adql.FieldInfoGetter instance. In that case, annotation
120 runs with the default stc equivalence policy.
121
122 The function returns the context used in any case.
123 """
124 if not isinstance(context, AnnotationContext):
125 context = AnnotationContext(context)
126
127 for wt in node.withTables:
128 _annotateTraverse(wt, context)
129 context.addWithTable(wt)
130
131 _annotateTraverse(node, context)
132 return context
133
134
135 def optimize(node):
136 """iterates postorder over the tree below, calling optimize(stack) methods
137 where they exist.
138 """
139 def recurse(node, stack):
140 stack.append(node)
141 for c in node.iterNodeChildren():
142 recurse(c, stack)
143 stack.pop()
144 if hasattr(node, "optimize"):
145 node.optimize(stack)
146
147 recurse(node, [])
148
149
150 def dumpFieldInfoedTree(tree): # pragma: no cover
151 """dumps an ADQL parse tree, giving the computed annotations.
152
153 For debugging.
154 """
155 import pprint
156 def traverse(node):
157 res = []
158 if hasattr(node, "fieldInfo"):
159 res.append("%s <- %s"%(node.type, repr(node.fieldInfo)))
160 if hasattr(node, "fieldInfos"):
161 res.append("%s -- %s"%(node.type, repr(node.fieldInfos)))
162 res.extend([_f for _f in [traverse(child) for child in
163 node.iterNodeChildren()] if _f])
164 if len(res)==1:
165 return res[0]
166 else:
167 return res
168 pprint.pprint(traverse(tree))