1 |
2211
|
aaronmk
|
# SQL code generation
|
2 |
|
|
|
3 |
2748
|
aaronmk
|
import copy
|
4 |
3518
|
aaronmk
|
import itertools
|
5 |
2276
|
aaronmk
|
import operator
|
6 |
3158
|
aaronmk
|
from ordereddict import OrderedDict
|
7 |
2568
|
aaronmk
|
import re
|
8 |
2653
|
aaronmk
|
import UserDict
|
9 |
2953
|
aaronmk
|
import warnings
|
10 |
2276
|
aaronmk
|
|
11 |
2667
|
aaronmk
|
import dicts
|
12 |
2953
|
aaronmk
|
import exc
|
13 |
2701
|
aaronmk
|
import iters
|
14 |
|
|
import lists
|
15 |
2360
|
aaronmk
|
import objects
|
16 |
5367
|
aaronmk
|
import regexp
|
17 |
2222
|
aaronmk
|
import strings
|
18 |
2227
|
aaronmk
|
import util
|
19 |
2211
|
aaronmk
|
|
20 |
2587
|
aaronmk
|
##### Names
|
21 |
2499
|
aaronmk
|
|
22 |
2608
|
aaronmk
|
identifier_max_len = 63 # works for both PostgreSQL and MySQL
|
23 |
2587
|
aaronmk
|
|
24 |
2932
|
aaronmk
|
def concat(str_, suffix):
|
25 |
2609
|
aaronmk
|
'''Preserves version so that it won't be truncated off the string, leading
|
26 |
|
|
to collisions.'''
|
27 |
2613
|
aaronmk
|
# Preserve version
|
28 |
2995
|
aaronmk
|
match = re.match(r'^(.*?)((?:(?:#\d+)?\)?)*(?:\.\w+)?(?:::[\w ]+)*)$', str_)
|
29 |
2985
|
aaronmk
|
if match:
|
30 |
|
|
str_, old_suffix = match.groups()
|
31 |
|
|
suffix = old_suffix+suffix
|
32 |
2613
|
aaronmk
|
|
33 |
2932
|
aaronmk
|
return strings.concat(str_, suffix, identifier_max_len)
|
34 |
2587
|
aaronmk
|
|
35 |
2932
|
aaronmk
|
def truncate(str_): return concat(str_, '')
|
36 |
2842
|
aaronmk
|
|
37 |
2575
|
aaronmk
|
def is_safe_name(name):
|
38 |
2583
|
aaronmk
|
'''A name is safe *and unambiguous* if it:
|
39 |
|
|
* contains only *lowercase* word (\w) characters
|
40 |
|
|
* doesn't start with a digit
|
41 |
|
|
* contains "_", so that it's not a keyword
|
42 |
2984
|
aaronmk
|
'''
|
43 |
|
|
return re.match(r'^(?=.*_)(?!\d)[^\WA-Z]+$', name)
|
44 |
2568
|
aaronmk
|
|
45 |
2499
|
aaronmk
|
def esc_name(name, quote='"'):
|
46 |
|
|
return quote + name.replace(quote, quote+quote) + quote
|
47 |
|
|
# doubling an embedded quote escapes it in both PostgreSQL and MySQL
|
48 |
|
|
|
49 |
3320
|
aaronmk
|
def unesc_name(name, quote='"'):
|
50 |
|
|
removed_ref = [False]
|
51 |
|
|
name = strings.remove_prefix(quote, name, removed_ref)
|
52 |
|
|
if removed_ref[0]:
|
53 |
|
|
name = strings.remove_suffix(quote, name, removed_ref)
|
54 |
|
|
assert removed_ref[0]
|
55 |
|
|
name = name.replace(quote+quote, quote)
|
56 |
|
|
return name
|
57 |
|
|
|
58 |
2513
|
aaronmk
|
def clean_name(name): return name.replace('"', '').replace('`', '')
|
59 |
|
|
|
60 |
3041
|
aaronmk
|
def esc_comment(comment): return '/*'+comment.replace('*/', '* /')+'*/'
|
61 |
|
|
|
62 |
3182
|
aaronmk
|
def lstrip(str_):
|
63 |
|
|
'''Also removes comments.'''
|
64 |
|
|
if str_.startswith('/*'): comment, sep, str_ = str_.partition('*/')
|
65 |
|
|
return str_.lstrip()
|
66 |
|
|
|
67 |
2659
|
aaronmk
|
##### General SQL code objects
|
68 |
2219
|
aaronmk
|
|
69 |
2349
|
aaronmk
|
class MockDb:
|
70 |
2503
|
aaronmk
|
def esc_value(self, value): return strings.repr_no_u(value)
|
71 |
2349
|
aaronmk
|
|
72 |
2499
|
aaronmk
|
def esc_name(self, name): return esc_name(name)
|
73 |
2859
|
aaronmk
|
|
74 |
|
|
def col_info(self, col):
|
75 |
|
|
return TypedCol(col.name, '<type>', CustomCode('<default>'), True)
|
76 |
|
|
|
77 |
2349
|
aaronmk
|
mockDb = MockDb()
|
78 |
|
|
|
79 |
2514
|
aaronmk
|
class BasicObject(objects.BasicObject):
|
80 |
|
|
def __str__(self): return clean_name(strings.repr_no_u(self))
|
81 |
|
|
|
82 |
2659
|
aaronmk
|
##### Unparameterized code objects
|
83 |
|
|
|
84 |
2514
|
aaronmk
|
class Code(BasicObject):
|
85 |
3446
|
aaronmk
|
def __init__(self, lang='sql'):
|
86 |
|
|
self.lang = lang
|
87 |
3445
|
aaronmk
|
|
88 |
2658
|
aaronmk
|
def to_str(self, db): raise NotImplementedError()
|
89 |
2349
|
aaronmk
|
|
90 |
2514
|
aaronmk
|
def __repr__(self): return self.to_str(mockDb)
|
91 |
2211
|
aaronmk
|
|
92 |
2269
|
aaronmk
|
class CustomCode(Code):
|
93 |
3445
|
aaronmk
|
def __init__(self, str_):
|
94 |
|
|
Code.__init__(self)
|
95 |
|
|
|
96 |
|
|
self.str_ = str_
|
97 |
2256
|
aaronmk
|
|
98 |
|
|
def to_str(self, db): return self.str_
|
99 |
|
|
|
100 |
2815
|
aaronmk
|
def as_Code(value, db=None):
|
101 |
|
|
'''
|
102 |
|
|
@param db If set, runs db.std_code() on the value.
|
103 |
|
|
'''
|
104 |
3447
|
aaronmk
|
if isinstance(value, Code): return value
|
105 |
|
|
|
106 |
2815
|
aaronmk
|
if util.is_str(value):
|
107 |
|
|
if db != None: value = db.std_code(value)
|
108 |
|
|
return CustomCode(value)
|
109 |
2659
|
aaronmk
|
else: return Literal(value)
|
110 |
|
|
|
111 |
2540
|
aaronmk
|
class Expr(Code):
|
112 |
3445
|
aaronmk
|
def __init__(self, expr):
|
113 |
|
|
Code.__init__(self)
|
114 |
|
|
|
115 |
|
|
self.expr = expr
|
116 |
2540
|
aaronmk
|
|
117 |
|
|
def to_str(self, db): return '('+self.expr.to_str(db)+')'
|
118 |
|
|
|
119 |
3086
|
aaronmk
|
##### Names
|
120 |
|
|
|
121 |
|
|
class Name(Code):
|
122 |
3087
|
aaronmk
|
def __init__(self, name):
|
123 |
3445
|
aaronmk
|
Code.__init__(self)
|
124 |
|
|
|
125 |
3087
|
aaronmk
|
name = truncate(name)
|
126 |
|
|
|
127 |
|
|
self.name = name
|
128 |
3086
|
aaronmk
|
|
129 |
|
|
def to_str(self, db): return db.esc_name(self.name)
|
130 |
|
|
|
131 |
|
|
def as_Name(value):
|
132 |
|
|
if isinstance(value, Code): return value
|
133 |
|
|
else: return Name(value)
|
134 |
|
|
|
135 |
2335
|
aaronmk
|
##### Literal values
|
136 |
|
|
|
137 |
3519
|
aaronmk
|
#### Primitives
|
138 |
|
|
|
139 |
2216
|
aaronmk
|
class Literal(Code):
|
140 |
3445
|
aaronmk
|
def __init__(self, value):
|
141 |
|
|
Code.__init__(self)
|
142 |
|
|
|
143 |
|
|
self.value = value
|
144 |
2213
|
aaronmk
|
|
145 |
|
|
def to_str(self, db): return db.esc_value(self.value)
|
146 |
2211
|
aaronmk
|
|
147 |
2400
|
aaronmk
|
def as_Value(value):
|
148 |
|
|
if isinstance(value, Code): return value
|
149 |
|
|
else: return Literal(value)
|
150 |
|
|
|
151 |
3429
|
aaronmk
|
def is_literal(value): return isinstance(value, Literal)
|
152 |
2216
|
aaronmk
|
|
153 |
3429
|
aaronmk
|
def is_null(value): return is_literal(value) and value.value == None
|
154 |
|
|
|
155 |
3519
|
aaronmk
|
#### Composites
|
156 |
|
|
|
157 |
3521
|
aaronmk
|
class List(Code):
|
158 |
|
|
def __init__(self, values):
|
159 |
3519
|
aaronmk
|
Code.__init__(self)
|
160 |
|
|
|
161 |
|
|
self.values = values
|
162 |
|
|
|
163 |
3521
|
aaronmk
|
def to_str(self, db): return ', '.join((v.to_str(db) for v in self.values))
|
164 |
3519
|
aaronmk
|
|
165 |
3521
|
aaronmk
|
class Tuple(List):
|
166 |
|
|
def __init__(self, *values):
|
167 |
|
|
List.__init__(self, values)
|
168 |
|
|
|
169 |
|
|
def to_str(self, db): return '('+List.to_str(self, db)+')'
|
170 |
|
|
|
171 |
3520
|
aaronmk
|
class Row(Tuple):
|
172 |
|
|
def to_str(self, db): return 'ROW'+Tuple.to_str(self, db)
|
173 |
3519
|
aaronmk
|
|
174 |
3522
|
aaronmk
|
### Arrays
|
175 |
|
|
|
176 |
|
|
class Array(List):
|
177 |
|
|
def __init__(self, values):
|
178 |
|
|
values = map(remove_col_rename, values)
|
179 |
|
|
|
180 |
|
|
List.__init__(self, values)
|
181 |
|
|
|
182 |
|
|
def to_str(self, db): return 'ARRAY['+List.to_str(self, db)+']'
|
183 |
|
|
|
184 |
|
|
def to_Array(value):
|
185 |
|
|
if isinstance(value, Array): return value
|
186 |
|
|
return Array(lists.mk_seq(value))
|
187 |
|
|
|
188 |
2711
|
aaronmk
|
##### Derived elements
|
189 |
|
|
|
190 |
|
|
src_self = object() # tells Col that it is its own source column
|
191 |
|
|
|
192 |
|
|
class Derived(Code):
|
193 |
|
|
def __init__(self, srcs):
|
194 |
2712
|
aaronmk
|
'''An element which was derived from some other element(s).
|
195 |
2711
|
aaronmk
|
@param srcs See self.set_srcs()
|
196 |
|
|
'''
|
197 |
3445
|
aaronmk
|
Code.__init__(self)
|
198 |
|
|
|
199 |
2711
|
aaronmk
|
self.set_srcs(srcs)
|
200 |
|
|
|
201 |
2713
|
aaronmk
|
def set_srcs(self, srcs, overwrite=True):
|
202 |
2711
|
aaronmk
|
'''
|
203 |
|
|
@param srcs (self_type...)|src_self The element(s) this is derived from
|
204 |
|
|
'''
|
205 |
2713
|
aaronmk
|
if not overwrite and self.srcs != (): return # already set
|
206 |
|
|
|
207 |
2711
|
aaronmk
|
if srcs == src_self: srcs = (self,)
|
208 |
|
|
srcs = tuple(srcs) # make Col hashable
|
209 |
|
|
self.srcs = srcs
|
210 |
|
|
|
211 |
|
|
def _compare_on(self):
|
212 |
|
|
compare_on = self.__dict__.copy()
|
213 |
|
|
del compare_on['srcs'] # ignore
|
214 |
|
|
return compare_on
|
215 |
|
|
|
216 |
|
|
def cols_srcs(cols): return lists.uniqify(iters.flatten((v.srcs for v in cols)))
|
217 |
|
|
|
218 |
2335
|
aaronmk
|
##### Tables
|
219 |
|
|
|
220 |
2712
|
aaronmk
|
class Table(Derived):
|
221 |
2991
|
aaronmk
|
def __init__(self, name, schema=None, srcs=(), is_temp=False):
|
222 |
2211
|
aaronmk
|
'''
|
223 |
|
|
@param schema str|None (for no schema)
|
224 |
2712
|
aaronmk
|
@param srcs (Table...)|src_self See Derived.set_srcs()
|
225 |
2211
|
aaronmk
|
'''
|
226 |
2712
|
aaronmk
|
Derived.__init__(self, srcs)
|
227 |
|
|
|
228 |
3091
|
aaronmk
|
if util.is_str(name): name = truncate(name)
|
229 |
2843
|
aaronmk
|
|
230 |
2211
|
aaronmk
|
self.name = name
|
231 |
|
|
self.schema = schema
|
232 |
2991
|
aaronmk
|
self.is_temp = is_temp
|
233 |
5524
|
aaronmk
|
self.order_by = None
|
234 |
3000
|
aaronmk
|
self.index_cols = {}
|
235 |
2211
|
aaronmk
|
|
236 |
2348
|
aaronmk
|
def to_str(self, db):
|
237 |
|
|
str_ = ''
|
238 |
3088
|
aaronmk
|
if self.schema != None: str_ += as_Name(self.schema).to_str(db)+'.'
|
239 |
|
|
str_ += as_Name(self.name).to_str(db)
|
240 |
2348
|
aaronmk
|
return str_
|
241 |
2336
|
aaronmk
|
|
242 |
|
|
def to_Table(self): return self
|
243 |
3000
|
aaronmk
|
|
244 |
|
|
def _compare_on(self):
|
245 |
|
|
compare_on = Derived._compare_on(self)
|
246 |
5524
|
aaronmk
|
del compare_on['order_by'] # ignore
|
247 |
3000
|
aaronmk
|
del compare_on['index_cols'] # ignore
|
248 |
|
|
return compare_on
|
249 |
2211
|
aaronmk
|
|
250 |
2835
|
aaronmk
|
def is_underlying_table(table):
|
251 |
|
|
return isinstance(table, Table) and table.to_Table() is table
|
252 |
2832
|
aaronmk
|
|
253 |
4114
|
aaronmk
|
class NoUnderlyingTableException(Exception):
|
254 |
|
|
def __init__(self, ref):
|
255 |
|
|
Exception.__init__(self, 'for: '+strings.as_tt(strings.urepr(ref)))
|
256 |
|
|
self.ref = ref
|
257 |
2902
|
aaronmk
|
|
258 |
|
|
def underlying_table(table):
|
259 |
|
|
table = remove_table_rename(table)
|
260 |
3532
|
aaronmk
|
if table != None and table.srcs:
|
261 |
|
|
table, = table.srcs # for derived tables or row vars
|
262 |
4114
|
aaronmk
|
if not is_underlying_table(table): raise NoUnderlyingTableException(table)
|
263 |
2902
|
aaronmk
|
return table
|
264 |
|
|
|
265 |
2776
|
aaronmk
|
def as_Table(table, schema=None):
|
266 |
2270
|
aaronmk
|
if table == None or isinstance(table, Code): return table
|
267 |
2776
|
aaronmk
|
else: return Table(table, schema)
|
268 |
2219
|
aaronmk
|
|
269 |
3101
|
aaronmk
|
def suffixed_table(table, suffix):
|
270 |
3128
|
aaronmk
|
table = copy.copy(table) # don't modify input!
|
271 |
|
|
table.name = concat(table.name, suffix)
|
272 |
|
|
return table
|
273 |
2707
|
aaronmk
|
|
274 |
2336
|
aaronmk
|
class NamedTable(Table):
|
275 |
|
|
def __init__(self, name, code, cols=None):
|
276 |
|
|
Table.__init__(self, name)
|
277 |
|
|
|
278 |
3016
|
aaronmk
|
code = as_Table(code)
|
279 |
2741
|
aaronmk
|
if not isinstance(code, (Table, FunctionCall, Expr)): code = Expr(code)
|
280 |
3020
|
aaronmk
|
if cols != None: cols = [to_name_only_col(c).to_Col() for c in cols]
|
281 |
2336
|
aaronmk
|
|
282 |
|
|
self.code = code
|
283 |
|
|
self.cols = cols
|
284 |
|
|
|
285 |
|
|
def to_str(self, db):
|
286 |
3026
|
aaronmk
|
str_ = self.code.to_str(db)
|
287 |
|
|
if str_.find('\n') >= 0: whitespace = '\n'
|
288 |
|
|
else: whitespace = ' '
|
289 |
|
|
str_ += whitespace+'AS '+Table.to_str(self, db)
|
290 |
2742
|
aaronmk
|
if self.cols != None:
|
291 |
|
|
str_ += ' ('+(', '.join((c.to_str(db) for c in self.cols)))+')'
|
292 |
2336
|
aaronmk
|
return str_
|
293 |
|
|
|
294 |
|
|
def to_Table(self): return Table(self.name)
|
295 |
|
|
|
296 |
2753
|
aaronmk
|
def remove_table_rename(table):
|
297 |
|
|
if isinstance(table, NamedTable): table = table.code
|
298 |
|
|
return table
|
299 |
|
|
|
300 |
2335
|
aaronmk
|
##### Columns
|
301 |
|
|
|
302 |
2711
|
aaronmk
|
class Col(Derived):
|
303 |
2701
|
aaronmk
|
def __init__(self, name, table=None, srcs=()):
|
304 |
2211
|
aaronmk
|
'''
|
305 |
|
|
@param table Table|None (for no table)
|
306 |
2711
|
aaronmk
|
@param srcs (Col...)|src_self See Derived.set_srcs()
|
307 |
2211
|
aaronmk
|
'''
|
308 |
2711
|
aaronmk
|
Derived.__init__(self, srcs)
|
309 |
|
|
|
310 |
3091
|
aaronmk
|
if util.is_str(name): name = truncate(name)
|
311 |
2241
|
aaronmk
|
if util.is_str(table): table = Table(table)
|
312 |
2211
|
aaronmk
|
assert table == None or isinstance(table, Table)
|
313 |
|
|
|
314 |
|
|
self.name = name
|
315 |
|
|
self.table = table
|
316 |
|
|
|
317 |
2989
|
aaronmk
|
def to_str(self, db, for_str=False):
|
318 |
3088
|
aaronmk
|
str_ = as_Name(self.name).to_str(db)
|
319 |
2989
|
aaronmk
|
if for_str: str_ = clean_name(str_)
|
320 |
2933
|
aaronmk
|
if self.table != None:
|
321 |
2989
|
aaronmk
|
table = self.table.to_Table()
|
322 |
3750
|
aaronmk
|
if for_str: str_ = concat(strings.ustr(table), '.'+str_)
|
323 |
2989
|
aaronmk
|
else: str_ = table.to_str(db)+'.'+str_
|
324 |
2211
|
aaronmk
|
return str_
|
325 |
2314
|
aaronmk
|
|
326 |
2989
|
aaronmk
|
def __str__(self): return self.to_str(mockDb, for_str=True)
|
327 |
2933
|
aaronmk
|
|
328 |
2314
|
aaronmk
|
def to_Col(self): return self
|
329 |
2211
|
aaronmk
|
|
330 |
3512
|
aaronmk
|
def is_col(col): return isinstance(col, Col)
|
331 |
2393
|
aaronmk
|
|
332 |
3512
|
aaronmk
|
def is_table_col(col): return is_col(col) and col.table != None
|
333 |
|
|
|
334 |
3000
|
aaronmk
|
def index_col(col):
|
335 |
|
|
if not is_table_col(col): return None
|
336 |
3104
|
aaronmk
|
|
337 |
|
|
table = col.table
|
338 |
|
|
try: name = table.index_cols[col.name]
|
339 |
|
|
except KeyError: return None
|
340 |
|
|
else: return Col(name, table, col.srcs)
|
341 |
2999
|
aaronmk
|
|
342 |
3024
|
aaronmk
|
def is_temp_col(col): return is_table_col(col) and col.table.is_temp
|
343 |
2996
|
aaronmk
|
|
344 |
2563
|
aaronmk
|
def as_Col(col, table=None, name=None):
|
345 |
|
|
'''
|
346 |
|
|
@param name If not None, any non-Col input will be renamed using NamedCol.
|
347 |
|
|
'''
|
348 |
|
|
if name != None:
|
349 |
|
|
col = as_Value(col)
|
350 |
|
|
if not isinstance(col, Col): col = NamedCol(name, col)
|
351 |
2333
|
aaronmk
|
|
352 |
|
|
if isinstance(col, Code): return col
|
353 |
3513
|
aaronmk
|
elif util.is_str(col): return Col(col, table)
|
354 |
|
|
else: return Literal(col)
|
355 |
2260
|
aaronmk
|
|
356 |
3093
|
aaronmk
|
def with_table(col, table):
|
357 |
3105
|
aaronmk
|
if isinstance(col, NamedCol): pass # doesn't take a table
|
358 |
|
|
elif isinstance(col, FunctionCall):
|
359 |
|
|
col = copy.deepcopy(col) # don't modify input!
|
360 |
|
|
col.args[0].table = table
|
361 |
3493
|
aaronmk
|
elif isinstance(col, Col):
|
362 |
3098
|
aaronmk
|
col = copy.copy(col) # don't modify input!
|
363 |
|
|
col.table = table
|
364 |
3093
|
aaronmk
|
return col
|
365 |
|
|
|
366 |
3100
|
aaronmk
|
def with_default_table(col, table):
|
367 |
2747
|
aaronmk
|
col = as_Col(col)
|
368 |
3100
|
aaronmk
|
if col.table == None: col = with_table(col, table)
|
369 |
2747
|
aaronmk
|
return col
|
370 |
|
|
|
371 |
2744
|
aaronmk
|
def set_cols_table(table, cols):
|
372 |
|
|
table = as_Table(table)
|
373 |
|
|
|
374 |
|
|
for i, col in enumerate(cols):
|
375 |
|
|
col = cols[i] = as_Col(col)
|
376 |
|
|
col.table = table
|
377 |
|
|
|
378 |
2401
|
aaronmk
|
def to_name_only_col(col, check_table=None):
|
379 |
|
|
col = as_Col(col)
|
380 |
3020
|
aaronmk
|
if not is_table_col(col): return col
|
381 |
2401
|
aaronmk
|
|
382 |
|
|
if check_table != None:
|
383 |
|
|
table = col.table
|
384 |
|
|
assert table == None or table == check_table
|
385 |
|
|
return Col(col.name)
|
386 |
|
|
|
387 |
2993
|
aaronmk
|
def suffixed_col(col, suffix):
|
388 |
|
|
return Col(concat(col.name, suffix), col.table, col.srcs)
|
389 |
|
|
|
390 |
3516
|
aaronmk
|
def has_srcs(col): return is_col(col) and col.srcs
|
391 |
|
|
|
392 |
3518
|
aaronmk
|
def cross_join_srcs(cols):
|
393 |
|
|
cols = filter(has_srcs, cols) # empty srcs will mess up the cross join
|
394 |
|
|
srcs = [[s.name for s in c.srcs] for c in cols]
|
395 |
|
|
return [Col(','.join(s)) for s in itertools.product(*srcs)]
|
396 |
3514
|
aaronmk
|
|
397 |
2323
|
aaronmk
|
class NamedCol(Col):
|
398 |
2229
|
aaronmk
|
def __init__(self, name, code):
|
399 |
2310
|
aaronmk
|
Col.__init__(self, name)
|
400 |
|
|
|
401 |
3016
|
aaronmk
|
code = as_Value(code)
|
402 |
2229
|
aaronmk
|
|
403 |
|
|
self.code = code
|
404 |
|
|
|
405 |
|
|
def to_str(self, db):
|
406 |
2310
|
aaronmk
|
return self.code.to_str(db)+' AS '+Col.to_str(self, db)
|
407 |
2314
|
aaronmk
|
|
408 |
|
|
def to_Col(self): return Col(self.name)
|
409 |
2229
|
aaronmk
|
|
410 |
2462
|
aaronmk
|
def remove_col_rename(col):
|
411 |
|
|
if isinstance(col, NamedCol): col = col.code
|
412 |
|
|
return col
|
413 |
|
|
|
414 |
2830
|
aaronmk
|
def underlying_col(col):
|
415 |
|
|
col = remove_col_rename(col)
|
416 |
4114
|
aaronmk
|
if not isinstance(col, Col): raise NoUnderlyingTableException(col)
|
417 |
2849
|
aaronmk
|
|
418 |
2902
|
aaronmk
|
return Col(col.name, underlying_table(col.table), col.srcs)
|
419 |
2830
|
aaronmk
|
|
420 |
2703
|
aaronmk
|
def wrap(wrap_func, value):
|
421 |
|
|
'''Wraps a value, propagating any column renaming to the returned value.'''
|
422 |
|
|
if isinstance(value, NamedCol):
|
423 |
|
|
return NamedCol(value.name, wrap_func(value.code))
|
424 |
|
|
else: return wrap_func(value)
|
425 |
|
|
|
426 |
2667
|
aaronmk
|
class ColDict(dicts.DictProxy):
|
427 |
3691
|
aaronmk
|
'''A dict that automatically makes inserted entries Col objects.
|
428 |
|
|
Anything that isn't a column is wrapped in a NamedCol with the key's column
|
429 |
|
|
name by `as_Col(value, name=key.name)`.
|
430 |
|
|
'''
|
431 |
2564
|
aaronmk
|
|
432 |
2645
|
aaronmk
|
def __init__(self, db, keys_table, dict_={}):
|
433 |
3158
|
aaronmk
|
dicts.DictProxy.__init__(self, OrderedDict())
|
434 |
2667
|
aaronmk
|
|
435 |
2645
|
aaronmk
|
keys_table = as_Table(keys_table)
|
436 |
|
|
|
437 |
2642
|
aaronmk
|
self.db = db
|
438 |
2641
|
aaronmk
|
self.table = keys_table
|
439 |
2653
|
aaronmk
|
self.update(dict_) # after setting vars because __setitem__() needs them
|
440 |
2641
|
aaronmk
|
|
441 |
2667
|
aaronmk
|
def copy(self): return ColDict(self.db, self.table, self.inner.copy())
|
442 |
2655
|
aaronmk
|
|
443 |
2667
|
aaronmk
|
def __getitem__(self, key):
|
444 |
|
|
return dicts.DictProxy.__getitem__(self, self._key(key))
|
445 |
2653
|
aaronmk
|
|
446 |
2564
|
aaronmk
|
def __setitem__(self, key, value):
|
447 |
2642
|
aaronmk
|
key = self._key(key)
|
448 |
3639
|
aaronmk
|
if value == None:
|
449 |
|
|
try: value = self.db.col_info(key).default
|
450 |
|
|
except NoUnderlyingTableException: pass # not a table column
|
451 |
2667
|
aaronmk
|
dicts.DictProxy.__setitem__(self, key, as_Col(value, name=key.name))
|
452 |
2564
|
aaronmk
|
|
453 |
2641
|
aaronmk
|
def _key(self, key): return as_Col(key, self.table)
|
454 |
2564
|
aaronmk
|
|
455 |
3519
|
aaronmk
|
##### Definitions
|
456 |
3491
|
aaronmk
|
|
457 |
3469
|
aaronmk
|
class TypedCol(Col):
|
458 |
|
|
def __init__(self, name, type_, default=None, nullable=True,
|
459 |
|
|
constraints=None):
|
460 |
|
|
assert default == None or isinstance(default, Code)
|
461 |
|
|
|
462 |
|
|
Col.__init__(self, name)
|
463 |
|
|
|
464 |
|
|
self.type = type_
|
465 |
|
|
self.default = default
|
466 |
|
|
self.nullable = nullable
|
467 |
|
|
self.constraints = constraints
|
468 |
|
|
|
469 |
|
|
def to_str(self, db):
|
470 |
3481
|
aaronmk
|
str_ = Col.to_str(self, db)+' '+as_Code(self.type).to_str(db)
|
471 |
3469
|
aaronmk
|
if not self.nullable: str_ += ' NOT NULL'
|
472 |
|
|
if self.default != None: str_ += ' DEFAULT '+self.default.to_str(db)
|
473 |
|
|
if self.constraints != None: str_ += ' '+self.constraints
|
474 |
|
|
return str_
|
475 |
|
|
|
476 |
|
|
def to_Col(self): return Col(self.name)
|
477 |
|
|
|
478 |
3488
|
aaronmk
|
class SetOf(Code):
|
479 |
|
|
def __init__(self, type_):
|
480 |
|
|
Code.__init__(self)
|
481 |
|
|
|
482 |
|
|
self.type = type_
|
483 |
|
|
|
484 |
|
|
def to_str(self, db):
|
485 |
|
|
return 'SETOF '+self.type.to_str(db)
|
486 |
|
|
|
487 |
3483
|
aaronmk
|
class RowType(Code):
|
488 |
|
|
def __init__(self, table):
|
489 |
|
|
Code.__init__(self)
|
490 |
|
|
|
491 |
|
|
self.table = table
|
492 |
|
|
|
493 |
|
|
def to_str(self, db):
|
494 |
|
|
return self.table.to_str(db)+'%ROWTYPE'
|
495 |
|
|
|
496 |
3485
|
aaronmk
|
class ColType(Code):
|
497 |
|
|
def __init__(self, col):
|
498 |
|
|
Code.__init__(self)
|
499 |
|
|
|
500 |
|
|
self.col = col
|
501 |
|
|
|
502 |
|
|
def to_str(self, db):
|
503 |
|
|
return self.col.to_str(db)+'%TYPE'
|
504 |
|
|
|
505 |
4935
|
aaronmk
|
class ArrayType(Code):
|
506 |
|
|
def __init__(self, elem_type):
|
507 |
|
|
Code.__init__(self)
|
508 |
|
|
elem_type = as_Code(elem_type)
|
509 |
|
|
|
510 |
|
|
self.elem_type = elem_type
|
511 |
|
|
|
512 |
|
|
def to_str(self, db):
|
513 |
|
|
return self.elem_type.to_str(db)+'[]'
|
514 |
|
|
|
515 |
2524
|
aaronmk
|
##### Functions
|
516 |
|
|
|
517 |
2912
|
aaronmk
|
Function = Table
|
518 |
2911
|
aaronmk
|
as_Function = as_Table
|
519 |
|
|
|
520 |
2691
|
aaronmk
|
class InternalFunction(CustomCode): pass
|
521 |
|
|
|
522 |
3442
|
aaronmk
|
#### Calls
|
523 |
|
|
|
524 |
2941
|
aaronmk
|
class NamedArg(NamedCol):
|
525 |
|
|
def __init__(self, name, value):
|
526 |
|
|
NamedCol.__init__(self, name, value)
|
527 |
|
|
|
528 |
|
|
def to_str(self, db):
|
529 |
|
|
return Col.to_str(self, db)+' := '+self.code.to_str(db)
|
530 |
|
|
|
531 |
2524
|
aaronmk
|
class FunctionCall(Code):
|
532 |
2941
|
aaronmk
|
def __init__(self, function, *args, **kw_args):
|
533 |
2524
|
aaronmk
|
'''
|
534 |
2690
|
aaronmk
|
@param args [Code|literal-value...] The function's arguments
|
535 |
2524
|
aaronmk
|
'''
|
536 |
3445
|
aaronmk
|
Code.__init__(self)
|
537 |
|
|
|
538 |
3016
|
aaronmk
|
function = as_Function(function)
|
539 |
2941
|
aaronmk
|
def filter_(arg): return remove_col_rename(as_Value(arg))
|
540 |
|
|
args = map(filter_, args)
|
541 |
|
|
args += [NamedArg(k, filter_(v)) for k, v in kw_args.iteritems()]
|
542 |
2524
|
aaronmk
|
|
543 |
|
|
self.function = function
|
544 |
|
|
self.args = args
|
545 |
|
|
|
546 |
|
|
def to_str(self, db):
|
547 |
|
|
args_str = ', '.join((v.to_str(db) for v in self.args))
|
548 |
|
|
return self.function.to_str(db)+'('+args_str+')'
|
549 |
|
|
|
550 |
2533
|
aaronmk
|
def wrap_in_func(function, value):
|
551 |
|
|
'''Wraps a value inside a function call.
|
552 |
|
|
Propagates any column renaming to the returned value.
|
553 |
|
|
'''
|
554 |
2703
|
aaronmk
|
return wrap(lambda v: FunctionCall(function, v), value)
|
555 |
2533
|
aaronmk
|
|
556 |
2561
|
aaronmk
|
def unwrap_func_call(func_call, check_name=None):
|
557 |
|
|
'''Unwraps any function call to its first argument.
|
558 |
|
|
Also removes any column renaming.
|
559 |
|
|
'''
|
560 |
|
|
func_call = remove_col_rename(func_call)
|
561 |
|
|
if not isinstance(func_call, FunctionCall): return func_call
|
562 |
|
|
|
563 |
|
|
if check_name != None:
|
564 |
|
|
name = func_call.function.name
|
565 |
|
|
assert name == None or name == check_name
|
566 |
|
|
return func_call.args[0]
|
567 |
|
|
|
568 |
3442
|
aaronmk
|
#### Definitions
|
569 |
|
|
|
570 |
|
|
class FunctionDef(Code):
|
571 |
3471
|
aaronmk
|
def __init__(self, function, return_type, body, params=[], modifiers=None):
|
572 |
3445
|
aaronmk
|
Code.__init__(self)
|
573 |
|
|
|
574 |
3487
|
aaronmk
|
return_type = as_Code(return_type)
|
575 |
3444
|
aaronmk
|
body = as_Code(body)
|
576 |
|
|
|
577 |
3442
|
aaronmk
|
self.function = function
|
578 |
|
|
self.return_type = return_type
|
579 |
|
|
self.body = body
|
580 |
3471
|
aaronmk
|
self.params = params
|
581 |
3456
|
aaronmk
|
self.modifiers = modifiers
|
582 |
3442
|
aaronmk
|
|
583 |
|
|
def to_str(self, db):
|
584 |
3487
|
aaronmk
|
params_str = (', '.join((p.to_str(db) for p in self.params)))
|
585 |
3442
|
aaronmk
|
str_ = '''\
|
586 |
3471
|
aaronmk
|
CREATE FUNCTION '''+self.function.to_str(db)+'''('''+params_str+''')
|
587 |
3487
|
aaronmk
|
RETURNS '''+self.return_type.to_str(db)+'''
|
588 |
3448
|
aaronmk
|
LANGUAGE '''+self.body.lang+'''
|
589 |
3456
|
aaronmk
|
'''
|
590 |
|
|
if self.modifiers != None: str_ += self.modifiers+'\n'
|
591 |
|
|
str_ += '''\
|
592 |
3442
|
aaronmk
|
AS $$
|
593 |
3444
|
aaronmk
|
'''+self.body.to_str(db)+'''
|
594 |
3442
|
aaronmk
|
$$;
|
595 |
|
|
'''
|
596 |
|
|
return str_
|
597 |
|
|
|
598 |
3469
|
aaronmk
|
class FunctionParam(TypedCol):
|
599 |
|
|
def __init__(self, name, type_, default=None, out=False):
|
600 |
|
|
TypedCol.__init__(self, name, type_, default)
|
601 |
|
|
|
602 |
|
|
self.out = out
|
603 |
|
|
|
604 |
|
|
def to_str(self, db):
|
605 |
|
|
str_ = TypedCol.to_str(self, db)
|
606 |
|
|
if self.out: str_ = 'OUT '+str_
|
607 |
|
|
return str_
|
608 |
|
|
|
609 |
|
|
def to_Col(self): return Col(self.name)
|
610 |
|
|
|
611 |
3454
|
aaronmk
|
### PL/pgSQL
|
612 |
|
|
|
613 |
3496
|
aaronmk
|
class ReturnQuery(Code):
|
614 |
|
|
def __init__(self, query):
|
615 |
|
|
Code.__init__(self)
|
616 |
|
|
|
617 |
|
|
query = as_Code(query)
|
618 |
|
|
|
619 |
|
|
self.query = query
|
620 |
|
|
|
621 |
|
|
def to_str(self, db):
|
622 |
|
|
return 'RETURN QUERY\n'+strings.indent(self.query.to_str(db))+';\n'
|
623 |
|
|
|
624 |
3515
|
aaronmk
|
## Exceptions
|
625 |
|
|
|
626 |
3509
|
aaronmk
|
class BaseExcHandler(BasicObject):
|
627 |
|
|
def to_str(self, db, body): raise NotImplementedError()
|
628 |
3510
|
aaronmk
|
|
629 |
|
|
def __repr__(self): return self.to_str(mockDb, '<body>')
|
630 |
3509
|
aaronmk
|
|
631 |
3549
|
aaronmk
|
suppress_exc = 'NULL;\n';
|
632 |
|
|
|
633 |
3554
|
aaronmk
|
reraise_exc = 'RAISE USING ERRCODE = SQLSTATE, MESSAGE = SQLERRM;\n';
|
634 |
|
|
|
635 |
3509
|
aaronmk
|
class ExcHandler(BaseExcHandler):
|
636 |
3454
|
aaronmk
|
def __init__(self, exc, handler=None):
|
637 |
|
|
if handler != None: handler = as_Code(handler)
|
638 |
|
|
|
639 |
|
|
self.exc = exc
|
640 |
|
|
self.handler = handler
|
641 |
|
|
|
642 |
|
|
def to_str(self, db, body):
|
643 |
|
|
body = as_Code(body)
|
644 |
|
|
|
645 |
3467
|
aaronmk
|
if self.handler != None:
|
646 |
|
|
handler_str = '\n'+strings.indent(self.handler.to_str(db), 2)
|
647 |
3549
|
aaronmk
|
else: handler_str = ' '+suppress_exc
|
648 |
3454
|
aaronmk
|
|
649 |
|
|
str_ = '''\
|
650 |
|
|
BEGIN
|
651 |
3467
|
aaronmk
|
'''+strings.indent(body.to_str(db))+'''\
|
652 |
3454
|
aaronmk
|
EXCEPTION
|
653 |
3463
|
aaronmk
|
WHEN '''+self.exc+''' THEN'''+handler_str+'''\
|
654 |
3454
|
aaronmk
|
END;\
|
655 |
|
|
'''
|
656 |
|
|
return str_
|
657 |
|
|
|
658 |
3515
|
aaronmk
|
class NestedExcHandler(BaseExcHandler):
|
659 |
|
|
def __init__(self, *handlers):
|
660 |
|
|
'''
|
661 |
|
|
@param handlers Sorted from outermost to innermost
|
662 |
|
|
'''
|
663 |
|
|
self.handlers = handlers
|
664 |
|
|
|
665 |
|
|
def to_str(self, db, body):
|
666 |
|
|
for handler in reversed(self.handlers): body = handler.to_str(db, body)
|
667 |
|
|
return body
|
668 |
|
|
|
669 |
3503
|
aaronmk
|
class ExcToWarning(Code):
|
670 |
|
|
def __init__(self, return_):
|
671 |
|
|
'''
|
672 |
|
|
@param return_ Statement to return a default value in case of error
|
673 |
|
|
'''
|
674 |
|
|
Code.__init__(self)
|
675 |
|
|
|
676 |
|
|
return_ = as_Code(return_)
|
677 |
|
|
|
678 |
|
|
self.return_ = return_
|
679 |
|
|
|
680 |
|
|
def to_str(self, db):
|
681 |
|
|
return "RAISE WARNING '%', SQLERRM;\n"+self.return_.to_str(db)
|
682 |
|
|
|
683 |
3454
|
aaronmk
|
unique_violation_handler = ExcHandler('unique_violation')
|
684 |
|
|
|
685 |
3555
|
aaronmk
|
# Note doubled "\"s because inside Python string
|
686 |
3468
|
aaronmk
|
plpythonu_error_handler = ExcHandler('internal_error', '''\
|
687 |
3591
|
aaronmk
|
-- Handle PL/Python exceptions
|
688 |
3555
|
aaronmk
|
DECLARE
|
689 |
3595
|
aaronmk
|
matches text[] := regexp_matches(SQLERRM,
|
690 |
|
|
E'^(?:PL/Python: )?(\\\\w+): (.*)$'); -- .* also matches \\n
|
691 |
3555
|
aaronmk
|
exc_name text := matches[1];
|
692 |
|
|
msg text := matches[2];
|
693 |
|
|
BEGIN
|
694 |
3596
|
aaronmk
|
/* Re-raise PL/Python exceptions with the PL/Python prefix removed.
|
695 |
|
|
This allows the exception to be parsed like a native exception.
|
696 |
|
|
Always raise as data_exception so it goes in the errors table. */
|
697 |
3598
|
aaronmk
|
IF exc_name IS NOT NULL THEN
|
698 |
4026
|
aaronmk
|
RAISE data_exception USING MESSAGE = msg;
|
699 |
3595
|
aaronmk
|
-- Re-raise non-PL/Python exceptions
|
700 |
|
|
ELSE
|
701 |
|
|
'''+reraise_exc+'''\
|
702 |
3555
|
aaronmk
|
END IF;
|
703 |
|
|
END;
|
704 |
3468
|
aaronmk
|
''')
|
705 |
|
|
|
706 |
3505
|
aaronmk
|
def data_exception_handler(handler):
|
707 |
|
|
return ExcHandler('data_exception', handler)
|
708 |
|
|
|
709 |
3527
|
aaronmk
|
row_var = Table('row')
|
710 |
|
|
|
711 |
3449
|
aaronmk
|
class RowExcIgnore(Code):
|
712 |
|
|
def __init__(self, row_type, select_query, with_row, cols=None,
|
713 |
3527
|
aaronmk
|
exc_handler=unique_violation_handler, row_var=row_var):
|
714 |
3529
|
aaronmk
|
'''
|
715 |
|
|
@param row_type Ignored if a custom row_var is used.
|
716 |
|
|
@pre If a custom row_var is used, it must already be defined.
|
717 |
|
|
'''
|
718 |
3449
|
aaronmk
|
Code.__init__(self, lang='plpgsql')
|
719 |
|
|
|
720 |
3482
|
aaronmk
|
row_type = as_Code(row_type)
|
721 |
3449
|
aaronmk
|
select_query = as_Code(select_query)
|
722 |
|
|
with_row = as_Code(with_row)
|
723 |
3452
|
aaronmk
|
row_var = as_Table(row_var)
|
724 |
3449
|
aaronmk
|
|
725 |
|
|
self.row_type = row_type
|
726 |
|
|
self.select_query = select_query
|
727 |
|
|
self.with_row = with_row
|
728 |
|
|
self.cols = cols
|
729 |
3455
|
aaronmk
|
self.exc_handler = exc_handler
|
730 |
3452
|
aaronmk
|
self.row_var = row_var
|
731 |
3449
|
aaronmk
|
|
732 |
|
|
def to_str(self, db):
|
733 |
3452
|
aaronmk
|
if self.cols == None: row_vars = [self.row_var]
|
734 |
|
|
else: row_vars = [Col(c.name, self.row_var) for c in self.cols]
|
735 |
3449
|
aaronmk
|
|
736 |
3526
|
aaronmk
|
# Need an EXCEPTION block for each individual row because "When an error
|
737 |
|
|
# is caught by an EXCEPTION clause, [...] all changes to persistent
|
738 |
|
|
# database state within the block are rolled back."
|
739 |
|
|
# This is unfortunate because "A block containing an EXCEPTION clause is
|
740 |
|
|
# significantly more expensive to enter and exit than a block without
|
741 |
|
|
# one."
|
742 |
|
|
# (http://www.postgresql.org/docs/8.3/static/\
|
743 |
|
|
# plpgsql-control-structures.html#PLPGSQL-ERROR-TRAPPING)
|
744 |
3449
|
aaronmk
|
str_ = '''\
|
745 |
3529
|
aaronmk
|
FOR '''+(', '.join((v.to_str(db) for v in row_vars)))+''' IN
|
746 |
|
|
'''+strings.indent(self.select_query.to_str(db))+'''\
|
747 |
|
|
LOOP
|
748 |
|
|
'''+strings.indent(self.exc_handler.to_str(db, self.with_row))+'''\
|
749 |
|
|
END LOOP;
|
750 |
|
|
'''
|
751 |
3533
|
aaronmk
|
if self.row_var == row_var:
|
752 |
3529
|
aaronmk
|
str_ = '''\
|
753 |
3449
|
aaronmk
|
DECLARE
|
754 |
3482
|
aaronmk
|
'''+self.row_var.to_str(db)+''' '''+self.row_type.to_str(db)+''';
|
755 |
3449
|
aaronmk
|
BEGIN
|
756 |
3529
|
aaronmk
|
'''+strings.indent(str_)+'''\
|
757 |
|
|
END;
|
758 |
3449
|
aaronmk
|
'''
|
759 |
|
|
return str_
|
760 |
|
|
|
761 |
2986
|
aaronmk
|
##### Casts
|
762 |
|
|
|
763 |
|
|
class Cast(FunctionCall):
|
764 |
|
|
def __init__(self, type_, value):
|
765 |
3539
|
aaronmk
|
type_ = as_Code(type_)
|
766 |
2986
|
aaronmk
|
value = as_Value(value)
|
767 |
|
|
|
768 |
|
|
self.type_ = type_
|
769 |
|
|
self.value = value
|
770 |
|
|
|
771 |
|
|
def to_str(self, db):
|
772 |
3539
|
aaronmk
|
return 'CAST('+self.value.to_str(db)+' AS '+self.type_.to_str(db)+')'
|
773 |
2986
|
aaronmk
|
|
774 |
3354
|
aaronmk
|
def cast_literal(value):
|
775 |
3429
|
aaronmk
|
if not is_literal(value): return value
|
776 |
3354
|
aaronmk
|
|
777 |
|
|
if util.is_str(value.value): value = Cast('text', value)
|
778 |
|
|
return value
|
779 |
|
|
|
780 |
2335
|
aaronmk
|
##### Conditions
|
781 |
2259
|
aaronmk
|
|
782 |
3350
|
aaronmk
|
class NotCond(Code):
|
783 |
|
|
def __init__(self, cond):
|
784 |
3445
|
aaronmk
|
Code.__init__(self)
|
785 |
|
|
|
786 |
3350
|
aaronmk
|
self.cond = cond
|
787 |
|
|
|
788 |
|
|
def to_str(self, db): return 'NOT '+self.cond.to_str(db)
|
789 |
|
|
|
790 |
2398
|
aaronmk
|
class ColValueCond(Code):
|
791 |
|
|
def __init__(self, col, value):
|
792 |
3445
|
aaronmk
|
Code.__init__(self)
|
793 |
|
|
|
794 |
2398
|
aaronmk
|
value = as_ValueCond(value)
|
795 |
|
|
|
796 |
|
|
self.col = col
|
797 |
|
|
self.value = value
|
798 |
|
|
|
799 |
|
|
def to_str(self, db): return self.value.to_str(db, self.col)
|
800 |
|
|
|
801 |
2577
|
aaronmk
|
def combine_conds(conds, keyword=None):
|
802 |
|
|
'''
|
803 |
|
|
@param keyword The keyword to add before the conditions, if any
|
804 |
|
|
'''
|
805 |
|
|
str_ = ''
|
806 |
|
|
if keyword != None:
|
807 |
|
|
if conds == []: whitespace = ''
|
808 |
|
|
elif len(conds) == 1: whitespace = ' '
|
809 |
|
|
else: whitespace = '\n'
|
810 |
|
|
str_ += keyword+whitespace
|
811 |
|
|
|
812 |
|
|
str_ += '\nAND '.join(conds)
|
813 |
|
|
return str_
|
814 |
|
|
|
815 |
2398
|
aaronmk
|
##### Condition column comparisons
|
816 |
|
|
|
817 |
2514
|
aaronmk
|
class ValueCond(BasicObject):
|
818 |
2213
|
aaronmk
|
def __init__(self, value):
|
819 |
2858
|
aaronmk
|
value = remove_col_rename(as_Value(value))
|
820 |
2213
|
aaronmk
|
|
821 |
|
|
self.value = value
|
822 |
2214
|
aaronmk
|
|
823 |
2216
|
aaronmk
|
def to_str(self, db, left_value):
|
824 |
2214
|
aaronmk
|
'''
|
825 |
2216
|
aaronmk
|
@param left_value The Code object that the condition is being applied on
|
826 |
2214
|
aaronmk
|
'''
|
827 |
|
|
raise NotImplemented()
|
828 |
2228
|
aaronmk
|
|
829 |
2514
|
aaronmk
|
def __repr__(self): return self.to_str(mockDb, '<left_value>')
|
830 |
2211
|
aaronmk
|
|
831 |
|
|
class CompareCond(ValueCond):
|
832 |
|
|
def __init__(self, value, operator='='):
|
833 |
2222
|
aaronmk
|
'''
|
834 |
|
|
@param operator By default, compares NULL values literally. Use '~=' or
|
835 |
|
|
'~!=' to pass NULLs through.
|
836 |
|
|
'''
|
837 |
2211
|
aaronmk
|
ValueCond.__init__(self, value)
|
838 |
|
|
self.operator = operator
|
839 |
|
|
|
840 |
2216
|
aaronmk
|
def to_str(self, db, left_value):
|
841 |
2858
|
aaronmk
|
left_value = remove_col_rename(as_Col(left_value))
|
842 |
2216
|
aaronmk
|
|
843 |
2222
|
aaronmk
|
right_value = self.value
|
844 |
|
|
|
845 |
|
|
# Parse operator
|
846 |
2216
|
aaronmk
|
operator = self.operator
|
847 |
2222
|
aaronmk
|
passthru_null_ref = [False]
|
848 |
|
|
operator = strings.remove_prefix('~', operator, passthru_null_ref)
|
849 |
|
|
neg_ref = [False]
|
850 |
|
|
operator = strings.remove_prefix('!', operator, neg_ref)
|
851 |
2844
|
aaronmk
|
equals = operator.endswith('=') # also includes <=, >=
|
852 |
2222
|
aaronmk
|
|
853 |
2825
|
aaronmk
|
# Handle nullable columns
|
854 |
|
|
check_null = False
|
855 |
2844
|
aaronmk
|
if not passthru_null_ref[0]: # NULLs compare equal
|
856 |
2857
|
aaronmk
|
try: left_value = ensure_not_null(db, left_value)
|
857 |
2844
|
aaronmk
|
except ensure_not_null_excs: # fall back to alternate method
|
858 |
|
|
check_null = equals and isinstance(right_value, Col)
|
859 |
2837
|
aaronmk
|
else:
|
860 |
2857
|
aaronmk
|
if isinstance(left_value, EnsureNotNull):
|
861 |
|
|
right_value = ensure_not_null(db, right_value,
|
862 |
|
|
left_value.type) # apply same function to both sides
|
863 |
2825
|
aaronmk
|
|
864 |
2844
|
aaronmk
|
if equals and is_null(right_value): operator = 'IS'
|
865 |
|
|
|
866 |
2825
|
aaronmk
|
left = left_value.to_str(db)
|
867 |
|
|
right = right_value.to_str(db)
|
868 |
|
|
|
869 |
2222
|
aaronmk
|
# Create str
|
870 |
|
|
str_ = left+' '+operator+' '+right
|
871 |
2825
|
aaronmk
|
if check_null:
|
872 |
2578
|
aaronmk
|
str_ = '('+str_+' OR ('+left+' IS NULL AND '+right+' IS NULL))'
|
873 |
|
|
if neg_ref[0]: str_ = 'NOT '+str_
|
874 |
2222
|
aaronmk
|
return str_
|
875 |
2216
|
aaronmk
|
|
876 |
2260
|
aaronmk
|
# Tells as_ValueCond() to assume a non-ValueCond is a literal value
|
877 |
|
|
assume_literal = object()
|
878 |
|
|
|
879 |
|
|
def as_ValueCond(value, default_table=assume_literal):
|
880 |
|
|
if not isinstance(value, ValueCond):
|
881 |
|
|
if default_table is not assume_literal:
|
882 |
2748
|
aaronmk
|
value = with_default_table(value, default_table)
|
883 |
2260
|
aaronmk
|
return CompareCond(value)
|
884 |
2216
|
aaronmk
|
else: return value
|
885 |
2219
|
aaronmk
|
|
886 |
2335
|
aaronmk
|
##### Joins
|
887 |
|
|
|
888 |
2352
|
aaronmk
|
join_same = object() # tells Join the left and right columns have the same name
|
889 |
2260
|
aaronmk
|
|
890 |
2353
|
aaronmk
|
# Tells Join the left and right columns have the same name and are never NULL
|
891 |
|
|
join_same_not_null = object()
|
892 |
|
|
|
893 |
2260
|
aaronmk
|
filter_out = object() # tells Join to filter out rows that match the join
|
894 |
|
|
|
895 |
2514
|
aaronmk
|
class Join(BasicObject):
|
896 |
2746
|
aaronmk
|
def __init__(self, table, mapping={}, type_=None):
|
897 |
2260
|
aaronmk
|
'''
|
898 |
|
|
@param mapping dict(right_table_col=left_table_col, ...)
|
899 |
2352
|
aaronmk
|
* if left_table_col is join_same: left_table_col = right_table_col
|
900 |
2353
|
aaronmk
|
* Note that right_table_col must be a string
|
901 |
|
|
* if left_table_col is join_same_not_null:
|
902 |
|
|
left_table_col = right_table_col and both have NOT NULL constraint
|
903 |
|
|
* Note that right_table_col must be a string
|
904 |
2260
|
aaronmk
|
@param type_ None (for plain join)|str (e.g. 'LEFT')|filter_out
|
905 |
|
|
* filter_out: equivalent to 'LEFT' with the query filtered by
|
906 |
|
|
`table_pkey IS NULL` (indicating no match)
|
907 |
|
|
'''
|
908 |
|
|
if util.is_str(table): table = Table(table)
|
909 |
|
|
assert type_ == None or util.is_str(type_) or type_ is filter_out
|
910 |
|
|
|
911 |
|
|
self.table = table
|
912 |
|
|
self.mapping = mapping
|
913 |
|
|
self.type_ = type_
|
914 |
|
|
|
915 |
2749
|
aaronmk
|
def to_str(self, db, left_table_):
|
916 |
2260
|
aaronmk
|
def join(entry):
|
917 |
|
|
'''Parses non-USING joins'''
|
918 |
|
|
right_table_col, left_table_col = entry
|
919 |
|
|
|
920 |
2353
|
aaronmk
|
# Switch order (right_table_col is on the left in the comparison)
|
921 |
|
|
left = right_table_col
|
922 |
|
|
right = left_table_col
|
923 |
2749
|
aaronmk
|
left_table = self.table
|
924 |
|
|
right_table = left_table_
|
925 |
2353
|
aaronmk
|
|
926 |
2747
|
aaronmk
|
# Parse left side
|
927 |
2748
|
aaronmk
|
left = with_default_table(left, left_table)
|
928 |
2747
|
aaronmk
|
|
929 |
2260
|
aaronmk
|
# Parse special values
|
930 |
2747
|
aaronmk
|
left_on_right = Col(left.name, right_table)
|
931 |
|
|
if right is join_same: right = left_on_right
|
932 |
2353
|
aaronmk
|
elif right is join_same_not_null:
|
933 |
2747
|
aaronmk
|
right = CompareCond(left_on_right, '~=')
|
934 |
2260
|
aaronmk
|
|
935 |
2747
|
aaronmk
|
# Parse right side
|
936 |
2353
|
aaronmk
|
right = as_ValueCond(right, right_table)
|
937 |
2747
|
aaronmk
|
|
938 |
|
|
return right.to_str(db, left)
|
939 |
2260
|
aaronmk
|
|
940 |
2265
|
aaronmk
|
# Create join condition
|
941 |
|
|
type_ = self.type_
|
942 |
2276
|
aaronmk
|
joins = self.mapping
|
943 |
2746
|
aaronmk
|
if joins == {}: join_cond = None
|
944 |
|
|
elif type_ is not filter_out and reduce(operator.and_,
|
945 |
2460
|
aaronmk
|
(v is join_same_not_null for v in joins.itervalues())):
|
946 |
2260
|
aaronmk
|
# all cols w/ USING, so can use simpler USING syntax
|
947 |
2747
|
aaronmk
|
cols = map(to_name_only_col, joins.iterkeys())
|
948 |
|
|
join_cond = 'USING ('+(', '.join((c.to_str(db) for c in cols)))+')'
|
949 |
2757
|
aaronmk
|
else: join_cond = combine_conds(map(join, joins.iteritems()), 'ON')
|
950 |
2260
|
aaronmk
|
|
951 |
2757
|
aaronmk
|
if isinstance(self.table, NamedTable): whitespace = '\n'
|
952 |
|
|
else: whitespace = ' '
|
953 |
|
|
|
954 |
2260
|
aaronmk
|
# Create join
|
955 |
|
|
if type_ is filter_out: type_ = 'LEFT'
|
956 |
2266
|
aaronmk
|
str_ = ''
|
957 |
|
|
if type_ != None: str_ += type_+' '
|
958 |
2757
|
aaronmk
|
str_ += 'JOIN'+whitespace+self.table.to_str(db)
|
959 |
|
|
if join_cond != None: str_ += whitespace+join_cond
|
960 |
2266
|
aaronmk
|
return str_
|
961 |
2349
|
aaronmk
|
|
962 |
2514
|
aaronmk
|
def __repr__(self): return self.to_str(mockDb, '<left_table>')
|
963 |
2424
|
aaronmk
|
|
964 |
|
|
##### Value exprs
|
965 |
|
|
|
966 |
3089
|
aaronmk
|
all_cols = CustomCode('*')
|
967 |
|
|
|
968 |
2737
|
aaronmk
|
default = CustomCode('DEFAULT')
|
969 |
|
|
|
970 |
3090
|
aaronmk
|
row_count = FunctionCall(InternalFunction('COUNT'), all_cols)
|
971 |
2674
|
aaronmk
|
|
972 |
3061
|
aaronmk
|
class Coalesce(FunctionCall):
|
973 |
|
|
def __init__(self, *args):
|
974 |
|
|
FunctionCall.__init__(self, InternalFunction('COALESCE'), *args)
|
975 |
3060
|
aaronmk
|
|
976 |
3062
|
aaronmk
|
class Nullif(FunctionCall):
|
977 |
|
|
def __init__(self, *args):
|
978 |
|
|
FunctionCall.__init__(self, InternalFunction('NULLIF'), *args)
|
979 |
|
|
|
980 |
3706
|
aaronmk
|
null_as_str = Cast('text', 'NULL')
|
981 |
|
|
|
982 |
|
|
def to_text(value): return Coalesce(Cast('text', value), null_as_str)
|
983 |
|
|
|
984 |
2850
|
aaronmk
|
# See <http://www.postgresql.org/docs/8.3/static/datatype-numeric.html>
|
985 |
2958
|
aaronmk
|
null_sentinels = {
|
986 |
|
|
'character varying': r'\N',
|
987 |
|
|
'double precision': 'NaN',
|
988 |
|
|
'integer': 2147483647,
|
989 |
|
|
'text': r'\N',
|
990 |
5498
|
aaronmk
|
'date': 'infinity',
|
991 |
5266
|
aaronmk
|
'timestamp with time zone': 'infinity',
|
992 |
|
|
'taxonrank': 'unknown',
|
993 |
2958
|
aaronmk
|
}
|
994 |
2692
|
aaronmk
|
|
995 |
3061
|
aaronmk
|
class EnsureNotNull(Coalesce):
|
996 |
2850
|
aaronmk
|
def __init__(self, value, type_):
|
997 |
4938
|
aaronmk
|
if isinstance(type_, ArrayType): null = []
|
998 |
|
|
else: null = null_sentinels[type_]
|
999 |
|
|
Coalesce.__init__(self, as_Col(value), Cast(type_, null))
|
1000 |
2850
|
aaronmk
|
|
1001 |
|
|
self.type = type_
|
1002 |
3001
|
aaronmk
|
|
1003 |
|
|
def to_str(self, db):
|
1004 |
|
|
col = self.args[0]
|
1005 |
|
|
index_col_ = index_col(col)
|
1006 |
|
|
if index_col_ != None: return index_col_.to_str(db)
|
1007 |
3061
|
aaronmk
|
return Coalesce.to_str(self, db)
|
1008 |
2850
|
aaronmk
|
|
1009 |
3523
|
aaronmk
|
#### Arrays
|
1010 |
|
|
|
1011 |
3535
|
aaronmk
|
class ArrayMerge(FunctionCall):
|
1012 |
3523
|
aaronmk
|
def __init__(self, sep, array):
|
1013 |
|
|
array = to_Array(array)
|
1014 |
|
|
FunctionCall.__init__(self, InternalFunction('array_to_string'), array,
|
1015 |
|
|
sep)
|
1016 |
|
|
|
1017 |
3537
|
aaronmk
|
def merge_not_null(db, sep, values):
|
1018 |
3707
|
aaronmk
|
return ArrayMerge(sep, map(to_text, values))
|
1019 |
3537
|
aaronmk
|
|
1020 |
2737
|
aaronmk
|
##### Table exprs
|
1021 |
|
|
|
1022 |
|
|
class Values(Code):
|
1023 |
|
|
def __init__(self, values):
|
1024 |
2739
|
aaronmk
|
'''
|
1025 |
|
|
@param values [...]|[[...], ...] Can be one or multiple rows.
|
1026 |
|
|
'''
|
1027 |
3445
|
aaronmk
|
Code.__init__(self)
|
1028 |
|
|
|
1029 |
2739
|
aaronmk
|
rows = values
|
1030 |
|
|
if len(values) >= 1 and not lists.is_seq(values[0]): # only one row
|
1031 |
|
|
rows = [values]
|
1032 |
|
|
for i, row in enumerate(rows):
|
1033 |
|
|
rows[i] = map(remove_col_rename, map(as_Value, row))
|
1034 |
2737
|
aaronmk
|
|
1035 |
2739
|
aaronmk
|
self.rows = rows
|
1036 |
2737
|
aaronmk
|
|
1037 |
|
|
def to_str(self, db):
|
1038 |
3520
|
aaronmk
|
return 'VALUES '+(', '.join((Tuple(*r).to_str(db) for r in self.rows)))
|
1039 |
2737
|
aaronmk
|
|
1040 |
2740
|
aaronmk
|
def NamedValues(name, cols, values):
|
1041 |
2745
|
aaronmk
|
'''
|
1042 |
3048
|
aaronmk
|
@param cols None|[...]
|
1043 |
2745
|
aaronmk
|
@post `cols` will be changed to Col objects with the table set to `name`.
|
1044 |
|
|
'''
|
1045 |
2834
|
aaronmk
|
table = NamedTable(name, Values(values), cols)
|
1046 |
3048
|
aaronmk
|
if cols != None: set_cols_table(table, cols)
|
1047 |
2834
|
aaronmk
|
return table
|
1048 |
2740
|
aaronmk
|
|
1049 |
2674
|
aaronmk
|
##### Database structure
|
1050 |
|
|
|
1051 |
5074
|
aaronmk
|
def is_nullable(db, value):
|
1052 |
5330
|
aaronmk
|
if not is_table_col(value): return is_null(value)
|
1053 |
|
|
try: return db.col_info(value).nullable
|
1054 |
5074
|
aaronmk
|
except NoUnderlyingTableException: return True # not a table column
|
1055 |
|
|
|
1056 |
4442
|
aaronmk
|
text_types = set(['character varying', 'text'])
|
1057 |
4406
|
aaronmk
|
|
1058 |
5334
|
aaronmk
|
def is_text_type(type_): return type_ in text_types
|
1059 |
|
|
|
1060 |
5335
|
aaronmk
|
def is_text_col(db, col): return is_text_type(db.col_info(col).type)
|
1061 |
4442
|
aaronmk
|
|
1062 |
5397
|
aaronmk
|
def canon_type(type_):
|
1063 |
|
|
if type_ in text_types: return 'text'
|
1064 |
|
|
else: return type_
|
1065 |
|
|
|
1066 |
2840
|
aaronmk
|
ensure_not_null_excs = (NoUnderlyingTableException, KeyError)
|
1067 |
|
|
|
1068 |
2851
|
aaronmk
|
def ensure_not_null(db, col, type_=None):
|
1069 |
2840
|
aaronmk
|
'''
|
1070 |
2855
|
aaronmk
|
@param col If type_ is not set, must have an underlying column.
|
1071 |
4488
|
aaronmk
|
@param type_ If set, overrides the underlying column's type and casts the
|
1072 |
|
|
column to it if needed.
|
1073 |
2840
|
aaronmk
|
@return EnsureNotNull|Col
|
1074 |
|
|
@throws ensure_not_null_excs
|
1075 |
|
|
'''
|
1076 |
5329
|
aaronmk
|
col = remove_col_rename(col)
|
1077 |
5332
|
aaronmk
|
|
1078 |
|
|
try: col_type = db.col_info(underlying_col(col)).type
|
1079 |
2855
|
aaronmk
|
except NoUnderlyingTableException:
|
1080 |
5333
|
aaronmk
|
if type_ == None and is_null(col): raise # NULL has no type
|
1081 |
2855
|
aaronmk
|
else:
|
1082 |
5332
|
aaronmk
|
if type_ == None: type_ = col_type
|
1083 |
|
|
elif type_ != col_type: col = Cast(type_, col)
|
1084 |
2855
|
aaronmk
|
|
1085 |
5331
|
aaronmk
|
if is_nullable(db, col):
|
1086 |
2953
|
aaronmk
|
try: col = EnsureNotNull(col, type_)
|
1087 |
|
|
except KeyError, e:
|
1088 |
|
|
# Warn of no null sentinel for type, even if caller catches error
|
1089 |
|
|
warnings.warn(UserWarning(exc.str_(e)))
|
1090 |
|
|
raise
|
1091 |
|
|
|
1092 |
2840
|
aaronmk
|
return col
|
1093 |
3536
|
aaronmk
|
|
1094 |
|
|
def try_mk_not_null(db, value):
|
1095 |
|
|
'''
|
1096 |
|
|
Warning: This function does not guarantee that its result is NOT NULL.
|
1097 |
|
|
'''
|
1098 |
|
|
try: return ensure_not_null(db, value)
|
1099 |
|
|
except ensure_not_null_excs: return value
|
1100 |
5367
|
aaronmk
|
|
1101 |
|
|
##### Expression transforming
|
1102 |
|
|
|
1103 |
|
|
true_expr = 'true'
|
1104 |
|
|
false_expr = 'false'
|
1105 |
|
|
|
1106 |
|
|
true_re = true_expr
|
1107 |
|
|
false_re = false_expr
|
1108 |
|
|
bool_re = r'(?:'+true_re+r'|'+false_re+r')'
|
1109 |
|
|
atom_re = r'(?:'+bool_re+r'|\([^()]*\)'+r')'
|
1110 |
|
|
|
1111 |
|
|
def logic_op_re(op, value_re, expr_re=''):
|
1112 |
|
|
op_re = ' '+op+' '
|
1113 |
|
|
return '(?:'+expr_re+op_re+value_re+'|'+value_re+op_re+expr_re+')'
|
1114 |
|
|
|
1115 |
5370
|
aaronmk
|
not_re = r'\bNOT '
|
1116 |
5372
|
aaronmk
|
not_false_re = not_re+false_re+r'\b'
|
1117 |
|
|
not_true_re = not_re+true_re+r'\b'
|
1118 |
5367
|
aaronmk
|
and_false_re = logic_op_re('AND', false_re, atom_re)
|
1119 |
5370
|
aaronmk
|
and_false_not_true_re = '(?:'+not_true_re+'|'+and_false_re+')'
|
1120 |
5367
|
aaronmk
|
and_true_re = logic_op_re('AND', true_re)
|
1121 |
|
|
or_re = logic_op_re('OR', bool_re)
|
1122 |
|
|
or_and_true_re = '(?:'+and_true_re+'|'+or_re+')'
|
1123 |
|
|
|
1124 |
|
|
def simplify_parens(expr):
|
1125 |
|
|
return regexp.sub_nested(r'\(('+atom_re+')\)', r'\1', expr)
|
1126 |
|
|
|
1127 |
|
|
def simplify_recursive(sub_func, expr):
|
1128 |
|
|
'''
|
1129 |
|
|
@param sub_func See regexp.sub_recursive() sub_func param
|
1130 |
|
|
'''
|
1131 |
5378
|
aaronmk
|
return regexp.sub_recursive(lambda s: sub_func(simplify_parens(s)), expr)
|
1132 |
|
|
# simplify_parens() is also done at end in final iteration
|
1133 |
5367
|
aaronmk
|
|
1134 |
|
|
def simplify_expr(expr):
|
1135 |
|
|
def simplify_logic_ops(expr):
|
1136 |
|
|
total_n = 0
|
1137 |
5371
|
aaronmk
|
expr, n = re.subn(not_false_re, true_re, expr)
|
1138 |
|
|
total_n += n
|
1139 |
5370
|
aaronmk
|
expr, n = re.subn(and_false_not_true_re, false_expr, expr)
|
1140 |
5367
|
aaronmk
|
total_n += n
|
1141 |
|
|
expr, n = re.subn(or_and_true_re, r'', expr)
|
1142 |
|
|
total_n += n
|
1143 |
|
|
return expr, total_n
|
1144 |
|
|
|
1145 |
|
|
expr = expr.replace('(NULL IS NULL)', true_expr)
|
1146 |
|
|
expr = expr.replace('(NULL IS NOT NULL)', false_expr)
|
1147 |
|
|
expr = simplify_recursive(simplify_logic_ops, expr)
|
1148 |
|
|
return expr
|
1149 |
|
|
|
1150 |
|
|
name_re = r'(?:\w+|(?:"[^"]*")+)'
|
1151 |
|
|
|
1152 |
|
|
def parse_expr_col(str_):
|
1153 |
|
|
match = re.match(r'^\('+name_re+r'\(('+name_re+r').*\)\)$', str_)
|
1154 |
|
|
if match: str_ = match.group(1)
|
1155 |
|
|
return unesc_name(str_)
|
1156 |
|
|
|
1157 |
|
|
def map_expr(db, expr, mapping, in_cols_found=None):
|
1158 |
|
|
'''Replaces output columns with input columns in an expression.
|
1159 |
|
|
@param in_cols_found If set, will be filled in with the expr's (input) cols
|
1160 |
|
|
'''
|
1161 |
|
|
for out, in_ in mapping.iteritems():
|
1162 |
|
|
orig_expr = expr
|
1163 |
|
|
out = to_name_only_col(out)
|
1164 |
|
|
in_str = to_name_only_col(remove_col_rename(in_)).to_str(db)
|
1165 |
|
|
|
1166 |
|
|
# Replace out both with and without quotes
|
1167 |
|
|
expr = expr.replace(out.to_str(db), in_str)
|
1168 |
5507
|
aaronmk
|
expr = re.sub(r'(?<!["\'\.=\[])\b'+out.name+r'\b(?!["\',\.=\]])',
|
1169 |
|
|
in_str, expr)
|
1170 |
5367
|
aaronmk
|
|
1171 |
|
|
if in_cols_found != None and expr != orig_expr: # replaced something
|
1172 |
|
|
in_cols_found.append(in_)
|
1173 |
|
|
|
1174 |
|
|
return simplify_expr(expr)
|