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
        if not isinstance(code, (Table, FunctionCall, Expr)): code = Expr(code)
151
        if cols != None: cols = map(to_name_only_col, cols)
152
        
153
        self.code = code
154
        self.cols = cols
155
    
156
    def to_str(self, db):
157
        str_ = self.code.to_str(db)+'\nAS '+Table.to_str(self, db)
158
        if self.cols != None:
159
            str_ += ' ('+(', '.join((c.to_str(db) for c in self.cols)))+')'
160
        return str_
161
    
162
    def to_Table(self): return Table(self.name)
163

    
164
##### Columns
165

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

    
188
def is_table_col(col): return col.table != None
189

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

    
201
def set_cols_table(table, cols):
202
    table = as_Table(table)
203
    
204
    for i, col in enumerate(cols):
205
        col = cols[i] = as_Col(col)
206
        col.table = table
207

    
208
def to_name_only_col(col, check_table=None):
209
    col = as_Col(col)
210
    if not isinstance(col, Col): return col
211
    
212
    if check_table != None:
213
        table = col.table
214
        assert table == None or table == check_table
215
    return Col(col.name)
216

    
217
class NamedCol(Col):
218
    def __init__(self, name, code):
219
        Col.__init__(self, name)
220
        
221
        if not isinstance(code, Code): code = Literal(code)
222
        
223
        self.code = code
224
    
225
    def to_str(self, db):
226
        return self.code.to_str(db)+' AS '+Col.to_str(self, db)
227
    
228
    def to_Col(self): return Col(self.name)
229

    
230
def remove_col_rename(col):
231
    if isinstance(col, NamedCol): col = col.code
232
    return col
233

    
234
def wrap(wrap_func, value):
235
    '''Wraps a value, propagating any column renaming to the returned value.'''
236
    if isinstance(value, NamedCol):
237
        return NamedCol(value.name, wrap_func(value.code))
238
    else: return wrap_func(value)
239

    
240
class ColDict(dicts.DictProxy):
241
    '''A dict that automatically makes inserted entries Col objects'''
242
    
243
    def __init__(self, db, keys_table, dict_={}):
244
        dicts.DictProxy.__init__(self, {})
245
        
246
        keys_table = as_Table(keys_table)
247
        
248
        self.db = db
249
        self.table = keys_table
250
        self.update(dict_) # after setting vars because __setitem__() needs them
251
    
252
    def copy(self): return ColDict(self.db, self.table, self.inner.copy())
253
    
254
    def __getitem__(self, key):
255
        return dicts.DictProxy.__getitem__(self, self._key(key))
256
    
257
    def __setitem__(self, key, value):
258
        key = self._key(key)
259
        if value == None: value = self.db.col_default(key)
260
        dicts.DictProxy.__setitem__(self, key, as_Col(value, name=key.name))
261
    
262
    def _key(self, key): return as_Col(key, self.table)
263

    
264
##### Functions
265

    
266
class Function(Table): pass
267

    
268
def TempFunction(name, autocommit):
269
    schema = None
270
    if not autocommit: schema = 'pg_temp'
271
    return Function(name, schema)
272

    
273
class InternalFunction(CustomCode): pass
274

    
275
class FunctionCall(Code):
276
    def __init__(self, function, *args):
277
        '''
278
        @param args [Code|literal-value...] The function's arguments
279
        '''
280
        if not isinstance(function, Code): function = Function(function)
281
        args = map(remove_col_rename, map(as_Value, args))
282
        
283
        self.function = function
284
        self.args = args
285
    
286
    def to_str(self, db):
287
        args_str = ', '.join((v.to_str(db) for v in self.args))
288
        return self.function.to_str(db)+'('+args_str+')'
289

    
290
def wrap_in_func(function, value):
291
    '''Wraps a value inside a function call.
292
    Propagates any column renaming to the returned value.
293
    '''
294
    return wrap(lambda v: FunctionCall(function, v), value)
295

    
296
def unwrap_func_call(func_call, check_name=None):
297
    '''Unwraps any function call to its first argument.
298
    Also removes any column renaming.
299
    '''
300
    func_call = remove_col_rename(func_call)
301
    if not isinstance(func_call, FunctionCall): return func_call
302
    
303
    if check_name != None:
304
        name = func_call.function.name
305
        assert name == None or name == check_name
306
    return func_call.args[0]
307

    
308
##### Conditions
309

    
310
class ColValueCond(Code):
311
    def __init__(self, col, value):
312
        value = as_ValueCond(value)
313
        
314
        self.col = col
315
        self.value = value
316
    
317
    def to_str(self, db): return self.value.to_str(db, self.col)
318

    
319
def combine_conds(conds, keyword=None):
320
    '''
321
    @param keyword The keyword to add before the conditions, if any
322
    '''
323
    str_ = ''
324
    if keyword != None:
325
        if conds == []: whitespace = ''
326
        elif len(conds) == 1: whitespace = ' '
327
        else: whitespace = '\n'
328
        str_ += keyword+whitespace
329
    
330
    str_ += '\nAND '.join(conds)
331
    return str_
332

    
333
##### Condition column comparisons
334

    
335
class ValueCond(BasicObject):
336
    def __init__(self, value):
337
        if not isinstance(value, Code): value = Literal(value)
338
        value = remove_col_rename(value)
339
        
340
        self.value = value
341
    
342
    def to_str(self, db, left_value):
343
        '''
344
        @param left_value The Code object that the condition is being applied on
345
        '''
346
        raise NotImplemented()
347
    
348
    def __repr__(self): return self.to_str(mockDb, '<left_value>')
349

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

    
383
# Tells as_ValueCond() to assume a non-ValueCond is a literal value
384
assume_literal = object()
385

    
386
def as_ValueCond(value, default_table=assume_literal):
387
    if not isinstance(value, ValueCond):
388
        if default_table is not assume_literal:
389
            value = as_Col(value, default_table)
390
        return CompareCond(value)
391
    else: return value
392

    
393
##### Joins
394

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

    
397
# Tells Join the left and right columns have the same name and are never NULL
398
join_same_not_null = object()
399

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

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

    
467
##### Value exprs
468

    
469
default = CustomCode('DEFAULT')
470

    
471
row_count = CustomCode('count(*)')
472

    
473
def EnsureNotNull(value, null=r'\N'):
474
    return FunctionCall(InternalFunction('coalesce'), as_Col(value), null)
475

    
476
##### Table exprs
477

    
478
class Values(Code):
479
    def __init__(self, values):
480
        '''
481
        @param values [...]|[[...], ...] Can be one or multiple rows.
482
        '''
483
        rows = values
484
        if len(values) >= 1 and not lists.is_seq(values[0]): # only one row
485
            rows = [values]
486
        for i, row in enumerate(rows):
487
            rows[i] = map(remove_col_rename, map(as_Value, row))
488
        
489
        self.rows = rows
490
    
491
    def to_str(self, db):
492
        def row_str(row):
493
            return '('+(', '.join((v.to_str(db) for v in row)))+')'
494
        return 'VALUES '+(', '.join(map(row_str, self.rows)))
495

    
496
def NamedValues(name, cols, values):
497
    '''
498
    @post `cols` will be changed to Col objects with the table set to `name`.
499
    '''
500
    set_cols_table(name, cols)
501
    return NamedTable(name, Values(values), cols)
502

    
503
##### Database structure
504

    
505
class TypedCol(Col):
506
    def __init__(self, name, type_):
507
        Col.__init__(self, name)
508
        
509
        self.type = type_
510
    
511
    def to_str(self, db): return Col.to_str(self, db)+' '+self.type
512
    
513
    def to_Col(self): return Col(self.name)
(25-25/36)