1 |
2211
|
aaronmk
|
# SQL code generation
|
2 |
|
|
|
3 |
2276
|
aaronmk
|
import operator
|
4 |
|
|
|
5 |
2360
|
aaronmk
|
import objects
|
6 |
2222
|
aaronmk
|
import strings
|
7 |
2227
|
aaronmk
|
import util
|
8 |
2211
|
aaronmk
|
|
9 |
2499
|
aaronmk
|
##### Escaping
|
10 |
|
|
|
11 |
|
|
def esc_name(name, quote='"'):
|
12 |
|
|
return quote + name.replace(quote, quote+quote) + quote
|
13 |
|
|
# doubling an embedded quote escapes it in both PostgreSQL and MySQL
|
14 |
|
|
|
15 |
2513
|
aaronmk
|
def clean_name(name): return name.replace('"', '').replace('`', '')
|
16 |
|
|
|
17 |
2219
|
aaronmk
|
##### SQL code objects
|
18 |
|
|
|
19 |
2349
|
aaronmk
|
class MockDb:
|
20 |
2503
|
aaronmk
|
def esc_value(self, value): return strings.repr_no_u(value)
|
21 |
2349
|
aaronmk
|
|
22 |
2499
|
aaronmk
|
def esc_name(self, name): return esc_name(name)
|
23 |
2349
|
aaronmk
|
mockDb = MockDb()
|
24 |
|
|
|
25 |
2514
|
aaronmk
|
class BasicObject(objects.BasicObject):
|
26 |
|
|
def __init__(self, value): self.value = value
|
27 |
|
|
|
28 |
|
|
def __str__(self): return clean_name(strings.repr_no_u(self))
|
29 |
|
|
|
30 |
|
|
class Code(BasicObject):
|
31 |
2211
|
aaronmk
|
def to_str(self, db): raise NotImplemented()
|
32 |
2349
|
aaronmk
|
|
33 |
2514
|
aaronmk
|
def __repr__(self): return self.to_str(mockDb)
|
34 |
2211
|
aaronmk
|
|
35 |
2269
|
aaronmk
|
class CustomCode(Code):
|
36 |
2256
|
aaronmk
|
def __init__(self, str_): self.str_ = str_
|
37 |
|
|
|
38 |
|
|
def to_str(self, db): return self.str_
|
39 |
|
|
|
40 |
2540
|
aaronmk
|
class Expr(Code):
|
41 |
|
|
def __init__(self, expr): self.expr = expr
|
42 |
|
|
|
43 |
|
|
def to_str(self, db): return '('+self.expr.to_str(db)+')'
|
44 |
|
|
|
45 |
2335
|
aaronmk
|
##### Literal values
|
46 |
|
|
|
47 |
2216
|
aaronmk
|
class Literal(Code):
|
48 |
2211
|
aaronmk
|
def __init__(self, value): self.value = value
|
49 |
2213
|
aaronmk
|
|
50 |
|
|
def to_str(self, db): return db.esc_value(self.value)
|
51 |
2211
|
aaronmk
|
|
52 |
2400
|
aaronmk
|
def as_Value(value):
|
53 |
|
|
if isinstance(value, Code): return value
|
54 |
|
|
else: return Literal(value)
|
55 |
|
|
|
56 |
2216
|
aaronmk
|
def is_null(value): return isinstance(value, Literal) and value.value == None
|
57 |
|
|
|
58 |
2335
|
aaronmk
|
##### Tables
|
59 |
|
|
|
60 |
2211
|
aaronmk
|
class Table(Code):
|
61 |
|
|
def __init__(self, name, schema=None):
|
62 |
|
|
'''
|
63 |
|
|
@param schema str|None (for no schema)
|
64 |
|
|
'''
|
65 |
|
|
self.name = name
|
66 |
|
|
self.schema = schema
|
67 |
|
|
|
68 |
2348
|
aaronmk
|
def to_str(self, db):
|
69 |
|
|
str_ = ''
|
70 |
|
|
if self.schema != None: str_ += db.esc_name(self.schema)+'.'
|
71 |
|
|
str_ += db.esc_name(self.name)
|
72 |
|
|
return str_
|
73 |
2336
|
aaronmk
|
|
74 |
|
|
def to_Table(self): return self
|
75 |
2211
|
aaronmk
|
|
76 |
2219
|
aaronmk
|
def as_Table(table):
|
77 |
2270
|
aaronmk
|
if table == None or isinstance(table, Code): return table
|
78 |
2219
|
aaronmk
|
else: return Table(table)
|
79 |
|
|
|
80 |
2336
|
aaronmk
|
class NamedTable(Table):
|
81 |
|
|
def __init__(self, name, code, cols=None):
|
82 |
|
|
Table.__init__(self, name)
|
83 |
|
|
|
84 |
|
|
if not isinstance(code, Code): code = Table(code)
|
85 |
|
|
|
86 |
|
|
self.code = code
|
87 |
|
|
self.cols = cols
|
88 |
|
|
|
89 |
|
|
def to_str(self, db):
|
90 |
2467
|
aaronmk
|
str_ = self.code.to_str(db)+'\nAS '+Table.to_str(self, db)
|
91 |
2336
|
aaronmk
|
if self.cols != None: str_ += ' ('+(', '.join(self.cols))+')'
|
92 |
|
|
return str_
|
93 |
|
|
|
94 |
|
|
def to_Table(self): return Table(self.name)
|
95 |
|
|
|
96 |
2335
|
aaronmk
|
##### Columns
|
97 |
|
|
|
98 |
2211
|
aaronmk
|
class Col(Code):
|
99 |
|
|
def __init__(self, name, table=None):
|
100 |
|
|
'''
|
101 |
|
|
@param table Table|None (for no table)
|
102 |
|
|
'''
|
103 |
2241
|
aaronmk
|
if util.is_str(table): table = Table(table)
|
104 |
2211
|
aaronmk
|
assert table == None or isinstance(table, Table)
|
105 |
|
|
|
106 |
|
|
self.name = name
|
107 |
|
|
self.table = table
|
108 |
|
|
|
109 |
|
|
def to_str(self, db):
|
110 |
|
|
str_ = ''
|
111 |
|
|
if self.table != None: str_ += self.table.to_str(db)+'.'
|
112 |
2348
|
aaronmk
|
str_ += db.esc_name(self.name)
|
113 |
2211
|
aaronmk
|
return str_
|
114 |
2314
|
aaronmk
|
|
115 |
|
|
def to_Col(self): return self
|
116 |
2211
|
aaronmk
|
|
117 |
2393
|
aaronmk
|
def is_table_col(col): return col.table != None
|
118 |
|
|
|
119 |
2563
|
aaronmk
|
def as_Col(col, table=None, name=None):
|
120 |
|
|
'''
|
121 |
|
|
@param name If not None, any non-Col input will be renamed using NamedCol.
|
122 |
|
|
'''
|
123 |
|
|
if name != None:
|
124 |
|
|
col = as_Value(col)
|
125 |
|
|
if not isinstance(col, Col): col = NamedCol(name, col)
|
126 |
2333
|
aaronmk
|
|
127 |
|
|
if isinstance(col, Code): return col
|
128 |
2260
|
aaronmk
|
else: return Col(col, table)
|
129 |
|
|
|
130 |
2401
|
aaronmk
|
def to_name_only_col(col, check_table=None):
|
131 |
|
|
col = as_Col(col)
|
132 |
|
|
|
133 |
|
|
if check_table != None:
|
134 |
|
|
table = col.table
|
135 |
|
|
assert table == None or table == check_table
|
136 |
|
|
return Col(col.name)
|
137 |
|
|
|
138 |
2323
|
aaronmk
|
class NamedCol(Col):
|
139 |
2229
|
aaronmk
|
def __init__(self, name, code):
|
140 |
2310
|
aaronmk
|
Col.__init__(self, name)
|
141 |
|
|
|
142 |
2229
|
aaronmk
|
if not isinstance(code, Code): code = Literal(code)
|
143 |
|
|
|
144 |
|
|
self.code = code
|
145 |
|
|
|
146 |
|
|
def to_str(self, db):
|
147 |
2310
|
aaronmk
|
return self.code.to_str(db)+' AS '+Col.to_str(self, db)
|
148 |
2314
|
aaronmk
|
|
149 |
|
|
def to_Col(self): return Col(self.name)
|
150 |
2229
|
aaronmk
|
|
151 |
2462
|
aaronmk
|
def remove_col_rename(col):
|
152 |
|
|
if isinstance(col, NamedCol): col = col.code
|
153 |
|
|
return col
|
154 |
|
|
|
155 |
2564
|
aaronmk
|
class ColDict(dict):
|
156 |
|
|
'''A dict that automatically makes inserted entries Col objects'''
|
157 |
|
|
|
158 |
|
|
def __setitem__(self, key, value):
|
159 |
|
|
return dict.__setitem__(self, key, as_Col(value, name=key))
|
160 |
|
|
|
161 |
|
|
def update(self, dict_):
|
162 |
|
|
for key, value in dict_.iteritems(): self[key] = value
|
163 |
|
|
|
164 |
2524
|
aaronmk
|
##### Functions
|
165 |
|
|
|
166 |
|
|
class Function(Table): pass
|
167 |
|
|
|
168 |
|
|
class FunctionCall(Code):
|
169 |
|
|
def __init__(self, function, *args):
|
170 |
|
|
'''
|
171 |
|
|
@param args [Code...] The function's arguments
|
172 |
|
|
'''
|
173 |
|
|
if not isinstance(function, Code): function = Function(function)
|
174 |
2532
|
aaronmk
|
args = map(remove_col_rename, args)
|
175 |
2524
|
aaronmk
|
|
176 |
|
|
self.function = function
|
177 |
|
|
self.args = args
|
178 |
|
|
|
179 |
|
|
def to_str(self, db):
|
180 |
|
|
args_str = ', '.join((v.to_str(db) for v in self.args))
|
181 |
|
|
return self.function.to_str(db)+'('+args_str+')'
|
182 |
|
|
|
183 |
2533
|
aaronmk
|
def wrap_in_func(function, value):
|
184 |
|
|
'''Wraps a value inside a function call.
|
185 |
|
|
Propagates any column renaming to the returned value.
|
186 |
|
|
'''
|
187 |
|
|
name = None
|
188 |
|
|
if isinstance(value, NamedCol): name = value.name
|
189 |
|
|
value = FunctionCall(function, value)
|
190 |
|
|
if name != None: value = NamedCol(name, value)
|
191 |
|
|
return value
|
192 |
|
|
|
193 |
2561
|
aaronmk
|
def unwrap_func_call(func_call, check_name=None):
|
194 |
|
|
'''Unwraps any function call to its first argument.
|
195 |
|
|
Also removes any column renaming.
|
196 |
|
|
'''
|
197 |
|
|
func_call = remove_col_rename(func_call)
|
198 |
|
|
if not isinstance(func_call, FunctionCall): return func_call
|
199 |
|
|
|
200 |
|
|
if check_name != None:
|
201 |
|
|
name = func_call.function.name
|
202 |
|
|
assert name == None or name == check_name
|
203 |
|
|
return func_call.args[0]
|
204 |
|
|
|
205 |
2335
|
aaronmk
|
##### Conditions
|
206 |
2259
|
aaronmk
|
|
207 |
2398
|
aaronmk
|
class ColValueCond(Code):
|
208 |
|
|
def __init__(self, col, value):
|
209 |
|
|
value = as_ValueCond(value)
|
210 |
|
|
|
211 |
|
|
self.col = col
|
212 |
|
|
self.value = value
|
213 |
|
|
|
214 |
|
|
def to_str(self, db): return self.value.to_str(db, self.col)
|
215 |
|
|
|
216 |
|
|
##### Condition column comparisons
|
217 |
|
|
|
218 |
2514
|
aaronmk
|
class ValueCond(BasicObject):
|
219 |
2213
|
aaronmk
|
def __init__(self, value):
|
220 |
2225
|
aaronmk
|
if not isinstance(value, Code): value = Literal(value)
|
221 |
2462
|
aaronmk
|
value = remove_col_rename(value)
|
222 |
2213
|
aaronmk
|
|
223 |
|
|
self.value = value
|
224 |
2214
|
aaronmk
|
|
225 |
2216
|
aaronmk
|
def to_str(self, db, left_value):
|
226 |
2214
|
aaronmk
|
'''
|
227 |
2216
|
aaronmk
|
@param left_value The Code object that the condition is being applied on
|
228 |
2214
|
aaronmk
|
'''
|
229 |
|
|
raise NotImplemented()
|
230 |
2228
|
aaronmk
|
|
231 |
2514
|
aaronmk
|
def __repr__(self): return self.to_str(mockDb, '<left_value>')
|
232 |
2211
|
aaronmk
|
|
233 |
|
|
class CompareCond(ValueCond):
|
234 |
|
|
def __init__(self, value, operator='='):
|
235 |
2222
|
aaronmk
|
'''
|
236 |
|
|
@param operator By default, compares NULL values literally. Use '~=' or
|
237 |
|
|
'~!=' to pass NULLs through.
|
238 |
|
|
'''
|
239 |
2211
|
aaronmk
|
ValueCond.__init__(self, value)
|
240 |
|
|
self.operator = operator
|
241 |
|
|
|
242 |
2216
|
aaronmk
|
def to_str(self, db, left_value):
|
243 |
|
|
if not isinstance(left_value, Code): left_value = Col(left_value)
|
244 |
2462
|
aaronmk
|
left_value = remove_col_rename(left_value)
|
245 |
2216
|
aaronmk
|
|
246 |
2222
|
aaronmk
|
right_value = self.value
|
247 |
|
|
left = left_value.to_str(db)
|
248 |
|
|
right = right_value.to_str(db)
|
249 |
|
|
|
250 |
|
|
# Parse operator
|
251 |
2216
|
aaronmk
|
operator = self.operator
|
252 |
2222
|
aaronmk
|
passthru_null_ref = [False]
|
253 |
|
|
operator = strings.remove_prefix('~', operator, passthru_null_ref)
|
254 |
|
|
neg_ref = [False]
|
255 |
|
|
operator = strings.remove_prefix('!', operator, neg_ref)
|
256 |
|
|
equals = operator.endswith('=')
|
257 |
|
|
if equals and is_null(self.value): operator = 'IS'
|
258 |
|
|
|
259 |
|
|
# Create str
|
260 |
|
|
str_ = left+' '+operator+' '+right
|
261 |
|
|
if equals and not passthru_null_ref[0] and isinstance(right_value, Col):
|
262 |
|
|
str_ += ' OR ('+left+' IS NULL AND '+right+' IS NULL)'
|
263 |
|
|
if neg_ref[0]: str_ = 'NOT ('+str_+')'
|
264 |
|
|
return str_
|
265 |
2216
|
aaronmk
|
|
266 |
2260
|
aaronmk
|
# Tells as_ValueCond() to assume a non-ValueCond is a literal value
|
267 |
|
|
assume_literal = object()
|
268 |
|
|
|
269 |
|
|
def as_ValueCond(value, default_table=assume_literal):
|
270 |
|
|
if not isinstance(value, ValueCond):
|
271 |
|
|
if default_table is not assume_literal:
|
272 |
|
|
value = as_Col(value, default_table)
|
273 |
|
|
return CompareCond(value)
|
274 |
2216
|
aaronmk
|
else: return value
|
275 |
2219
|
aaronmk
|
|
276 |
2335
|
aaronmk
|
##### Joins
|
277 |
|
|
|
278 |
2352
|
aaronmk
|
join_same = object() # tells Join the left and right columns have the same name
|
279 |
2260
|
aaronmk
|
|
280 |
2353
|
aaronmk
|
# Tells Join the left and right columns have the same name and are never NULL
|
281 |
|
|
join_same_not_null = object()
|
282 |
|
|
|
283 |
2260
|
aaronmk
|
filter_out = object() # tells Join to filter out rows that match the join
|
284 |
|
|
|
285 |
2514
|
aaronmk
|
class Join(BasicObject):
|
286 |
2260
|
aaronmk
|
def __init__(self, table, mapping, type_=None):
|
287 |
|
|
'''
|
288 |
|
|
@param mapping dict(right_table_col=left_table_col, ...)
|
289 |
2352
|
aaronmk
|
* if left_table_col is join_same: left_table_col = right_table_col
|
290 |
2353
|
aaronmk
|
* Note that right_table_col must be a string
|
291 |
|
|
* if left_table_col is join_same_not_null:
|
292 |
|
|
left_table_col = right_table_col and both have NOT NULL constraint
|
293 |
|
|
* Note that right_table_col must be a string
|
294 |
2260
|
aaronmk
|
@param type_ None (for plain join)|str (e.g. 'LEFT')|filter_out
|
295 |
|
|
* filter_out: equivalent to 'LEFT' with the query filtered by
|
296 |
|
|
`table_pkey IS NULL` (indicating no match)
|
297 |
|
|
'''
|
298 |
|
|
if util.is_str(table): table = Table(table)
|
299 |
|
|
assert type_ == None or util.is_str(type_) or type_ is filter_out
|
300 |
|
|
|
301 |
|
|
self.table = table
|
302 |
|
|
self.mapping = mapping
|
303 |
|
|
self.type_ = type_
|
304 |
|
|
|
305 |
|
|
def to_str(self, db, left_table):
|
306 |
2353
|
aaronmk
|
# Switch order (left_table is on the right in the comparison)
|
307 |
|
|
right_table = left_table
|
308 |
|
|
left_table = self.table # note left_table is reassigned
|
309 |
|
|
|
310 |
2260
|
aaronmk
|
def join(entry):
|
311 |
|
|
'''Parses non-USING joins'''
|
312 |
|
|
right_table_col, left_table_col = entry
|
313 |
|
|
|
314 |
2353
|
aaronmk
|
# Switch order (right_table_col is on the left in the comparison)
|
315 |
|
|
left = right_table_col
|
316 |
|
|
right = left_table_col
|
317 |
|
|
|
318 |
2260
|
aaronmk
|
# Parse special values
|
319 |
2353
|
aaronmk
|
if right is join_same: right = left
|
320 |
|
|
elif right is join_same_not_null:
|
321 |
|
|
right = CompareCond(as_Col(left, right_table), '~=')
|
322 |
2260
|
aaronmk
|
|
323 |
2353
|
aaronmk
|
right = as_ValueCond(right, right_table)
|
324 |
2410
|
aaronmk
|
return '('+right.to_str(db, as_Col(left, left_table))+')'
|
325 |
2260
|
aaronmk
|
|
326 |
2265
|
aaronmk
|
# Create join condition
|
327 |
|
|
type_ = self.type_
|
328 |
2276
|
aaronmk
|
joins = self.mapping
|
329 |
2265
|
aaronmk
|
if type_ is not filter_out and reduce(operator.and_,
|
330 |
2460
|
aaronmk
|
(v is join_same_not_null for v in joins.itervalues())):
|
331 |
2260
|
aaronmk
|
# all cols w/ USING, so can use simpler USING syntax
|
332 |
2298
|
aaronmk
|
cols = (as_Col(v).to_str(db) for v in joins.iterkeys())
|
333 |
|
|
join_cond = 'USING ('+(', '.join(cols))+')'
|
334 |
2467
|
aaronmk
|
else: join_cond = 'ON\n'+('\nAND\n'.join(map(join, joins.iteritems())))
|
335 |
2260
|
aaronmk
|
|
336 |
|
|
# Create join
|
337 |
|
|
if type_ is filter_out: type_ = 'LEFT'
|
338 |
2266
|
aaronmk
|
str_ = ''
|
339 |
|
|
if type_ != None: str_ += type_+' '
|
340 |
2353
|
aaronmk
|
str_ += 'JOIN '+left_table.to_str(db)+' '+join_cond
|
341 |
2266
|
aaronmk
|
return str_
|
342 |
2349
|
aaronmk
|
|
343 |
2514
|
aaronmk
|
def __repr__(self): return self.to_str(mockDb, '<left_table>')
|
344 |
2424
|
aaronmk
|
|
345 |
|
|
##### Value exprs
|
346 |
|
|
|
347 |
|
|
row_count = CustomCode('count(*)')
|