Project

General

Profile

1
# SQL code generation
2

    
3
import copy
4
import operator
5
import re
6
import UserDict
7

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

    
15
##### Names
16

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

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

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

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

    
44
##### General SQL code objects
45

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

    
52
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
##### Unparameterized code objects
58

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

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

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

    
73
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
##### Literal values
79

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

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

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

    
91
##### 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
        '''An element which was derived from some other element(s).
98
        @param srcs See self.set_srcs()
99
        '''
100
        self.set_srcs(srcs)
101
    
102
    def set_srcs(self, srcs, overwrite=True):
103
        '''
104
        @param srcs (self_type...)|src_self The element(s) this is derived from
105
        '''
106
        if not overwrite and self.srcs != (): return # already set
107
        
108
        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
##### Tables
120

    
121
class Table(Derived):
122
    def __init__(self, name, schema=None, srcs=()):
123
        '''
124
        @param schema str|None (for no schema)
125
        @param srcs (Table...)|src_self See Derived.set_srcs()
126
        '''
127
        Derived.__init__(self, srcs)
128
        
129
        self.name = name
130
        self.schema = schema
131
    
132
    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
    
138
    def to_Table(self): return self
139

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

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

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

    
165
##### Columns
166

    
167
class Col(Derived):
168
    def __init__(self, name, table=None, srcs=()):
169
        '''
170
        @param table Table|None (for no table)
171
        @param srcs (Col...)|src_self See Derived.set_srcs()
172
        '''
173
        Derived.__init__(self, srcs)
174
        
175
        if util.is_str(table): table = Table(table)
176
        assert table == None or isinstance(table, Table)
177
        if table != None: table = table.to_Table()
178
        
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
        str_ += db.esc_name(self.name)
186
        return str_
187
    
188
    def to_Col(self): return self
189

    
190
def is_table_col(col): return col.table != None
191

    
192
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
    
200
    if isinstance(col, Code): return col
201
    else: return Col(col, table)
202

    
203
def with_default_table(col, table, overwrite=False):
204
    col = as_Col(col)
205
    if not isinstance(col, NamedCol) and (overwrite or col.table == None):
206
        col = copy.copy(col) # don't modify input!
207
        col.table = table
208
    return col
209

    
210
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
def to_name_only_col(col, check_table=None):
218
    col = as_Col(col)
219
    if not isinstance(col, Col): return col
220
    
221
    if check_table != None:
222
        table = col.table
223
        assert table == None or table == check_table
224
    return Col(col.name)
225

    
226
class NamedCol(Col):
227
    def __init__(self, name, code):
228
        Col.__init__(self, name)
229
        
230
        if not isinstance(code, Code): code = Literal(code)
231
        
232
        self.code = code
233
    
234
    def to_str(self, db):
235
        return self.code.to_str(db)+' AS '+Col.to_str(self, db)
236
    
237
    def to_Col(self): return Col(self.name)
238

    
239
def remove_col_rename(col):
240
    if isinstance(col, NamedCol): col = col.code
241
    return col
242

    
243
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
class ColDict(dicts.DictProxy):
250
    '''A dict that automatically makes inserted entries Col objects'''
251
    
252
    def __init__(self, db, keys_table, dict_={}):
253
        dicts.DictProxy.__init__(self, {})
254
        
255
        keys_table = as_Table(keys_table)
256
        
257
        self.db = db
258
        self.table = keys_table
259
        self.update(dict_) # after setting vars because __setitem__() needs them
260
    
261
    def copy(self): return ColDict(self.db, self.table, self.inner.copy())
262
    
263
    def __getitem__(self, key):
264
        return dicts.DictProxy.__getitem__(self, self._key(key))
265
    
266
    def __setitem__(self, key, value):
267
        key = self._key(key)
268
        if value == None: value = self.db.col_default(key)
269
        dicts.DictProxy.__setitem__(self, key, as_Col(value, name=key.name))
270
    
271
    def _key(self, key): return as_Col(key, self.table)
272

    
273
##### Functions
274

    
275
class Function(Table): pass
276

    
277
def TempFunction(name, autocommit):
278
    schema = None
279
    if not autocommit: schema = 'pg_temp'
280
    return Function(name, schema)
281

    
282
class InternalFunction(CustomCode): pass
283

    
284
class FunctionCall(Code):
285
    def __init__(self, function, *args):
286
        '''
287
        @param args [Code|literal-value...] The function's arguments
288
        '''
289
        if not isinstance(function, Code): function = Function(function)
290
        args = map(remove_col_rename, map(as_Value, args))
291
        
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
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
    return wrap(lambda v: FunctionCall(function, v), value)
304

    
305
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
##### Conditions
318

    
319
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
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
##### Condition column comparisons
343

    
344
class ValueCond(BasicObject):
345
    def __init__(self, value):
346
        if not isinstance(value, Code): value = Literal(value)
347
        value = remove_col_rename(value)
348
        
349
        self.value = value
350
    
351
    def to_str(self, db, left_value):
352
        '''
353
        @param left_value The Code object that the condition is being applied on
354
        '''
355
        raise NotImplemented()
356
    
357
    def __repr__(self): return self.to_str(mockDb, '<left_value>')
358

    
359
class CompareCond(ValueCond):
360
    def __init__(self, value, operator='='):
361
        '''
362
        @param operator By default, compares NULL values literally. Use '~=' or
363
            '~!=' to pass NULLs through.
364
        '''
365
        ValueCond.__init__(self, value)
366
        self.operator = operator
367
    
368
    def to_str(self, db, left_value):
369
        if not isinstance(left_value, Code): left_value = Col(left_value)
370
        left_value = remove_col_rename(left_value)
371
        
372
        right_value = self.value
373
        left = left_value.to_str(db)
374
        right = right_value.to_str(db)
375
        
376
        # Parse operator
377
        operator = self.operator
378
        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
            str_ = '('+str_+' OR ('+left+' IS NULL AND '+right+' IS NULL))'
389
        if neg_ref[0]: str_ = 'NOT '+str_
390
        return str_
391

    
392
# 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
            value = with_default_table(value, default_table)
399
        return CompareCond(value)
400
    else: return value
401

    
402
##### Joins
403

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

    
406
# Tells Join the left and right columns have the same name and are never NULL
407
join_same_not_null = object()
408

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

    
411
class Join(BasicObject):
412
    def __init__(self, table, mapping={}, type_=None):
413
        '''
414
        @param mapping dict(right_table_col=left_table_col, ...)
415
            * if left_table_col is join_same: left_table_col = right_table_col
416
              * 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
        @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
    def to_str(self, db, left_table_):
432
        def join(entry):
433
            '''Parses non-USING joins'''
434
            right_table_col, left_table_col = entry
435
            
436
            # Switch order (right_table_col is on the left in the comparison)
437
            left = right_table_col
438
            right = left_table_col
439
            left_table = self.table
440
            right_table = left_table_
441
            
442
            left_table = left_table.to_Table()
443
            right_table = right_table.to_Table()
444
            
445
            # Parse left side
446
            left = with_default_table(left, left_table)
447
            
448
            # Parse special values
449
            left_on_right = Col(left.name, right_table)
450
            if right is join_same: right = left_on_right
451
            elif right is join_same_not_null:
452
                right = CompareCond(left_on_right, '~=')
453
            
454
            # Parse right side
455
            right = as_ValueCond(right, right_table)
456
            
457
            return right.to_str(db, left)
458
        
459
        # Create join condition
460
        type_ = self.type_
461
        joins = self.mapping
462
        if joins == {}: join_cond = None
463
        elif type_ is not filter_out and reduce(operator.and_,
464
            (v is join_same_not_null for v in joins.itervalues())):
465
            # all cols w/ USING, so can use simpler USING syntax
466
            cols = map(to_name_only_col, joins.iterkeys())
467
            join_cond = 'USING ('+(', '.join((c.to_str(db) for c in cols)))+')'
468
        else:
469
            if len(joins) == 1: whitespace = ' '
470
            else: whitespace = '\n'
471
            join_cond = combine_conds(map(join, joins.iteritems()), 'ON')
472
        
473
        # Create join
474
        if type_ is filter_out: type_ = 'LEFT'
475
        str_ = ''
476
        if type_ != None: str_ += type_+' '
477
        str_ += 'JOIN '+self.table.to_str(db)
478
        if join_cond != None: str_ += ' '+join_cond
479
        return str_
480
    
481
    def __repr__(self): return self.to_str(mockDb, '<left_table>')
482

    
483
##### Value exprs
484

    
485
default = CustomCode('DEFAULT')
486

    
487
row_count = CustomCode('count(*)')
488

    
489
def EnsureNotNull(value, null=r'\N'):
490
    return FunctionCall(InternalFunction('coalesce'), as_Col(value), null)
491

    
492
##### Table exprs
493

    
494
class Values(Code):
495
    def __init__(self, values):
496
        '''
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
        
505
        self.rows = rows
506
    
507
    def to_str(self, db):
508
        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

    
512
def NamedValues(name, cols, values):
513
    '''
514
    @post `cols` will be changed to Col objects with the table set to `name`.
515
    '''
516
    set_cols_table(name, cols)
517
    return NamedTable(name, Values(values), cols)
518

    
519
##### 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)
(25-25/36)