Project

General

Profile

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