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 2219 aaronmk
def as_Table(table):
141 2270 aaronmk
    if table == None or isinstance(table, Code): return table
142 2219 aaronmk
    else: return Table(table)
143
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 2335 aaronmk
##### Columns
166
167 2711 aaronmk
class Col(Derived):
168 2701 aaronmk
    def __init__(self, name, table=None, srcs=()):
169 2211 aaronmk
        '''
170
        @param table Table|None (for no table)
171 2711 aaronmk
        @param srcs (Col...)|src_self See Derived.set_srcs()
172 2211 aaronmk
        '''
173 2711 aaronmk
        Derived.__init__(self, srcs)
174
175 2241 aaronmk
        if util.is_str(table): table = Table(table)
176 2211 aaronmk
        assert table == None or isinstance(table, Table)
177 2752 aaronmk
        if table != None: table = table.to_Table()
178 2211 aaronmk
179
        self.name = name
180
        self.table = table
181
182
    def to_str(self, db):
183
        str_ = ''
184
        if self.table != None: str_ += self.table.to_str(db)+'.'
185 2348 aaronmk
        str_ += db.esc_name(self.name)
186 2211 aaronmk
        return str_
187 2314 aaronmk
188
    def to_Col(self): return self
189 2211 aaronmk
190 2393 aaronmk
def is_table_col(col): return col.table != None
191
192 2563 aaronmk
def as_Col(col, table=None, name=None):
193
    '''
194
    @param name If not None, any non-Col input will be renamed using NamedCol.
195
    '''
196
    if name != None:
197
        col = as_Value(col)
198
        if not isinstance(col, Col): col = NamedCol(name, col)
199 2333 aaronmk
200
    if isinstance(col, Code): return col
201 2260 aaronmk
    else: return Col(col, table)
202
203 2750 aaronmk
def with_default_table(col, table, overwrite=False):
204 2747 aaronmk
    col = as_Col(col)
205 2750 aaronmk
    if not isinstance(col, NamedCol) and (overwrite or col.table == None):
206 2748 aaronmk
        col = copy.copy(col) # don't modify input!
207
        col.table = table
208 2747 aaronmk
    return col
209
210 2744 aaronmk
def set_cols_table(table, cols):
211
    table = as_Table(table)
212
213
    for i, col in enumerate(cols):
214
        col = cols[i] = as_Col(col)
215
        col.table = table
216
217 2401 aaronmk
def to_name_only_col(col, check_table=None):
218
    col = as_Col(col)
219 2579 aaronmk
    if not isinstance(col, Col): return col
220 2401 aaronmk
221
    if check_table != None:
222
        table = col.table
223
        assert table == None or table == check_table
224
    return Col(col.name)
225
226 2323 aaronmk
class NamedCol(Col):
227 2229 aaronmk
    def __init__(self, name, code):
228 2310 aaronmk
        Col.__init__(self, name)
229
230 2229 aaronmk
        if not isinstance(code, Code): code = Literal(code)
231
232
        self.code = code
233
234
    def to_str(self, db):
235 2310 aaronmk
        return self.code.to_str(db)+' AS '+Col.to_str(self, db)
236 2314 aaronmk
237
    def to_Col(self): return Col(self.name)
238 2229 aaronmk
239 2462 aaronmk
def remove_col_rename(col):
240
    if isinstance(col, NamedCol): col = col.code
241
    return col
242
243 2703 aaronmk
def wrap(wrap_func, value):
244
    '''Wraps a value, propagating any column renaming to the returned value.'''
245
    if isinstance(value, NamedCol):
246
        return NamedCol(value.name, wrap_func(value.code))
247
    else: return wrap_func(value)
248
249 2667 aaronmk
class ColDict(dicts.DictProxy):
250 2564 aaronmk
    '''A dict that automatically makes inserted entries Col objects'''
251
252 2645 aaronmk
    def __init__(self, db, keys_table, dict_={}):
253 2667 aaronmk
        dicts.DictProxy.__init__(self, {})
254
255 2645 aaronmk
        keys_table = as_Table(keys_table)
256
257 2642 aaronmk
        self.db = db
258 2641 aaronmk
        self.table = keys_table
259 2653 aaronmk
        self.update(dict_) # after setting vars because __setitem__() needs them
260 2641 aaronmk
261 2667 aaronmk
    def copy(self): return ColDict(self.db, self.table, self.inner.copy())
262 2655 aaronmk
263 2667 aaronmk
    def __getitem__(self, key):
264
        return dicts.DictProxy.__getitem__(self, self._key(key))
265 2653 aaronmk
266 2564 aaronmk
    def __setitem__(self, key, value):
267 2642 aaronmk
        key = self._key(key)
268 2661 aaronmk
        if value == None: value = self.db.col_default(key)
269 2667 aaronmk
        dicts.DictProxy.__setitem__(self, key, as_Col(value, name=key.name))
270 2564 aaronmk
271 2641 aaronmk
    def _key(self, key): return as_Col(key, self.table)
272 2564 aaronmk
273 2524 aaronmk
##### Functions
274
275
class Function(Table): pass
276
277 2697 aaronmk
def TempFunction(name, autocommit):
278
    schema = None
279
    if not autocommit: schema = 'pg_temp'
280
    return Function(name, schema)
281
282 2691 aaronmk
class InternalFunction(CustomCode): pass
283
284 2524 aaronmk
class FunctionCall(Code):
285
    def __init__(self, function, *args):
286
        '''
287 2690 aaronmk
        @param args [Code|literal-value...] The function's arguments
288 2524 aaronmk
        '''
289
        if not isinstance(function, Code): function = Function(function)
290 2690 aaronmk
        args = map(remove_col_rename, map(as_Value, args))
291 2524 aaronmk
292
        self.function = function
293
        self.args = args
294
295
    def to_str(self, db):
296
        args_str = ', '.join((v.to_str(db) for v in self.args))
297
        return self.function.to_str(db)+'('+args_str+')'
298
299 2533 aaronmk
def wrap_in_func(function, value):
300
    '''Wraps a value inside a function call.
301
    Propagates any column renaming to the returned value.
302
    '''
303 2703 aaronmk
    return wrap(lambda v: FunctionCall(function, v), value)
304 2533 aaronmk
305 2561 aaronmk
def unwrap_func_call(func_call, check_name=None):
306
    '''Unwraps any function call to its first argument.
307
    Also removes any column renaming.
308
    '''
309
    func_call = remove_col_rename(func_call)
310
    if not isinstance(func_call, FunctionCall): return func_call
311
312
    if check_name != None:
313
        name = func_call.function.name
314
        assert name == None or name == check_name
315
    return func_call.args[0]
316
317 2335 aaronmk
##### Conditions
318 2259 aaronmk
319 2398 aaronmk
class ColValueCond(Code):
320
    def __init__(self, col, value):
321
        value = as_ValueCond(value)
322
323
        self.col = col
324
        self.value = value
325
326
    def to_str(self, db): return self.value.to_str(db, self.col)
327
328 2577 aaronmk
def combine_conds(conds, keyword=None):
329
    '''
330
    @param keyword The keyword to add before the conditions, if any
331
    '''
332
    str_ = ''
333
    if keyword != None:
334
        if conds == []: whitespace = ''
335
        elif len(conds) == 1: whitespace = ' '
336
        else: whitespace = '\n'
337
        str_ += keyword+whitespace
338
339
    str_ += '\nAND '.join(conds)
340
    return str_
341
342 2398 aaronmk
##### Condition column comparisons
343
344 2514 aaronmk
class ValueCond(BasicObject):
345 2213 aaronmk
    def __init__(self, value):
346 2225 aaronmk
        if not isinstance(value, Code): value = Literal(value)
347 2462 aaronmk
        value = remove_col_rename(value)
348 2213 aaronmk
349
        self.value = value
350 2214 aaronmk
351 2216 aaronmk
    def to_str(self, db, left_value):
352 2214 aaronmk
        '''
353 2216 aaronmk
        @param left_value The Code object that the condition is being applied on
354 2214 aaronmk
        '''
355
        raise NotImplemented()
356 2228 aaronmk
357 2514 aaronmk
    def __repr__(self): return self.to_str(mockDb, '<left_value>')
358 2211 aaronmk
359
class CompareCond(ValueCond):
360
    def __init__(self, value, operator='='):
361 2222 aaronmk
        '''
362
        @param operator By default, compares NULL values literally. Use '~=' or
363
            '~!=' to pass NULLs through.
364
        '''
365 2211 aaronmk
        ValueCond.__init__(self, value)
366
        self.operator = operator
367
368 2216 aaronmk
    def to_str(self, db, left_value):
369
        if not isinstance(left_value, Code): left_value = Col(left_value)
370 2462 aaronmk
        left_value = remove_col_rename(left_value)
371 2216 aaronmk
372 2222 aaronmk
        right_value = self.value
373
        left = left_value.to_str(db)
374
        right = right_value.to_str(db)
375
376
        # Parse operator
377 2216 aaronmk
        operator = self.operator
378 2222 aaronmk
        passthru_null_ref = [False]
379
        operator = strings.remove_prefix('~', operator, passthru_null_ref)
380
        neg_ref = [False]
381
        operator = strings.remove_prefix('!', operator, neg_ref)
382
        equals = operator.endswith('=')
383
        if equals and is_null(self.value): operator = 'IS'
384
385
        # Create str
386
        str_ = left+' '+operator+' '+right
387
        if equals and not passthru_null_ref[0] and isinstance(right_value, Col):
388 2578 aaronmk
            str_ = '('+str_+' OR ('+left+' IS NULL AND '+right+' IS NULL))'
389
        if neg_ref[0]: str_ = 'NOT '+str_
390 2222 aaronmk
        return str_
391 2216 aaronmk
392 2260 aaronmk
# Tells as_ValueCond() to assume a non-ValueCond is a literal value
393
assume_literal = object()
394
395
def as_ValueCond(value, default_table=assume_literal):
396
    if not isinstance(value, ValueCond):
397
        if default_table is not assume_literal:
398 2748 aaronmk
            value = with_default_table(value, default_table)
399 2260 aaronmk
        return CompareCond(value)
400 2216 aaronmk
    else: return value
401 2219 aaronmk
402 2335 aaronmk
##### Joins
403
404 2352 aaronmk
join_same = object() # tells Join the left and right columns have the same name
405 2260 aaronmk
406 2353 aaronmk
# Tells Join the left and right columns have the same name and are never NULL
407
join_same_not_null = object()
408
409 2260 aaronmk
filter_out = object() # tells Join to filter out rows that match the join
410
411 2514 aaronmk
class Join(BasicObject):
412 2746 aaronmk
    def __init__(self, table, mapping={}, type_=None):
413 2260 aaronmk
        '''
414
        @param mapping dict(right_table_col=left_table_col, ...)
415 2352 aaronmk
            * if left_table_col is join_same: left_table_col = right_table_col
416 2353 aaronmk
              * Note that right_table_col must be a string
417
            * if left_table_col is join_same_not_null:
418
              left_table_col = right_table_col and both have NOT NULL constraint
419
              * Note that right_table_col must be a string
420 2260 aaronmk
        @param type_ None (for plain join)|str (e.g. 'LEFT')|filter_out
421
            * filter_out: equivalent to 'LEFT' with the query filtered by
422
              `table_pkey IS NULL` (indicating no match)
423
        '''
424
        if util.is_str(table): table = Table(table)
425
        assert type_ == None or util.is_str(type_) or type_ is filter_out
426
427
        self.table = table
428
        self.mapping = mapping
429
        self.type_ = type_
430
431 2749 aaronmk
    def to_str(self, db, left_table_):
432 2260 aaronmk
        def join(entry):
433
            '''Parses non-USING joins'''
434
            right_table_col, left_table_col = entry
435
436 2353 aaronmk
            # Switch order (right_table_col is on the left in the comparison)
437
            left = right_table_col
438
            right = left_table_col
439 2749 aaronmk
            left_table = self.table
440
            right_table = left_table_
441 2353 aaronmk
442 2749 aaronmk
            left_table = left_table.to_Table()
443
            right_table = right_table.to_Table()
444
445 2747 aaronmk
            # Parse left side
446 2748 aaronmk
            left = with_default_table(left, left_table)
447 2747 aaronmk
448 2260 aaronmk
            # Parse special values
449 2747 aaronmk
            left_on_right = Col(left.name, right_table)
450
            if right is join_same: right = left_on_right
451 2353 aaronmk
            elif right is join_same_not_null:
452 2747 aaronmk
                right = CompareCond(left_on_right, '~=')
453 2260 aaronmk
454 2747 aaronmk
            # Parse right side
455 2353 aaronmk
            right = as_ValueCond(right, right_table)
456 2747 aaronmk
457
            return right.to_str(db, left)
458 2260 aaronmk
459 2265 aaronmk
        # Create join condition
460
        type_ = self.type_
461 2276 aaronmk
        joins = self.mapping
462 2746 aaronmk
        if joins == {}: join_cond = None
463
        elif type_ is not filter_out and reduce(operator.and_,
464 2460 aaronmk
            (v is join_same_not_null for v in joins.itervalues())):
465 2260 aaronmk
            # all cols w/ USING, so can use simpler USING syntax
466 2747 aaronmk
            cols = map(to_name_only_col, joins.iterkeys())
467
            join_cond = 'USING ('+(', '.join((c.to_str(db) for c in cols)))+')'
468 2576 aaronmk
        else:
469
            if len(joins) == 1: whitespace = ' '
470
            else: whitespace = '\n'
471 2577 aaronmk
            join_cond = combine_conds(map(join, joins.iteritems()), 'ON')
472 2260 aaronmk
473
        # Create join
474
        if type_ is filter_out: type_ = 'LEFT'
475 2266 aaronmk
        str_ = ''
476
        if type_ != None: str_ += type_+' '
477 2749 aaronmk
        str_ += 'JOIN '+self.table.to_str(db)
478 2746 aaronmk
        if join_cond != None: str_ += ' '+join_cond
479 2266 aaronmk
        return str_
480 2349 aaronmk
481 2514 aaronmk
    def __repr__(self): return self.to_str(mockDb, '<left_table>')
482 2424 aaronmk
483
##### Value exprs
484
485 2737 aaronmk
default = CustomCode('DEFAULT')
486
487 2424 aaronmk
row_count = CustomCode('count(*)')
488 2674 aaronmk
489 2692 aaronmk
def EnsureNotNull(value, null=r'\N'):
490 2694 aaronmk
    return FunctionCall(InternalFunction('coalesce'), as_Col(value), null)
491 2692 aaronmk
492 2737 aaronmk
##### Table exprs
493
494
class Values(Code):
495
    def __init__(self, values):
496 2739 aaronmk
        '''
497
        @param values [...]|[[...], ...] Can be one or multiple rows.
498
        '''
499
        rows = values
500
        if len(values) >= 1 and not lists.is_seq(values[0]): # only one row
501
            rows = [values]
502
        for i, row in enumerate(rows):
503
            rows[i] = map(remove_col_rename, map(as_Value, row))
504 2737 aaronmk
505 2739 aaronmk
        self.rows = rows
506 2737 aaronmk
507
    def to_str(self, db):
508 2739 aaronmk
        def row_str(row):
509
            return '('+(', '.join((v.to_str(db) for v in row)))+')'
510
        return 'VALUES '+(', '.join(map(row_str, self.rows)))
511 2737 aaronmk
512 2740 aaronmk
def NamedValues(name, cols, values):
513 2745 aaronmk
    '''
514
    @post `cols` will be changed to Col objects with the table set to `name`.
515
    '''
516
    set_cols_table(name, cols)
517 2740 aaronmk
    return NamedTable(name, Values(values), cols)
518
519 2674 aaronmk
##### Database structure
520
521
class TypedCol(Col):
522
    def __init__(self, name, type_):
523
        Col.__init__(self, name)
524
525
        self.type = type_
526
527
    def to_str(self, db): return Col.to_str(self, db)+' '+self.type
528
529
    def to_Col(self): return Col(self.name)