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
##### Tables
91

    
92
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
    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
    
106
    def to_Table(self): return self
107

    
108
def as_Table(table):
109
    if table == None or isinstance(table, Code): return table
110
    else: return Table(table)
111

    
112
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
        str_ = self.code.to_str(db)+'\nAS '+Table.to_str(self, db)
123
        if self.cols != None: str_ += ' ('+(', '.join(self.cols))+')'
124
        return str_
125
    
126
    def to_Table(self): return Table(self.name)
127

    
128
##### Columns
129

    
130
src_self = object() # tells Col that it is its own source column
131

    
132
class Col(Code):
133
    def __init__(self, name, table=None, srcs=()):
134
        '''
135
        @param table Table|None (for no table)
136
        @param srcs See self.set_srcs()
137
        '''
138
        if util.is_str(table): table = Table(table)
139
        assert table == None or isinstance(table, Table)
140
        
141
        self.name = name
142
        self.table = table
143
        self.set_srcs(srcs)
144
    
145
    def to_str(self, db):
146
        str_ = ''
147
        if self.table != None: str_ += self.table.to_str(db)+'.'
148
        str_ += db.esc_name(self.name)
149
        return str_
150
    
151
    def to_Col(self): return self
152
    
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

    
166
def is_table_col(col): return col.table != None
167

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

    
170
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
    
178
    if isinstance(col, Code): return col
179
    else: return Col(col, table)
180

    
181
def to_name_only_col(col, check_table=None):
182
    col = as_Col(col)
183
    if not isinstance(col, Col): return col
184
    
185
    if check_table != None:
186
        table = col.table
187
        assert table == None or table == check_table
188
    return Col(col.name)
189

    
190
class NamedCol(Col):
191
    def __init__(self, name, code):
192
        Col.__init__(self, name)
193
        
194
        if not isinstance(code, Code): code = Literal(code)
195
        
196
        self.code = code
197
    
198
    def to_str(self, db):
199
        return self.code.to_str(db)+' AS '+Col.to_str(self, db)
200
    
201
    def to_Col(self): return Col(self.name)
202

    
203
def remove_col_rename(col):
204
    if isinstance(col, NamedCol): col = col.code
205
    return col
206

    
207
def wrap(wrap_func, value):
208
    '''Wraps a value, propagating any column renaming to the returned value.'''
209
    if isinstance(value, NamedCol):
210
        return NamedCol(value.name, wrap_func(value.code))
211
    else: return wrap_func(value)
212

    
213
class ColDict(dicts.DictProxy):
214
    '''A dict that automatically makes inserted entries Col objects'''
215
    
216
    def __init__(self, db, keys_table, dict_={}):
217
        dicts.DictProxy.__init__(self, {})
218
        
219
        keys_table = as_Table(keys_table)
220
        
221
        self.db = db
222
        self.table = keys_table
223
        self.update(dict_) # after setting vars because __setitem__() needs them
224
    
225
    def copy(self): return ColDict(self.db, self.table, self.inner.copy())
226
    
227
    def __getitem__(self, key):
228
        return dicts.DictProxy.__getitem__(self, self._key(key))
229
    
230
    def __setitem__(self, key, value):
231
        key = self._key(key)
232
        if value == None: value = self.db.col_default(key)
233
        dicts.DictProxy.__setitem__(self, key, as_Col(value, name=key.name))
234
    
235
    def _key(self, key): return as_Col(key, self.table)
236

    
237
##### Functions
238

    
239
class Function(Table): pass
240

    
241
def TempFunction(name, autocommit):
242
    schema = None
243
    if not autocommit: schema = 'pg_temp'
244
    return Function(name, schema)
245

    
246
class InternalFunction(CustomCode): pass
247

    
248
class FunctionCall(Code):
249
    def __init__(self, function, *args):
250
        '''
251
        @param args [Code|literal-value...] The function's arguments
252
        '''
253
        if not isinstance(function, Code): function = Function(function)
254
        args = map(remove_col_rename, map(as_Value, args))
255
        
256
        self.function = function
257
        self.args = args
258
    
259
    def to_str(self, db):
260
        args_str = ', '.join((v.to_str(db) for v in self.args))
261
        return self.function.to_str(db)+'('+args_str+')'
262

    
263
def wrap_in_func(function, value):
264
    '''Wraps a value inside a function call.
265
    Propagates any column renaming to the returned value.
266
    '''
267
    return wrap(lambda v: FunctionCall(function, v), value)
268

    
269
def unwrap_func_call(func_call, check_name=None):
270
    '''Unwraps any function call to its first argument.
271
    Also removes any column renaming.
272
    '''
273
    func_call = remove_col_rename(func_call)
274
    if not isinstance(func_call, FunctionCall): return func_call
275
    
276
    if check_name != None:
277
        name = func_call.function.name
278
        assert name == None or name == check_name
279
    return func_call.args[0]
280

    
281
##### Conditions
282

    
283
class ColValueCond(Code):
284
    def __init__(self, col, value):
285
        value = as_ValueCond(value)
286
        
287
        self.col = col
288
        self.value = value
289
    
290
    def to_str(self, db): return self.value.to_str(db, self.col)
291

    
292
def combine_conds(conds, keyword=None):
293
    '''
294
    @param keyword The keyword to add before the conditions, if any
295
    '''
296
    str_ = ''
297
    if keyword != None:
298
        if conds == []: whitespace = ''
299
        elif len(conds) == 1: whitespace = ' '
300
        else: whitespace = '\n'
301
        str_ += keyword+whitespace
302
    
303
    str_ += '\nAND '.join(conds)
304
    return str_
305

    
306
##### Condition column comparisons
307

    
308
class ValueCond(BasicObject):
309
    def __init__(self, value):
310
        if not isinstance(value, Code): value = Literal(value)
311
        value = remove_col_rename(value)
312
        
313
        self.value = value
314
    
315
    def to_str(self, db, left_value):
316
        '''
317
        @param left_value The Code object that the condition is being applied on
318
        '''
319
        raise NotImplemented()
320
    
321
    def __repr__(self): return self.to_str(mockDb, '<left_value>')
322

    
323
class CompareCond(ValueCond):
324
    def __init__(self, value, operator='='):
325
        '''
326
        @param operator By default, compares NULL values literally. Use '~=' or
327
            '~!=' to pass NULLs through.
328
        '''
329
        ValueCond.__init__(self, value)
330
        self.operator = operator
331
    
332
    def to_str(self, db, left_value):
333
        if not isinstance(left_value, Code): left_value = Col(left_value)
334
        left_value = remove_col_rename(left_value)
335
        
336
        right_value = self.value
337
        left = left_value.to_str(db)
338
        right = right_value.to_str(db)
339
        
340
        # Parse operator
341
        operator = self.operator
342
        passthru_null_ref = [False]
343
        operator = strings.remove_prefix('~', operator, passthru_null_ref)
344
        neg_ref = [False]
345
        operator = strings.remove_prefix('!', operator, neg_ref)
346
        equals = operator.endswith('=')
347
        if equals and is_null(self.value): operator = 'IS'
348
        
349
        # Create str
350
        str_ = left+' '+operator+' '+right
351
        if equals and not passthru_null_ref[0] and isinstance(right_value, Col):
352
            str_ = '('+str_+' OR ('+left+' IS NULL AND '+right+' IS NULL))'
353
        if neg_ref[0]: str_ = 'NOT '+str_
354
        return str_
355

    
356
# Tells as_ValueCond() to assume a non-ValueCond is a literal value
357
assume_literal = object()
358

    
359
def as_ValueCond(value, default_table=assume_literal):
360
    if not isinstance(value, ValueCond):
361
        if default_table is not assume_literal:
362
            value = as_Col(value, default_table)
363
        return CompareCond(value)
364
    else: return value
365

    
366
##### Joins
367

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

    
370
# Tells Join the left and right columns have the same name and are never NULL
371
join_same_not_null = object()
372

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

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

    
438
##### Value exprs
439

    
440
row_count = CustomCode('count(*)')
441

    
442
def EnsureNotNull(value, null=r'\N'):
443
    return FunctionCall(InternalFunction('coalesce'), as_Col(value), null)
444

    
445
##### Database structure
446

    
447
class TypedCol(Col):
448
    def __init__(self, name, type_):
449
        Col.__init__(self, name)
450
        
451
        self.type = type_
452
    
453
    def to_str(self, db): return Col.to_str(self, db)+' '+self.type
454
    
455
    def to_Col(self): return Col(self.name)
(25-25/36)