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
        
152
        self.code = code
153
        self.cols = cols
154
    
155
    def to_str(self, db):
156
        str_ = self.code.to_str(db)+'\nAS '+Table.to_str(self, db)
157
        if self.cols != None: str_ += ' ('+(', '.join(self.cols))+')'
158
        return str_
159
    
160
    def to_Table(self): return Table(self.name)
161

    
162
##### Columns
163

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

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

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

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

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

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

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

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

    
255
##### Functions
256

    
257
class Function(Table): pass
258

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

    
264
class InternalFunction(CustomCode): pass
265

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

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

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

    
299
##### Conditions
300

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

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

    
324
##### Condition column comparisons
325

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

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

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

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

    
384
##### Joins
385

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

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

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

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

    
457
##### Value exprs
458

    
459
default = CustomCode('DEFAULT')
460

    
461
row_count = CustomCode('count(*)')
462

    
463
def EnsureNotNull(value, null=r'\N'):
464
    return FunctionCall(InternalFunction('coalesce'), as_Col(value), null)
465

    
466
##### Table exprs
467

    
468
class Values(Code):
469
    def __init__(self, values):
470
        '''
471
        @param values [...]|[[...], ...] Can be one or multiple rows.
472
        '''
473
        rows = values
474
        if len(values) >= 1 and not lists.is_seq(values[0]): # only one row
475
            rows = [values]
476
        for i, row in enumerate(rows):
477
            rows[i] = map(remove_col_rename, map(as_Value, row))
478
        
479
        self.rows = rows
480
    
481
    def to_str(self, db):
482
        def row_str(row):
483
            return '('+(', '.join((v.to_str(db) for v in row)))+')'
484
        return 'VALUES '+(', '.join(map(row_str, self.rows)))
485

    
486
def NamedValues(name, cols, values):
487
    return NamedTable(name, Values(values), cols)
488

    
489
##### Database structure
490

    
491
class TypedCol(Col):
492
    def __init__(self, name, type_):
493
        Col.__init__(self, name)
494
        
495
        self.type = type_
496
    
497
    def to_str(self, db): return Col.to_str(self, db)+' '+self.type
498
    
499
    def to_Col(self): return Col(self.name)
(25-25/36)