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 2335 aaronmk
##### Tables
91
92 2211 aaronmk
class Table(Code):
93
    def __init__(self, name, schema=None):
94
        '''
95
        @param schema str|None (for no schema)
96
        '''
97
        self.name = name
98
        self.schema = schema
99
100 2348 aaronmk
    def to_str(self, db):
101
        str_ = ''
102
        if self.schema != None: str_ += db.esc_name(self.schema)+'.'
103
        str_ += db.esc_name(self.name)
104
        return str_
105 2336 aaronmk
106
    def to_Table(self): return self
107 2211 aaronmk
108 2219 aaronmk
def as_Table(table):
109 2270 aaronmk
    if table == None or isinstance(table, Code): return table
110 2219 aaronmk
    else: return Table(table)
111
112 2336 aaronmk
class NamedTable(Table):
113
    def __init__(self, name, code, cols=None):
114
        Table.__init__(self, name)
115
116
        if not isinstance(code, Code): code = Table(code)
117
118
        self.code = code
119
        self.cols = cols
120
121
    def to_str(self, db):
122 2467 aaronmk
        str_ = self.code.to_str(db)+'\nAS '+Table.to_str(self, db)
123 2336 aaronmk
        if self.cols != None: str_ += ' ('+(', '.join(self.cols))+')'
124
        return str_
125
126
    def to_Table(self): return Table(self.name)
127
128 2335 aaronmk
##### Columns
129
130 2701 aaronmk
src_self = object() # tells Col that it is its own source column
131
132 2211 aaronmk
class Col(Code):
133 2701 aaronmk
    def __init__(self, name, table=None, srcs=()):
134 2211 aaronmk
        '''
135
        @param table Table|None (for no table)
136 2701 aaronmk
        @param srcs See self.set_srcs()
137 2211 aaronmk
        '''
138 2241 aaronmk
        if util.is_str(table): table = Table(table)
139 2211 aaronmk
        assert table == None or isinstance(table, Table)
140
141
        self.name = name
142
        self.table = table
143 2701 aaronmk
        self.set_srcs(srcs)
144 2211 aaronmk
145
    def to_str(self, db):
146
        str_ = ''
147
        if self.table != None: str_ += self.table.to_str(db)+'.'
148 2348 aaronmk
        str_ += db.esc_name(self.name)
149 2211 aaronmk
        return str_
150 2314 aaronmk
151
    def to_Col(self): return self
152 2701 aaronmk
153
    def set_srcs(self, srcs):
154
        '''
155
        @param srcs (Col...)|src_self The column(s) this column is derived from
156
        '''
157
        if srcs == src_self: srcs = (self,)
158
        srcs = tuple(srcs) # make Col hashable
159
        self.srcs = srcs
160
161
    def _compare_on(self):
162
        compare_on = self.__dict__.copy()
163
        del compare_on['srcs'] # ignore
164
        return compare_on
165 2211 aaronmk
166 2393 aaronmk
def is_table_col(col): return col.table != None
167
168 2701 aaronmk
def cols_srcs(cols): return lists.uniqify(iters.flatten((v.srcs for v in cols)))
169
170 2563 aaronmk
def as_Col(col, table=None, name=None):
171
    '''
172
    @param name If not None, any non-Col input will be renamed using NamedCol.
173
    '''
174
    if name != None:
175
        col = as_Value(col)
176
        if not isinstance(col, Col): col = NamedCol(name, col)
177 2333 aaronmk
178
    if isinstance(col, Code): return col
179 2260 aaronmk
    else: return Col(col, table)
180
181 2401 aaronmk
def to_name_only_col(col, check_table=None):
182
    col = as_Col(col)
183 2579 aaronmk
    if not isinstance(col, Col): return col
184 2401 aaronmk
185
    if check_table != None:
186
        table = col.table
187
        assert table == None or table == check_table
188
    return Col(col.name)
189
190 2323 aaronmk
class NamedCol(Col):
191 2229 aaronmk
    def __init__(self, name, code):
192 2310 aaronmk
        Col.__init__(self, name)
193
194 2229 aaronmk
        if not isinstance(code, Code): code = Literal(code)
195
196
        self.code = code
197
198
    def to_str(self, db):
199 2310 aaronmk
        return self.code.to_str(db)+' AS '+Col.to_str(self, db)
200 2314 aaronmk
201
    def to_Col(self): return Col(self.name)
202 2229 aaronmk
203 2462 aaronmk
def remove_col_rename(col):
204
    if isinstance(col, NamedCol): col = col.code
205
    return col
206
207 2667 aaronmk
class ColDict(dicts.DictProxy):
208 2564 aaronmk
    '''A dict that automatically makes inserted entries Col objects'''
209
210 2645 aaronmk
    def __init__(self, db, keys_table, dict_={}):
211 2667 aaronmk
        dicts.DictProxy.__init__(self, {})
212
213 2645 aaronmk
        keys_table = as_Table(keys_table)
214
215 2642 aaronmk
        self.db = db
216 2641 aaronmk
        self.table = keys_table
217 2653 aaronmk
        self.update(dict_) # after setting vars because __setitem__() needs them
218 2641 aaronmk
219 2667 aaronmk
    def copy(self): return ColDict(self.db, self.table, self.inner.copy())
220 2655 aaronmk
221 2667 aaronmk
    def __getitem__(self, key):
222
        return dicts.DictProxy.__getitem__(self, self._key(key))
223 2653 aaronmk
224 2564 aaronmk
    def __setitem__(self, key, value):
225 2642 aaronmk
        key = self._key(key)
226 2661 aaronmk
        if value == None: value = self.db.col_default(key)
227 2667 aaronmk
        dicts.DictProxy.__setitem__(self, key, as_Col(value, name=key.name))
228 2564 aaronmk
229 2641 aaronmk
    def _key(self, key): return as_Col(key, self.table)
230 2564 aaronmk
231 2524 aaronmk
##### Functions
232
233
class Function(Table): pass
234
235 2697 aaronmk
def TempFunction(name, autocommit):
236
    schema = None
237
    if not autocommit: schema = 'pg_temp'
238
    return Function(name, schema)
239
240 2691 aaronmk
class InternalFunction(CustomCode): pass
241
242 2524 aaronmk
class FunctionCall(Code):
243
    def __init__(self, function, *args):
244
        '''
245 2690 aaronmk
        @param args [Code|literal-value...] The function's arguments
246 2524 aaronmk
        '''
247
        if not isinstance(function, Code): function = Function(function)
248 2690 aaronmk
        args = map(remove_col_rename, map(as_Value, args))
249 2524 aaronmk
250
        self.function = function
251
        self.args = args
252
253
    def to_str(self, db):
254
        args_str = ', '.join((v.to_str(db) for v in self.args))
255
        return self.function.to_str(db)+'('+args_str+')'
256
257 2533 aaronmk
def wrap_in_func(function, value):
258
    '''Wraps a value inside a function call.
259
    Propagates any column renaming to the returned value.
260
    '''
261
    name = None
262
    if isinstance(value, NamedCol): name = value.name
263
    value = FunctionCall(function, value)
264
    if name != None: value = NamedCol(name, value)
265
    return value
266
267 2561 aaronmk
def unwrap_func_call(func_call, check_name=None):
268
    '''Unwraps any function call to its first argument.
269
    Also removes any column renaming.
270
    '''
271
    func_call = remove_col_rename(func_call)
272
    if not isinstance(func_call, FunctionCall): return func_call
273
274
    if check_name != None:
275
        name = func_call.function.name
276
        assert name == None or name == check_name
277
    return func_call.args[0]
278
279 2335 aaronmk
##### Conditions
280 2259 aaronmk
281 2398 aaronmk
class ColValueCond(Code):
282
    def __init__(self, col, value):
283
        value = as_ValueCond(value)
284
285
        self.col = col
286
        self.value = value
287
288
    def to_str(self, db): return self.value.to_str(db, self.col)
289
290 2577 aaronmk
def combine_conds(conds, keyword=None):
291
    '''
292
    @param keyword The keyword to add before the conditions, if any
293
    '''
294
    str_ = ''
295
    if keyword != None:
296
        if conds == []: whitespace = ''
297
        elif len(conds) == 1: whitespace = ' '
298
        else: whitespace = '\n'
299
        str_ += keyword+whitespace
300
301
    str_ += '\nAND '.join(conds)
302
    return str_
303
304 2398 aaronmk
##### Condition column comparisons
305
306 2514 aaronmk
class ValueCond(BasicObject):
307 2213 aaronmk
    def __init__(self, value):
308 2225 aaronmk
        if not isinstance(value, Code): value = Literal(value)
309 2462 aaronmk
        value = remove_col_rename(value)
310 2213 aaronmk
311
        self.value = value
312 2214 aaronmk
313 2216 aaronmk
    def to_str(self, db, left_value):
314 2214 aaronmk
        '''
315 2216 aaronmk
        @param left_value The Code object that the condition is being applied on
316 2214 aaronmk
        '''
317
        raise NotImplemented()
318 2228 aaronmk
319 2514 aaronmk
    def __repr__(self): return self.to_str(mockDb, '<left_value>')
320 2211 aaronmk
321
class CompareCond(ValueCond):
322
    def __init__(self, value, operator='='):
323 2222 aaronmk
        '''
324
        @param operator By default, compares NULL values literally. Use '~=' or
325
            '~!=' to pass NULLs through.
326
        '''
327 2211 aaronmk
        ValueCond.__init__(self, value)
328
        self.operator = operator
329
330 2216 aaronmk
    def to_str(self, db, left_value):
331
        if not isinstance(left_value, Code): left_value = Col(left_value)
332 2462 aaronmk
        left_value = remove_col_rename(left_value)
333 2216 aaronmk
334 2222 aaronmk
        right_value = self.value
335
        left = left_value.to_str(db)
336
        right = right_value.to_str(db)
337
338
        # Parse operator
339 2216 aaronmk
        operator = self.operator
340 2222 aaronmk
        passthru_null_ref = [False]
341
        operator = strings.remove_prefix('~', operator, passthru_null_ref)
342
        neg_ref = [False]
343
        operator = strings.remove_prefix('!', operator, neg_ref)
344
        equals = operator.endswith('=')
345
        if equals and is_null(self.value): operator = 'IS'
346
347
        # Create str
348
        str_ = left+' '+operator+' '+right
349
        if equals and not passthru_null_ref[0] and isinstance(right_value, Col):
350 2578 aaronmk
            str_ = '('+str_+' OR ('+left+' IS NULL AND '+right+' IS NULL))'
351
        if neg_ref[0]: str_ = 'NOT '+str_
352 2222 aaronmk
        return str_
353 2216 aaronmk
354 2260 aaronmk
# Tells as_ValueCond() to assume a non-ValueCond is a literal value
355
assume_literal = object()
356
357
def as_ValueCond(value, default_table=assume_literal):
358
    if not isinstance(value, ValueCond):
359
        if default_table is not assume_literal:
360
            value = as_Col(value, default_table)
361
        return CompareCond(value)
362 2216 aaronmk
    else: return value
363 2219 aaronmk
364 2335 aaronmk
##### Joins
365
366 2352 aaronmk
join_same = object() # tells Join the left and right columns have the same name
367 2260 aaronmk
368 2353 aaronmk
# Tells Join the left and right columns have the same name and are never NULL
369
join_same_not_null = object()
370
371 2260 aaronmk
filter_out = object() # tells Join to filter out rows that match the join
372
373 2514 aaronmk
class Join(BasicObject):
374 2260 aaronmk
    def __init__(self, table, mapping, type_=None):
375
        '''
376
        @param mapping dict(right_table_col=left_table_col, ...)
377 2352 aaronmk
            * if left_table_col is join_same: left_table_col = right_table_col
378 2353 aaronmk
              * Note that right_table_col must be a string
379
            * if left_table_col is join_same_not_null:
380
              left_table_col = right_table_col and both have NOT NULL constraint
381
              * Note that right_table_col must be a string
382 2260 aaronmk
        @param type_ None (for plain join)|str (e.g. 'LEFT')|filter_out
383
            * filter_out: equivalent to 'LEFT' with the query filtered by
384
              `table_pkey IS NULL` (indicating no match)
385
        '''
386
        if util.is_str(table): table = Table(table)
387
        assert type_ == None or util.is_str(type_) or type_ is filter_out
388
389
        self.table = table
390
        self.mapping = mapping
391
        self.type_ = type_
392
393
    def to_str(self, db, left_table):
394 2353 aaronmk
        # Switch order (left_table is on the right in the comparison)
395
        right_table = left_table
396
        left_table = self.table # note left_table is reassigned
397
398 2260 aaronmk
        def join(entry):
399
            '''Parses non-USING joins'''
400
            right_table_col, left_table_col = entry
401
402 2353 aaronmk
            # Switch order (right_table_col is on the left in the comparison)
403
            left = right_table_col
404
            right = left_table_col
405
406 2260 aaronmk
            # Parse special values
407 2353 aaronmk
            if right is join_same: right = left
408
            elif right is join_same_not_null:
409
                right = CompareCond(as_Col(left, right_table), '~=')
410 2260 aaronmk
411 2353 aaronmk
            right = as_ValueCond(right, right_table)
412 2578 aaronmk
            return right.to_str(db, as_Col(left, left_table))
413 2260 aaronmk
414 2265 aaronmk
        # Create join condition
415
        type_ = self.type_
416 2276 aaronmk
        joins = self.mapping
417 2265 aaronmk
        if type_ is not filter_out and reduce(operator.and_,
418 2460 aaronmk
            (v is join_same_not_null for v in joins.itervalues())):
419 2260 aaronmk
            # all cols w/ USING, so can use simpler USING syntax
420 2298 aaronmk
            cols = (as_Col(v).to_str(db) for v in joins.iterkeys())
421
            join_cond = 'USING ('+(', '.join(cols))+')'
422 2576 aaronmk
        else:
423
            if len(joins) == 1: whitespace = ' '
424
            else: whitespace = '\n'
425 2577 aaronmk
            join_cond = combine_conds(map(join, joins.iteritems()), 'ON')
426 2260 aaronmk
427
        # Create join
428
        if type_ is filter_out: type_ = 'LEFT'
429 2266 aaronmk
        str_ = ''
430
        if type_ != None: str_ += type_+' '
431 2353 aaronmk
        str_ += 'JOIN '+left_table.to_str(db)+' '+join_cond
432 2266 aaronmk
        return str_
433 2349 aaronmk
434 2514 aaronmk
    def __repr__(self): return self.to_str(mockDb, '<left_table>')
435 2424 aaronmk
436
##### Value exprs
437
438
row_count = CustomCode('count(*)')
439 2674 aaronmk
440 2692 aaronmk
def EnsureNotNull(value, null=r'\N'):
441 2694 aaronmk
    return FunctionCall(InternalFunction('coalesce'), as_Col(value), null)
442 2692 aaronmk
443 2674 aaronmk
##### Database structure
444
445
class TypedCol(Col):
446
    def __init__(self, name, type_):
447
        Col.__init__(self, name)
448
449
        self.type = type_
450
451
    def to_str(self, db): return Col.to_str(self, db)+' '+self.type
452
453
    def to_Col(self): return Col(self.name)