Project

General

Profile

1
# SQL code generation
2

    
3
import operator
4
import re
5
import UserDict
6

    
7
import dicts
8
import iters
9
import lists
10
import objects
11
import strings
12
import util
13

    
14
##### Names
15

    
16
identifier_max_len = 63 # works for both PostgreSQL and MySQL
17

    
18
def add_suffix(str_, suffix):
19
    '''Preserves version so that it won't be truncated off the string, leading
20
    to collisions.'''
21
    # Preserve version
22
    before, sep, version = str_.rpartition('#')
23
    if sep != '': # found match
24
        str_ = before
25
        suffix = sep+version+suffix
26
    
27
    return strings.add_suffix(str_, suffix, identifier_max_len)
28

    
29
def is_safe_name(name):
30
    '''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

    
37
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
def clean_name(name): return name.replace('"', '').replace('`', '')
42

    
43
##### General SQL code objects
44

    
45
class MockDb:
46
    def esc_value(self, value): return strings.repr_no_u(value)
47
    
48
    def esc_name(self, name): return esc_name(name)
49
mockDb = MockDb()
50

    
51
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
##### Unparameterized code objects
57

    
58
class Code(BasicObject):
59
    def to_str(self, db): raise NotImplementedError()
60
    
61
    def __repr__(self): return self.to_str(mockDb)
62

    
63
class CustomCode(Code):
64
    def __init__(self, str_): self.str_ = str_
65
    
66
    def to_str(self, db): return self.str_
67

    
68
def as_Code(value):
69
    if util.is_str(value): return CustomCode(value)
70
    else: return Literal(value)
71

    
72
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
##### Literal values
78

    
79
class Literal(Code):
80
    def __init__(self, value): self.value = value
81
    
82
    def to_str(self, db): return db.esc_value(self.value)
83

    
84
def as_Value(value):
85
    if isinstance(value, Code): return value
86
    else: return Literal(value)
87

    
88
def is_null(value): return isinstance(value, Literal) and value.value == None
89

    
90
##### 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
        '''An element which was derived from some other element(s).
97
        @param srcs See self.set_srcs()
98
        '''
99
        self.set_srcs(srcs)
100
    
101
    def set_srcs(self, srcs, overwrite=True):
102
        '''
103
        @param srcs (self_type...)|src_self The element(s) this is derived from
104
        '''
105
        if not overwrite and self.srcs != (): return # already set
106
        
107
        if srcs == src_self: srcs = (self,)
108
        srcs = tuple(srcs) # make Col hashable
109
        self.srcs = srcs
110
    
111
    def _compare_on(self):
112
        compare_on = self.__dict__.copy()
113
        del compare_on['srcs'] # ignore
114
        return compare_on
115

    
116
def cols_srcs(cols): return lists.uniqify(iters.flatten((v.srcs for v in cols)))
117

    
118
##### Tables
119

    
120
class Table(Derived):
121
    def __init__(self, name, schema=None, srcs=()):
122
        '''
123
        @param schema str|None (for no schema)
124
        @param srcs (Table...)|src_self See Derived.set_srcs()
125
        '''
126
        Derived.__init__(self, srcs)
127
        
128
        self.name = name
129
        self.schema = schema
130
    
131
    def to_str(self, db):
132
        str_ = ''
133
        if self.schema != None: str_ += db.esc_name(self.schema)+'.'
134
        str_ += db.esc_name(self.name)
135
        return str_
136
    
137
    def to_Table(self): return self
138

    
139
def as_Table(table):
140
    if table == None or isinstance(table, Code): return table
141
    else: return Table(table)
142

    
143
def suffixed_table(table, suffix): return Table(table.name+suffix, table.schema)
144

    
145
class NamedTable(Table):
146
    def __init__(self, name, code, cols=None):
147
        Table.__init__(self, name)
148
        
149
        if not isinstance(code, Code): code = Table(code)
150
        
151
        self.code = code
152
        self.cols = cols
153
    
154
    def to_str(self, db):
155
        str_ = self.code.to_str(db)+'\nAS '+Table.to_str(self, db)
156
        if self.cols != None: str_ += ' ('+(', '.join(self.cols))+')'
157
        return str_
158
    
159
    def to_Table(self): return Table(self.name)
160

    
161
##### Columns
162

    
163
class Col(Derived):
164
    def __init__(self, name, table=None, srcs=()):
165
        '''
166
        @param table Table|None (for no table)
167
        @param srcs (Col...)|src_self See Derived.set_srcs()
168
        '''
169
        Derived.__init__(self, srcs)
170
        
171
        if util.is_str(table): table = Table(table)
172
        assert table == None or isinstance(table, Table)
173
        
174
        self.name = name
175
        self.table = table
176
    
177
    def to_str(self, db):
178
        str_ = ''
179
        if self.table != None: str_ += self.table.to_str(db)+'.'
180
        str_ += db.esc_name(self.name)
181
        return str_
182
    
183
    def to_Col(self): return self
184

    
185
def is_table_col(col): return col.table != None
186

    
187
def as_Col(col, table=None, name=None):
188
    '''
189
    @param name If not None, any non-Col input will be renamed using NamedCol.
190
    '''
191
    if name != None:
192
        col = as_Value(col)
193
        if not isinstance(col, Col): col = NamedCol(name, col)
194
    
195
    if isinstance(col, Code): return col
196
    else: return Col(col, table)
197

    
198
def to_name_only_col(col, check_table=None):
199
    col = as_Col(col)
200
    if not isinstance(col, Col): return col
201
    
202
    if check_table != None:
203
        table = col.table
204
        assert table == None or table == check_table
205
    return Col(col.name)
206

    
207
class NamedCol(Col):
208
    def __init__(self, name, code):
209
        Col.__init__(self, name)
210
        
211
        if not isinstance(code, Code): code = Literal(code)
212
        
213
        self.code = code
214
    
215
    def to_str(self, db):
216
        return self.code.to_str(db)+' AS '+Col.to_str(self, db)
217
    
218
    def to_Col(self): return Col(self.name)
219

    
220
def remove_col_rename(col):
221
    if isinstance(col, NamedCol): col = col.code
222
    return col
223

    
224
def wrap(wrap_func, value):
225
    '''Wraps a value, propagating any column renaming to the returned value.'''
226
    if isinstance(value, NamedCol):
227
        return NamedCol(value.name, wrap_func(value.code))
228
    else: return wrap_func(value)
229

    
230
class ColDict(dicts.DictProxy):
231
    '''A dict that automatically makes inserted entries Col objects'''
232
    
233
    def __init__(self, db, keys_table, dict_={}):
234
        dicts.DictProxy.__init__(self, {})
235
        
236
        keys_table = as_Table(keys_table)
237
        
238
        self.db = db
239
        self.table = keys_table
240
        self.update(dict_) # after setting vars because __setitem__() needs them
241
    
242
    def copy(self): return ColDict(self.db, self.table, self.inner.copy())
243
    
244
    def __getitem__(self, key):
245
        return dicts.DictProxy.__getitem__(self, self._key(key))
246
    
247
    def __setitem__(self, key, value):
248
        key = self._key(key)
249
        if value == None: value = self.db.col_default(key)
250
        dicts.DictProxy.__setitem__(self, key, as_Col(value, name=key.name))
251
    
252
    def _key(self, key): return as_Col(key, self.table)
253

    
254
##### Functions
255

    
256
class Function(Table): pass
257

    
258
def TempFunction(name, autocommit):
259
    schema = None
260
    if not autocommit: schema = 'pg_temp'
261
    return Function(name, schema)
262

    
263
class InternalFunction(CustomCode): pass
264

    
265
class FunctionCall(Code):
266
    def __init__(self, function, *args):
267
        '''
268
        @param args [Code|literal-value...] The function's arguments
269
        '''
270
        if not isinstance(function, Code): function = Function(function)
271
        args = map(remove_col_rename, map(as_Value, args))
272
        
273
        self.function = function
274
        self.args = args
275
    
276
    def to_str(self, db):
277
        args_str = ', '.join((v.to_str(db) for v in self.args))
278
        return self.function.to_str(db)+'('+args_str+')'
279

    
280
def wrap_in_func(function, value):
281
    '''Wraps a value inside a function call.
282
    Propagates any column renaming to the returned value.
283
    '''
284
    return wrap(lambda v: FunctionCall(function, v), value)
285

    
286
def unwrap_func_call(func_call, check_name=None):
287
    '''Unwraps any function call to its first argument.
288
    Also removes any column renaming.
289
    '''
290
    func_call = remove_col_rename(func_call)
291
    if not isinstance(func_call, FunctionCall): return func_call
292
    
293
    if check_name != None:
294
        name = func_call.function.name
295
        assert name == None or name == check_name
296
    return func_call.args[0]
297

    
298
##### Conditions
299

    
300
class ColValueCond(Code):
301
    def __init__(self, col, value):
302
        value = as_ValueCond(value)
303
        
304
        self.col = col
305
        self.value = value
306
    
307
    def to_str(self, db): return self.value.to_str(db, self.col)
308

    
309
def combine_conds(conds, keyword=None):
310
    '''
311
    @param keyword The keyword to add before the conditions, if any
312
    '''
313
    str_ = ''
314
    if keyword != None:
315
        if conds == []: whitespace = ''
316
        elif len(conds) == 1: whitespace = ' '
317
        else: whitespace = '\n'
318
        str_ += keyword+whitespace
319
    
320
    str_ += '\nAND '.join(conds)
321
    return str_
322

    
323
##### Condition column comparisons
324

    
325
class ValueCond(BasicObject):
326
    def __init__(self, value):
327
        if not isinstance(value, Code): value = Literal(value)
328
        value = remove_col_rename(value)
329
        
330
        self.value = value
331
    
332
    def to_str(self, db, left_value):
333
        '''
334
        @param left_value The Code object that the condition is being applied on
335
        '''
336
        raise NotImplemented()
337
    
338
    def __repr__(self): return self.to_str(mockDb, '<left_value>')
339

    
340
class CompareCond(ValueCond):
341
    def __init__(self, value, operator='='):
342
        '''
343
        @param operator By default, compares NULL values literally. Use '~=' or
344
            '~!=' to pass NULLs through.
345
        '''
346
        ValueCond.__init__(self, value)
347
        self.operator = operator
348
    
349
    def to_str(self, db, left_value):
350
        if not isinstance(left_value, Code): left_value = Col(left_value)
351
        left_value = remove_col_rename(left_value)
352
        
353
        right_value = self.value
354
        left = left_value.to_str(db)
355
        right = right_value.to_str(db)
356
        
357
        # Parse operator
358
        operator = self.operator
359
        passthru_null_ref = [False]
360
        operator = strings.remove_prefix('~', operator, passthru_null_ref)
361
        neg_ref = [False]
362
        operator = strings.remove_prefix('!', operator, neg_ref)
363
        equals = operator.endswith('=')
364
        if equals and is_null(self.value): operator = 'IS'
365
        
366
        # Create str
367
        str_ = left+' '+operator+' '+right
368
        if equals and not passthru_null_ref[0] and isinstance(right_value, Col):
369
            str_ = '('+str_+' OR ('+left+' IS NULL AND '+right+' IS NULL))'
370
        if neg_ref[0]: str_ = 'NOT '+str_
371
        return str_
372

    
373
# Tells as_ValueCond() to assume a non-ValueCond is a literal value
374
assume_literal = object()
375

    
376
def as_ValueCond(value, default_table=assume_literal):
377
    if not isinstance(value, ValueCond):
378
        if default_table is not assume_literal:
379
            value = as_Col(value, default_table)
380
        return CompareCond(value)
381
    else: return value
382

    
383
##### Joins
384

    
385
join_same = object() # tells Join the left and right columns have the same name
386

    
387
# Tells Join the left and right columns have the same name and are never NULL
388
join_same_not_null = object()
389

    
390
filter_out = object() # tells Join to filter out rows that match the join
391

    
392
class Join(BasicObject):
393
    def __init__(self, table, mapping, type_=None):
394
        '''
395
        @param mapping dict(right_table_col=left_table_col, ...)
396
            * if left_table_col is join_same: left_table_col = right_table_col
397
              * Note that right_table_col must be a string
398
            * if left_table_col is join_same_not_null:
399
              left_table_col = right_table_col and both have NOT NULL constraint
400
              * Note that right_table_col must be a string
401
        @param type_ None (for plain join)|str (e.g. 'LEFT')|filter_out
402
            * filter_out: equivalent to 'LEFT' with the query filtered by
403
              `table_pkey IS NULL` (indicating no match)
404
        '''
405
        if util.is_str(table): table = Table(table)
406
        assert type_ == None or util.is_str(type_) or type_ is filter_out
407
        
408
        self.table = table
409
        self.mapping = mapping
410
        self.type_ = type_
411
    
412
    def to_str(self, db, left_table):
413
        # Switch order (left_table is on the right in the comparison)
414
        right_table = left_table
415
        left_table = self.table # note left_table is reassigned
416
        
417
        def join(entry):
418
            '''Parses non-USING joins'''
419
            right_table_col, left_table_col = entry
420
            
421
            # Switch order (right_table_col is on the left in the comparison)
422
            left = right_table_col
423
            right = left_table_col
424
            
425
            # Parse special values
426
            if right is join_same: right = left
427
            elif right is join_same_not_null:
428
                right = CompareCond(as_Col(left, right_table), '~=')
429
            
430
            right = as_ValueCond(right, right_table)
431
            return right.to_str(db, as_Col(left, left_table))
432
        
433
        # Create join condition
434
        type_ = self.type_
435
        joins = self.mapping
436
        if type_ is not filter_out and reduce(operator.and_,
437
            (v is join_same_not_null for v in joins.itervalues())):
438
            # all cols w/ USING, so can use simpler USING syntax
439
            cols = (as_Col(v).to_str(db) for v in joins.iterkeys())
440
            join_cond = 'USING ('+(', '.join(cols))+')'
441
        else:
442
            if len(joins) == 1: whitespace = ' '
443
            else: whitespace = '\n'
444
            join_cond = combine_conds(map(join, joins.iteritems()), 'ON')
445
        
446
        # Create join
447
        if type_ is filter_out: type_ = 'LEFT'
448
        str_ = ''
449
        if type_ != None: str_ += type_+' '
450
        str_ += 'JOIN '+left_table.to_str(db)+' '+join_cond
451
        return str_
452
    
453
    def __repr__(self): return self.to_str(mockDb, '<left_table>')
454

    
455
##### Value exprs
456

    
457
row_count = CustomCode('count(*)')
458

    
459
def EnsureNotNull(value, null=r'\N'):
460
    return FunctionCall(InternalFunction('coalesce'), as_Col(value), null)
461

    
462
##### Database structure
463

    
464
class TypedCol(Col):
465
    def __init__(self, name, type_):
466
        Col.__init__(self, name)
467
        
468
        self.type = type_
469
    
470
    def to_str(self, db): return Col.to_str(self, db)+' '+self.type
471
    
472
    def to_Col(self): return Col(self.name)
(25-25/36)