Debian Codegraph @

gavo/base/sqlmunge.py

raw
1 """
2 Helpers for building SQL expressions.
3
4 Some of this code is concerned with SQL factories. These are functions
5 with the signature::
6
7 func(field, val, outPars) -> fragment
8
9 outPars is a dictionary that is used to transmit literal values into SQL.
10 The result must be an SQL boolean expression for embedding into a WHERE clause
11 (use None to signal no constraint). Field is the field for which the
12 expression is being generated.
13
14 The factories currently are never called when val is a sequence; there's
15 special hard-coded behaviour for that in getSQLFactory.
16
17 To enter values in outPars, use getSQLKey. Its docstring contains
18 an example that shows how that would look like.
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 import datetime
27
28 from gavo import utils
29 from gavo.stc import mjdToDateTime
30
31 from gavo.utils.dachstypes import (
32 Any, Callable, Dict, List, Optional, Union, TYPE_CHECKING)
33
34 if TYPE_CHECKING:
35 from gavo.svcs import InputKey
36
37
38 plusInfinity = float("Inf")
39 minusInfinity = float("-Inf")
40
41
42 def joinOperatorExpr(operator: str, operands: List[str]) -> Optional[str]:
43 """filters empty operands and joins the rest using operator.
44
45 The function returns an expression string or None for the empty expression.
46 """
47 operands = [_f for _f in operands if _f]
48 if not operands:
49 return None
50 elif len(operands)==1:
51 return operands[0]
52 else:
53 return operator.join([" (%s) "%op for op in operands]).strip()
54
55
56 def getSQLKey(key: str, value: Any, sqlPars: Dict[str, Any]) -> str:
57 """adds value to sqlPars and returns a key for inclusion in a SQL query.
58
59 This function is used to build parameter dictionaries for SQL queries,
60 avoiding overwriting parameters with accidental name clashes. key
61 usually a string matching the identifier pattern or a QuotedName (the
62 latter are going to be horribly mogrified)
63
64 As an extra service, if value is a list, it is turned into a set
65 (rather than the default, which would be an array). We don't believe
66 there's a great need to match against arrays. If you must match against
67 arrays, use numpy arrays.
68
69 >>> sqlPars = {}
70 >>> getSQLKey("foo", 13, sqlPars)
71 'foo0'
72 >>> getSQLKey("foo", 14, sqlPars)
73 'foo1'
74 >>> getSQLKey("foo", 13, sqlPars)
75 'foo0'
76 >>> sqlPars["foo0"], sqlPars["foo1"]; sqlPars = {}
77 (13, 14)
78 >>> "WHERE foo<%%(%s)s OR foo>%%(%s)s"%(getSQLKey("foo", 1, sqlPars),
79 ... getSQLKey("foo", 15, sqlPars))
80 'WHERE foo<%(foo0)s OR foo>%(foo1)s'
81 >>> getSQLKey(utils.QuotedName("-x-"), "x", sqlPars)
82 'id2dx2d0'
83 """
84 if isinstance(key, utils.QuotedName):
85 key = key.makeIdentifier()
86 if isinstance(value, list):
87 value = frozenset(value)
88
89 ct = 0
90 while True:
91 dataKey = "%s%d"%(key, ct)
92 if dataKey not in sqlPars or sqlPars[dataKey]==value:
93 break
94 ct += 1
95 sqlPars[dataKey] = value
96 return dataKey
97
98
99 _REGISTRED_SQL_FACTORIES = {}
100 def registerSQLFactory(
101 type: str,
102 factory: Callable[["InputKey", Any, Dict[str, Any]], Optional[str]]
103 ) -> None:
104 """registers factory as an SQL factory for the type type (a string).
105
106 A SQL factory turns expression of a special type (e.g., vexpr-float
107 for VizieR-like float searches) into literal SQL. They receive
108 an rscdef.OutputField, the expression, and the dictionary of
109 SQL query parameters that they will in general amend (avoid doing
110 value serialisation yourself; you will produce SQL injection surface).
111 """
112 _REGISTRED_SQL_FACTORIES[type] = factory
113
114
115 def _getSQLForSequence(
116 field: "InputKey",
117 val: List[Any],
118 sqlPars: Dict[str, Any]) -> str:
119 if len(val)==0 or (len(val)==1 and val[0] is None):
120 return ""
121 return "%s IN %%(%s)s"%(field.name, getSQLKey(field.name,
122 set(val), sqlPars))
123
124 _FloatLike = Union[float, datetime.date]
125
126 def _convertIfFinite(
127 val: _FloatLike,
128 converter: Callable[[_FloatLike], _FloatLike]) -> _FloatLike:
129 """returns converter(val) if val is a finite float.
130 """
131 if minusInfinity<val<plusInfinity: # type: ignore # date comparison does not hurt here
132 return converter(val)
133 return val
134
135
136 def _getSQLForInterval(
137 field: "InputKey",
138 val: List[_FloatLike],
139 sqlPars: Dict[str, Any]) -> Optional[str]:
140 """returns SQL for DALI intervals.
141
142 This presumes that val is a 2-array of numbers and will return
143 an empty condition otherwise.
144 """
145 if len(val)!=2:
146 return ""
147
148 if field.hasProperty("database-column-is-date"):
149 val = [_convertIfFinite(v, mjdToDateTime) for v in val]
150
151 if val[1]==plusInfinity:
152 return "%s > %%(%s)s"%(field.name, getSQLKey(field.name,
153 val[0], sqlPars))
154
155 elif val[0]==minusInfinity:
156 return "%s < %%(%s)s"%(field.name, getSQLKey(field.name,
157 val[1], sqlPars))
158
159 else:
160 return "%s BETWEEN %%(%s)s AND %%(%s)s"%(field.name,
161 getSQLKey(field.name, val[0], sqlPars),
162 getSQLKey(field.name, val[1], sqlPars))
163
164
165 def _getSQLForSimple(
166 field: "InputKey",
167 val: str,
168 sqlPars: Dict[str, Any]) -> str:
169 return "%s=%%(%s)s"%(field.name, getSQLKey(field.name,
170 val, sqlPars))
171
172
173 def _getSQLFactory(field: "InputKey", value: str
174 ) -> Callable[["InputKey", Any, Dict[str, Any]], Optional[str]]:
175 """returns an SQL factory for matching field's values against value.
176 """
177 if field.xtype=="interval":
178 return _getSQLForInterval
179
180 elif isinstance(value, (list, tuple)):
181 return _getSQLForSequence
182
183 elif field.type in _REGISTRED_SQL_FACTORIES:
184 return _REGISTRED_SQL_FACTORIES[field.type]
185
186 else:
187 return _getSQLForSimple
188
189
190 def getSQLForField(
191 field: "InputKey",
192 inPars: Dict[str, Any],
193 sqlPars: Dict[str, Any]) -> Optional[str]:
194 """returns an SQL fragment for a column-like thing.
195
196 This will be empty if no input in inPars is present. If it is, (a) new
197 key(s) will be left in sqlPars.
198
199 getSQLForField defines the default behaviour; in DBCore condDescs,
200 it can be overridden using phrase makers.
201
202 inPars is supposed to be "typed"; we do not catch general parse errors
203 here.
204 """
205 val = inPars.get(field.name)
206 if val is None:
207 return None
208 # identifying 1-sequences with scalars probably was a bad idea,
209 # but it's hard to get out of that now.
210 if isinstance(val, (list, tuple)) and len(val)==1:
211 val = val[0] # type: ignore # protected polymorphism
212
213 factory = _getSQLFactory(field, val)
214 return factory(field, val, sqlPars)
215
216
217 def _test():
218 import doctest
219 doctest.testmod()
220
221
222 if __name__=="__main__":
223 _test()