Project

General

Profile

1 2211 aaronmk
# SQL code generation
2
3 2748 aaronmk
import copy
4 2276 aaronmk
import operator
5 2568 aaronmk
import re
6 2653 aaronmk
import UserDict
7 2276 aaronmk
8 2667 aaronmk
import dicts
9 2701 aaronmk
import iters
10
import lists
11 2360 aaronmk
import objects
12 2222 aaronmk
import strings
13 2227 aaronmk
import util
14 2211 aaronmk
15 2587 aaronmk
##### Names
16 2499 aaronmk
17 2608 aaronmk
identifier_max_len = 63 # works for both PostgreSQL and MySQL
18 2587 aaronmk
19
def add_suffix(str_, suffix):
20 2609 aaronmk
    '''Preserves version so that it won't be truncated off the string, leading
21
    to collisions.'''
22 2613 aaronmk
    # Preserve version
23
    before, sep, version = str_.rpartition('#')
24
    if sep != '': # found match
25
        str_ = before
26 2609 aaronmk
        suffix = sep+version+suffix
27 2613 aaronmk
28 2587 aaronmk
    return strings.add_suffix(str_, suffix, identifier_max_len)
29
30 2575 aaronmk
def is_safe_name(name):
31 2583 aaronmk
    '''A name is safe *and unambiguous* if it:
32
    * contains only *lowercase* word (\w) characters
33
    * doesn't start with a digit
34
    * contains "_", so that it's not a keyword
35
    '''
36
    return re.match(r'^(?=.*_)(?!\d)[^\WA-Z]+$', name)
37 2568 aaronmk
38 2499 aaronmk
def esc_name(name, quote='"'):
39
    return quote + name.replace(quote, quote+quote) + quote
40
        # doubling an embedded quote escapes it in both PostgreSQL and MySQL
41
42 2513 aaronmk
def clean_name(name): return name.replace('"', '').replace('`', '')
43
44 2659 aaronmk
##### General SQL code objects
45 2219 aaronmk
46 2349 aaronmk
class MockDb:
47 2503 aaronmk
    def esc_value(self, value): return strings.repr_no_u(value)
48 2349 aaronmk
49 2499 aaronmk
    def esc_name(self, name): return esc_name(name)
50 2349 aaronmk
mockDb = MockDb()
51
52 2514 aaronmk
class BasicObject(objects.BasicObject):
53
    def __init__(self, value): self.value = value
54
55
    def __str__(self): return clean_name(strings.repr_no_u(self))
56
57 2659 aaronmk
##### Unparameterized code objects
58
59 2514 aaronmk
class Code(BasicObject):
60 2658 aaronmk
    def to_str(self, db): raise NotImplementedError()
61 2349 aaronmk
62 2514 aaronmk
    def __repr__(self): return self.to_str(mockDb)
63 2211 aaronmk
64 2269 aaronmk
class CustomCode(Code):
65 2256 aaronmk
    def __init__(self, str_): self.str_ = str_
66
67
    def to_str(self, db): return self.str_
68
69 2659 aaronmk
def as_Code(value):
70
    if util.is_str(value): return CustomCode(value)
71
    else: return Literal(value)
72
73 2540 aaronmk
class Expr(Code):
74
    def __init__(self, expr): self.expr = expr
75
76
    def to_str(self, db): return '('+self.expr.to_str(db)+')'
77
78 2335 aaronmk
##### Literal values
79
80 2216 aaronmk
class Literal(Code):
81 2211 aaronmk
    def __init__(self, value): self.value = value
82 2213 aaronmk
83
    def to_str(self, db): return db.esc_value(self.value)
84 2211 aaronmk
85 2400 aaronmk
def as_Value(value):
86
    if isinstance(value, Code): return value
87
    else: return Literal(value)
88
89 2216 aaronmk
def is_null(value): return isinstance(value, Literal) and value.value == None
90
91 2711 aaronmk
##### Derived elements
92
93
src_self = object() # tells Col that it is its own source column
94
95
class Derived(Code):
96
    def __init__(self, srcs):
97 2712 aaronmk
        '''An element which was derived from some other element(s).
98 2711 aaronmk
        @param srcs See self.set_srcs()
99
        '''
100
        self.set_srcs(srcs)
101
102 2713 aaronmk
    def set_srcs(self, srcs, overwrite=True):
103 2711 aaronmk
        '''
104
        @param srcs (self_type...)|src_self The element(s) this is derived from
105
        '''
106 2713 aaronmk
        if not overwrite and self.srcs != (): return # already set
107
108 2711 aaronmk
        if srcs == src_self: srcs = (self,)
109
        srcs = tuple(srcs) # make Col hashable
110
        self.srcs = srcs
111
112
    def _compare_on(self):
113
        compare_on = self.__dict__.copy()
114
        del compare_on['srcs'] # ignore
115
        return compare_on
116
117
def cols_srcs(cols): return lists.uniqify(iters.flatten((v.srcs for v in cols)))
118
119 2335 aaronmk
##### Tables
120
121 2712 aaronmk
class Table(Derived):
122
    def __init__(self, name, schema=None, srcs=()):
123 2211 aaronmk
        '''
124
        @param schema str|None (for no schema)
125 2712 aaronmk
        @param srcs (Table...)|src_self See Derived.set_srcs()
126 2211 aaronmk
        '''
127 2712 aaronmk
        Derived.__init__(self, srcs)
128
129 2211 aaronmk
        self.name = name
130
        self.schema = schema
131
132 2348 aaronmk
    def to_str(self, db):
133
        str_ = ''
134
        if self.schema != None: str_ += db.esc_name(self.schema)+'.'
135
        str_ += db.esc_name(self.name)
136
        return str_
137 2336 aaronmk
138
    def to_Table(self): return self
139 2211 aaronmk
140 2776 aaronmk
def as_Table(table, schema=None):
141 2270 aaronmk
    if table == None or isinstance(table, Code): return table
142 2776 aaronmk
    else: return Table(table, schema)
143 2219 aaronmk
144 2707 aaronmk
def suffixed_table(table, suffix): return Table(table.name+suffix, table.schema)
145
146 2336 aaronmk
class NamedTable(Table):
147
    def __init__(self, name, code, cols=None):
148
        Table.__init__(self, name)
149
150
        if not isinstance(code, Code): code = Table(code)
151 2741 aaronmk
        if not isinstance(code, (Table, FunctionCall, Expr)): code = Expr(code)
152 2742 aaronmk
        if cols != None: cols = map(to_name_only_col, cols)
153 2336 aaronmk
154
        self.code = code
155
        self.cols = cols
156
157
    def to_str(self, db):
158 2467 aaronmk
        str_ = self.code.to_str(db)+'\nAS '+Table.to_str(self, db)
159 2742 aaronmk
        if self.cols != None:
160
            str_ += ' ('+(', '.join((c.to_str(db) for c in self.cols)))+')'
161 2336 aaronmk
        return str_
162
163
    def to_Table(self): return Table(self.name)
164
165 2753 aaronmk
def remove_table_rename(table):
166
    if isinstance(table, NamedTable): table = table.code
167
    return table
168
169 2335 aaronmk
##### Columns
170
171 2711 aaronmk
class Col(Derived):
172 2701 aaronmk
    def __init__(self, name, table=None, srcs=()):
173 2211 aaronmk
        '''
174
        @param table Table|None (for no table)
175 2711 aaronmk
        @param srcs (Col...)|src_self See Derived.set_srcs()
176 2211 aaronmk
        '''
177 2711 aaronmk
        Derived.__init__(self, srcs)
178
179 2241 aaronmk
        if util.is_str(table): table = Table(table)
180 2211 aaronmk
        assert table == None or isinstance(table, Table)
181 2752 aaronmk
        if table != None: table = table.to_Table()
182 2211 aaronmk
183
        self.name = name
184
        self.table = table
185
186
    def to_str(self, db):
187
        str_ = ''
188
        if self.table != None: str_ += self.table.to_str(db)+'.'
189 2348 aaronmk
        str_ += db.esc_name(self.name)
190 2211 aaronmk
        return str_
191 2314 aaronmk
192
    def to_Col(self): return self
193 2211 aaronmk
194 2767 aaronmk
def is_table_col(col): return isinstance(col, Col) and col.table != None
195 2393 aaronmk
196 2563 aaronmk
def as_Col(col, table=None, name=None):
197
    '''
198
    @param name If not None, any non-Col input will be renamed using NamedCol.
199
    '''
200
    if name != None:
201
        col = as_Value(col)
202
        if not isinstance(col, Col): col = NamedCol(name, col)
203 2333 aaronmk
204
    if isinstance(col, Code): return col
205 2260 aaronmk
    else: return Col(col, table)
206
207 2750 aaronmk
def with_default_table(col, table, overwrite=False):
208 2747 aaronmk
    col = as_Col(col)
209 2750 aaronmk
    if not isinstance(col, NamedCol) and (overwrite or col.table == None):
210 2748 aaronmk
        col = copy.copy(col) # don't modify input!
211
        col.table = table
212 2747 aaronmk
    return col
213
214 2744 aaronmk
def set_cols_table(table, cols):
215
    table = as_Table(table)
216
217
    for i, col in enumerate(cols):
218
        col = cols[i] = as_Col(col)
219
        col.table = table
220
221 2401 aaronmk
def to_name_only_col(col, check_table=None):
222
    col = as_Col(col)
223 2579 aaronmk
    if not isinstance(col, Col): return col
224 2401 aaronmk
225
    if check_table != None:
226
        table = col.table
227
        assert table == None or table == check_table
228
    return Col(col.name)
229
230 2323 aaronmk
class NamedCol(Col):
231 2229 aaronmk
    def __init__(self, name, code):
232 2310 aaronmk
        Col.__init__(self, name)
233
234 2229 aaronmk
        if not isinstance(code, Code): code = Literal(code)
235
236
        self.code = code
237
238
    def to_str(self, db):
239 2310 aaronmk
        return self.code.to_str(db)+' AS '+Col.to_str(self, db)
240 2314 aaronmk
241
    def to_Col(self): return Col(self.name)
242 2229 aaronmk
243 2462 aaronmk
def remove_col_rename(col):
244
    if isinstance(col, NamedCol): col = col.code
245
    return col
246
247 2703 aaronmk
def wrap(wrap_func, value):
248
    '''Wraps a value, propagating any column renaming to the returned value.'''
249
    if isinstance(value, NamedCol):
250
        return NamedCol(value.name, wrap_func(value.code))
251
    else: return wrap_func(value)
252
253 2667 aaronmk
class ColDict(dicts.DictProxy):
254 2564 aaronmk
    '''A dict that automatically makes inserted entries Col objects'''
255
256 2645 aaronmk
    def __init__(self, db, keys_table, dict_={}):
257 2667 aaronmk
        dicts.DictProxy.__init__(self, {})
258
259 2645 aaronmk
        keys_table = as_Table(keys_table)
260
261 2642 aaronmk
        self.db = db
262 2641 aaronmk
        self.table = keys_table
263 2653 aaronmk
        self.update(dict_) # after setting vars because __setitem__() needs them
264 2641 aaronmk
265 2667 aaronmk
    def copy(self): return ColDict(self.db, self.table, self.inner.copy())
266 2655 aaronmk
267 2667 aaronmk
    def __getitem__(self, key):
268
        return dicts.DictProxy.__getitem__(self, self._key(key))
269 2653 aaronmk
270 2564 aaronmk
    def __setitem__(self, key, value):
271 2642 aaronmk
        key = self._key(key)
272 2661 aaronmk
        if value == None: value = self.db.col_default(key)
273 2667 aaronmk
        dicts.DictProxy.__setitem__(self, key, as_Col(value, name=key.name))
274 2564 aaronmk
275 2641 aaronmk
    def _key(self, key): return as_Col(key, self.table)
276 2564 aaronmk
277 2524 aaronmk
##### Functions
278
279
class Function(Table): pass
280
281 2697 aaronmk
def TempFunction(name, autocommit):
282
    schema = None
283
    if not autocommit: schema = 'pg_temp'
284
    return Function(name, schema)
285
286 2691 aaronmk
class InternalFunction(CustomCode): pass
287
288 2524 aaronmk
class FunctionCall(Code):
289
    def __init__(self, function, *args):
290
        '''
291 2690 aaronmk
        @param args [Code|literal-value...] The function's arguments
292 2524 aaronmk
        '''
293
        if not isinstance(function, Code): function = Function(function)
294 2690 aaronmk
        args = map(remove_col_rename, map(as_Value, args))
295 2524 aaronmk
296
        self.function = function
297
        self.args = args
298
299
    def to_str(self, db):
300
        args_str = ', '.join((v.to_str(db) for v in self.args))
301
        return self.function.to_str(db)+'('+args_str+')'
302
303 2533 aaronmk
def wrap_in_func(function, value):
304
    '''Wraps a value inside a function call.
305
    Propagates any column renaming to the returned value.
306
    '''
307 2703 aaronmk
    return wrap(lambda v: FunctionCall(function, v), value)
308 2533 aaronmk
309 2561 aaronmk
def unwrap_func_call(func_call, check_name=None):
310
    '''Unwraps any function call to its first argument.
311
    Also removes any column renaming.
312
    '''
313
    func_call = remove_col_rename(func_call)
314
    if not isinstance(func_call, FunctionCall): return func_call
315
316
    if check_name != None:
317
        name = func_call.function.name
318
        assert name == None or name == check_name
319
    return func_call.args[0]
320
321 2335 aaronmk
##### Conditions
322 2259 aaronmk
323 2398 aaronmk
class ColValueCond(Code):
324
    def __init__(self, col, value):
325
        value = as_ValueCond(value)
326
327
        self.col = col
328
        self.value = value
329
330
    def to_str(self, db): return self.value.to_str(db, self.col)
331
332 2577 aaronmk
def combine_conds(conds, keyword=None):
333
    '''
334
    @param keyword The keyword to add before the conditions, if any
335
    '''
336
    str_ = ''
337
    if keyword != None:
338
        if conds == []: whitespace = ''
339
        elif len(conds) == 1: whitespace = ' '
340
        else: whitespace = '\n'
341
        str_ += keyword+whitespace
342
343
    str_ += '\nAND '.join(conds)
344
    return str_
345
346 2398 aaronmk
##### Condition column comparisons
347
348 2514 aaronmk
class ValueCond(BasicObject):
349 2213 aaronmk
    def __init__(self, value):
350 2225 aaronmk
        if not isinstance(value, Code): value = Literal(value)
351 2462 aaronmk
        value = remove_col_rename(value)
352 2213 aaronmk
353
        self.value = value
354 2214 aaronmk
355 2216 aaronmk
    def to_str(self, db, left_value):
356 2214 aaronmk
        '''
357 2216 aaronmk
        @param left_value The Code object that the condition is being applied on
358 2214 aaronmk
        '''
359
        raise NotImplemented()
360 2228 aaronmk
361 2514 aaronmk
    def __repr__(self): return self.to_str(mockDb, '<left_value>')
362 2211 aaronmk
363
class CompareCond(ValueCond):
364
    def __init__(self, value, operator='='):
365 2222 aaronmk
        '''
366
        @param operator By default, compares NULL values literally. Use '~=' or
367
            '~!=' to pass NULLs through.
368
        '''
369 2211 aaronmk
        ValueCond.__init__(self, value)
370
        self.operator = operator
371
372 2216 aaronmk
    def to_str(self, db, left_value):
373
        if not isinstance(left_value, Code): left_value = Col(left_value)
374 2462 aaronmk
        left_value = remove_col_rename(left_value)
375 2216 aaronmk
376 2222 aaronmk
        right_value = self.value
377
        left = left_value.to_str(db)
378
        right = right_value.to_str(db)
379
380
        # Parse operator
381 2216 aaronmk
        operator = self.operator
382 2222 aaronmk
        passthru_null_ref = [False]
383
        operator = strings.remove_prefix('~', operator, passthru_null_ref)
384
        neg_ref = [False]
385
        operator = strings.remove_prefix('!', operator, neg_ref)
386
        equals = operator.endswith('=')
387
        if equals and is_null(self.value): operator = 'IS'
388
389
        # Create str
390
        str_ = left+' '+operator+' '+right
391
        if equals and not passthru_null_ref[0] and isinstance(right_value, Col):
392 2578 aaronmk
            str_ = '('+str_+' OR ('+left+' IS NULL AND '+right+' IS NULL))'
393
        if neg_ref[0]: str_ = 'NOT '+str_
394 2222 aaronmk
        return str_
395 2216 aaronmk
396 2260 aaronmk
# Tells as_ValueCond() to assume a non-ValueCond is a literal value
397
assume_literal = object()
398
399
def as_ValueCond(value, default_table=assume_literal):
400
    if not isinstance(value, ValueCond):
401
        if default_table is not assume_literal:
402 2748 aaronmk
            value = with_default_table(value, default_table)
403 2260 aaronmk
        return CompareCond(value)
404 2216 aaronmk
    else: return value
405 2219 aaronmk
406 2335 aaronmk
##### Joins
407
408 2352 aaronmk
join_same = object() # tells Join the left and right columns have the same name
409 2260 aaronmk
410 2353 aaronmk
# Tells Join the left and right columns have the same name and are never NULL
411
join_same_not_null = object()
412
413 2260 aaronmk
filter_out = object() # tells Join to filter out rows that match the join
414
415 2514 aaronmk
class Join(BasicObject):
416 2746 aaronmk
    def __init__(self, table, mapping={}, type_=None):
417 2260 aaronmk
        '''
418
        @param mapping dict(right_table_col=left_table_col, ...)
419 2352 aaronmk
            * if left_table_col is join_same: left_table_col = right_table_col
420 2353 aaronmk
              * Note that right_table_col must be a string
421
            * if left_table_col is join_same_not_null:
422
              left_table_col = right_table_col and both have NOT NULL constraint
423
              * Note that right_table_col must be a string
424 2260 aaronmk
        @param type_ None (for plain join)|str (e.g. 'LEFT')|filter_out
425
            * filter_out: equivalent to 'LEFT' with the query filtered by
426
              `table_pkey IS NULL` (indicating no match)
427
        '''
428
        if util.is_str(table): table = Table(table)
429
        assert type_ == None or util.is_str(type_) or type_ is filter_out
430
431
        self.table = table
432
        self.mapping = mapping
433
        self.type_ = type_
434
435 2749 aaronmk
    def to_str(self, db, left_table_):
436 2260 aaronmk
        def join(entry):
437
            '''Parses non-USING joins'''
438
            right_table_col, left_table_col = entry
439
440 2353 aaronmk
            # Switch order (right_table_col is on the left in the comparison)
441
            left = right_table_col
442
            right = left_table_col
443 2749 aaronmk
            left_table = self.table
444
            right_table = left_table_
445 2353 aaronmk
446 2749 aaronmk
            left_table = left_table.to_Table()
447
            right_table = right_table.to_Table()
448
449 2747 aaronmk
            # Parse left side
450 2748 aaronmk
            left = with_default_table(left, left_table)
451 2747 aaronmk
452 2260 aaronmk
            # Parse special values
453 2747 aaronmk
            left_on_right = Col(left.name, right_table)
454
            if right is join_same: right = left_on_right
455 2353 aaronmk
            elif right is join_same_not_null:
456 2747 aaronmk
                right = CompareCond(left_on_right, '~=')
457 2260 aaronmk
458 2747 aaronmk
            # Parse right side
459 2353 aaronmk
            right = as_ValueCond(right, right_table)
460 2747 aaronmk
461
            return right.to_str(db, left)
462 2260 aaronmk
463 2265 aaronmk
        # Create join condition
464
        type_ = self.type_
465 2276 aaronmk
        joins = self.mapping
466 2746 aaronmk
        if joins == {}: join_cond = None
467
        elif type_ is not filter_out and reduce(operator.and_,
468 2460 aaronmk
            (v is join_same_not_null for v in joins.itervalues())):
469 2260 aaronmk
            # all cols w/ USING, so can use simpler USING syntax
470 2747 aaronmk
            cols = map(to_name_only_col, joins.iterkeys())
471
            join_cond = 'USING ('+(', '.join((c.to_str(db) for c in cols)))+')'
472 2757 aaronmk
        else: join_cond = combine_conds(map(join, joins.iteritems()), 'ON')
473 2260 aaronmk
474 2757 aaronmk
        if isinstance(self.table, NamedTable): whitespace = '\n'
475
        else: whitespace = ' '
476
477 2260 aaronmk
        # Create join
478
        if type_ is filter_out: type_ = 'LEFT'
479 2266 aaronmk
        str_ = ''
480
        if type_ != None: str_ += type_+' '
481 2757 aaronmk
        str_ += 'JOIN'+whitespace+self.table.to_str(db)
482
        if join_cond != None: str_ += whitespace+join_cond
483 2266 aaronmk
        return str_
484 2349 aaronmk
485 2514 aaronmk
    def __repr__(self): return self.to_str(mockDb, '<left_table>')
486 2424 aaronmk
487
##### Value exprs
488
489 2737 aaronmk
default = CustomCode('DEFAULT')
490
491 2424 aaronmk
row_count = CustomCode('count(*)')
492 2674 aaronmk
493 2692 aaronmk
def EnsureNotNull(value, null=r'\N'):
494 2694 aaronmk
    return FunctionCall(InternalFunction('coalesce'), as_Col(value), null)
495 2692 aaronmk
496 2737 aaronmk
##### Table exprs
497
498
class Values(Code):
499
    def __init__(self, values):
500 2739 aaronmk
        '''
501
        @param values [...]|[[...], ...] Can be one or multiple rows.
502
        '''
503
        rows = values
504
        if len(values) >= 1 and not lists.is_seq(values[0]): # only one row
505
            rows = [values]
506
        for i, row in enumerate(rows):
507
            rows[i] = map(remove_col_rename, map(as_Value, row))
508 2737 aaronmk
509 2739 aaronmk
        self.rows = rows
510 2737 aaronmk
511
    def to_str(self, db):
512 2739 aaronmk
        def row_str(row):
513
            return '('+(', '.join((v.to_str(db) for v in row)))+')'
514
        return 'VALUES '+(', '.join(map(row_str, self.rows)))
515 2737 aaronmk
516 2740 aaronmk
def NamedValues(name, cols, values):
517 2745 aaronmk
    '''
518
    @post `cols` will be changed to Col objects with the table set to `name`.
519
    '''
520
    set_cols_table(name, cols)
521 2740 aaronmk
    return NamedTable(name, Values(values), cols)
522
523 2674 aaronmk
##### Database structure
524
525
class TypedCol(Col):
526
    def __init__(self, name, type_):
527
        Col.__init__(self, name)
528
529
        self.type = type_
530
531
    def to_str(self, db): return Col.to_str(self, db)+' '+self.type
532
533
    def to_Col(self): return Col(self.name)