Project

General

Profile

1
# SQL code generation
2

    
3
import operator
4
import re
5
import UserDict
6

    
7
import dicts
8
import objects
9
import strings
10
import util
11

    
12
##### Names
13

    
14
identifier_max_len = 63 # works for both PostgreSQL and MySQL
15

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

    
27
def is_safe_name(name):
28
    '''A name is safe *and unambiguous* if it:
29
    * contains only *lowercase* word (\w) characters
30
    * doesn't start with a digit
31
    * contains "_", so that it's not a keyword
32
    ''' 
33
    return re.match(r'^(?=.*_)(?!\d)[^\WA-Z]+$', name) 
34

    
35
def esc_name(name, quote='"'):
36
    return quote + name.replace(quote, quote+quote) + quote
37
        # doubling an embedded quote escapes it in both PostgreSQL and MySQL
38

    
39
def clean_name(name): return name.replace('"', '').replace('`', '')
40

    
41
##### General SQL code objects
42

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

    
49
class BasicObject(objects.BasicObject):
50
    def __init__(self, value): self.value = value
51
    
52
    def __str__(self): return clean_name(strings.repr_no_u(self))
53

    
54
##### Unparameterized code objects
55

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

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

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

    
70
class Expr(Code):
71
    def __init__(self, expr): self.expr = expr
72
    
73
    def to_str(self, db): return '('+self.expr.to_str(db)+')'
74

    
75
##### Literal values
76

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

    
82
def as_Value(value):
83
    if isinstance(value, Code): return value
84
    else: return Literal(value)
85

    
86
def is_null(value): return isinstance(value, Literal) and value.value == None
87

    
88
##### Tables
89

    
90
class Table(Code):
91
    def __init__(self, name, schema=None):
92
        '''
93
        @param schema str|None (for no schema)
94
        '''
95
        self.name = name
96
        self.schema = schema
97
    
98
    def to_str(self, db):
99
        str_ = ''
100
        if self.schema != None: str_ += db.esc_name(self.schema)+'.'
101
        str_ += db.esc_name(self.name)
102
        return str_
103
    
104
    def to_Table(self): return self
105

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

    
110
class NamedTable(Table):
111
    def __init__(self, name, code, cols=None):
112
        Table.__init__(self, name)
113
        
114
        if not isinstance(code, Code): code = Table(code)
115
        
116
        self.code = code
117
        self.cols = cols
118
    
119
    def to_str(self, db):
120
        str_ = self.code.to_str(db)+'\nAS '+Table.to_str(self, db)
121
        if self.cols != None: str_ += ' ('+(', '.join(self.cols))+')'
122
        return str_
123
    
124
    def to_Table(self): return Table(self.name)
125

    
126
##### Columns
127

    
128
class Col(Code):
129
    def __init__(self, name, table=None):
130
        '''
131
        @param table Table|None (for no table)
132
        '''
133
        if util.is_str(table): table = Table(table)
134
        assert table == None or isinstance(table, Table)
135
        
136
        self.name = name
137
        self.table = table
138
    
139
    def to_str(self, db):
140
        str_ = ''
141
        if self.table != None: str_ += self.table.to_str(db)+'.'
142
        str_ += db.esc_name(self.name)
143
        return str_
144
    
145
    def to_Col(self): return self
146

    
147
def is_table_col(col): return col.table != None
148

    
149
def as_Col(col, table=None, name=None):
150
    '''
151
    @param name If not None, any non-Col input will be renamed using NamedCol.
152
    '''
153
    if name != None:
154
        col = as_Value(col)
155
        if not isinstance(col, Col): col = NamedCol(name, col)
156
    
157
    if isinstance(col, Code): return col
158
    else: return Col(col, table)
159

    
160
def to_name_only_col(col, check_table=None):
161
    col = as_Col(col)
162
    if not isinstance(col, Col): return col
163
    
164
    if check_table != None:
165
        table = col.table
166
        assert table == None or table == check_table
167
    return Col(col.name)
168

    
169
class NamedCol(Col):
170
    def __init__(self, name, code):
171
        Col.__init__(self, name)
172
        
173
        if not isinstance(code, Code): code = Literal(code)
174
        
175
        self.code = code
176
    
177
    def to_str(self, db):
178
        return self.code.to_str(db)+' AS '+Col.to_str(self, db)
179
    
180
    def to_Col(self): return Col(self.name)
181

    
182
def remove_col_rename(col):
183
    if isinstance(col, NamedCol): col = col.code
184
    return col
185

    
186
class ColDict(dicts.DictProxy):
187
    '''A dict that automatically makes inserted entries Col objects'''
188
    
189
    def __init__(self, db, keys_table, dict_={}):
190
        dicts.DictProxy.__init__(self, {})
191
        
192
        keys_table = as_Table(keys_table)
193
        
194
        self.db = db
195
        self.table = keys_table
196
        self.update(dict_) # after setting vars because __setitem__() needs them
197
    
198
    def copy(self): return ColDict(self.db, self.table, self.inner.copy())
199
    
200
    def __getitem__(self, key):
201
        return dicts.DictProxy.__getitem__(self, self._key(key))
202
    
203
    def __setitem__(self, key, value):
204
        key = self._key(key)
205
        if value == None: value = self.db.col_default(key)
206
        dicts.DictProxy.__setitem__(self, key, as_Col(value, name=key.name))
207
    
208
    def _key(self, key): return as_Col(key, self.table)
209

    
210
##### Functions
211

    
212
class Function(Table): pass
213

    
214
def TempFunction(name, autocommit):
215
    schema = None
216
    if not autocommit: schema = 'pg_temp'
217
    return Function(name, schema)
218

    
219
class InternalFunction(CustomCode): pass
220

    
221
class FunctionCall(Code):
222
    def __init__(self, function, *args):
223
        '''
224
        @param args [Code|literal-value...] The function's arguments
225
        '''
226
        if not isinstance(function, Code): function = Function(function)
227
        args = map(remove_col_rename, map(as_Value, args))
228
        
229
        self.function = function
230
        self.args = args
231
    
232
    def to_str(self, db):
233
        args_str = ', '.join((v.to_str(db) for v in self.args))
234
        return self.function.to_str(db)+'('+args_str+')'
235

    
236
def wrap_in_func(function, value):
237
    '''Wraps a value inside a function call.
238
    Propagates any column renaming to the returned value.
239
    '''
240
    name = None
241
    if isinstance(value, NamedCol): name = value.name
242
    value = FunctionCall(function, value)
243
    if name != None: value = NamedCol(name, value)
244
    return value
245

    
246
def unwrap_func_call(func_call, check_name=None):
247
    '''Unwraps any function call to its first argument.
248
    Also removes any column renaming.
249
    '''
250
    func_call = remove_col_rename(func_call)
251
    if not isinstance(func_call, FunctionCall): return func_call
252
    
253
    if check_name != None:
254
        name = func_call.function.name
255
        assert name == None or name == check_name
256
    return func_call.args[0]
257

    
258
##### Conditions
259

    
260
class ColValueCond(Code):
261
    def __init__(self, col, value):
262
        value = as_ValueCond(value)
263
        
264
        self.col = col
265
        self.value = value
266
    
267
    def to_str(self, db): return self.value.to_str(db, self.col)
268

    
269
def combine_conds(conds, keyword=None):
270
    '''
271
    @param keyword The keyword to add before the conditions, if any
272
    '''
273
    str_ = ''
274
    if keyword != None:
275
        if conds == []: whitespace = ''
276
        elif len(conds) == 1: whitespace = ' '
277
        else: whitespace = '\n'
278
        str_ += keyword+whitespace
279
    
280
    str_ += '\nAND '.join(conds)
281
    return str_
282

    
283
##### Condition column comparisons
284

    
285
class ValueCond(BasicObject):
286
    def __init__(self, value):
287
        if not isinstance(value, Code): value = Literal(value)
288
        value = remove_col_rename(value)
289
        
290
        self.value = value
291
    
292
    def to_str(self, db, left_value):
293
        '''
294
        @param left_value The Code object that the condition is being applied on
295
        '''
296
        raise NotImplemented()
297
    
298
    def __repr__(self): return self.to_str(mockDb, '<left_value>')
299

    
300
class CompareCond(ValueCond):
301
    def __init__(self, value, operator='='):
302
        '''
303
        @param operator By default, compares NULL values literally. Use '~=' or
304
            '~!=' to pass NULLs through.
305
        '''
306
        ValueCond.__init__(self, value)
307
        self.operator = operator
308
    
309
    def to_str(self, db, left_value):
310
        if not isinstance(left_value, Code): left_value = Col(left_value)
311
        left_value = remove_col_rename(left_value)
312
        
313
        right_value = self.value
314
        left = left_value.to_str(db)
315
        right = right_value.to_str(db)
316
        
317
        # Parse operator
318
        operator = self.operator
319
        passthru_null_ref = [False]
320
        operator = strings.remove_prefix('~', operator, passthru_null_ref)
321
        neg_ref = [False]
322
        operator = strings.remove_prefix('!', operator, neg_ref)
323
        equals = operator.endswith('=')
324
        if equals and is_null(self.value): operator = 'IS'
325
        
326
        # Create str
327
        str_ = left+' '+operator+' '+right
328
        if equals and not passthru_null_ref[0] and isinstance(right_value, Col):
329
            str_ = '('+str_+' OR ('+left+' IS NULL AND '+right+' IS NULL))'
330
        if neg_ref[0]: str_ = 'NOT '+str_
331
        return str_
332

    
333
# Tells as_ValueCond() to assume a non-ValueCond is a literal value
334
assume_literal = object()
335

    
336
def as_ValueCond(value, default_table=assume_literal):
337
    if not isinstance(value, ValueCond):
338
        if default_table is not assume_literal:
339
            value = as_Col(value, default_table)
340
        return CompareCond(value)
341
    else: return value
342

    
343
##### Joins
344

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

    
347
# Tells Join the left and right columns have the same name and are never NULL
348
join_same_not_null = object()
349

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

    
352
class Join(BasicObject):
353
    def __init__(self, table, mapping, type_=None):
354
        '''
355
        @param mapping dict(right_table_col=left_table_col, ...)
356
            * if left_table_col is join_same: left_table_col = right_table_col
357
              * Note that right_table_col must be a string
358
            * if left_table_col is join_same_not_null:
359
              left_table_col = right_table_col and both have NOT NULL constraint
360
              * Note that right_table_col must be a string
361
        @param type_ None (for plain join)|str (e.g. 'LEFT')|filter_out
362
            * filter_out: equivalent to 'LEFT' with the query filtered by
363
              `table_pkey IS NULL` (indicating no match)
364
        '''
365
        if util.is_str(table): table = Table(table)
366
        assert type_ == None or util.is_str(type_) or type_ is filter_out
367
        
368
        self.table = table
369
        self.mapping = mapping
370
        self.type_ = type_
371
    
372
    def to_str(self, db, left_table):
373
        # Switch order (left_table is on the right in the comparison)
374
        right_table = left_table
375
        left_table = self.table # note left_table is reassigned
376
        
377
        def join(entry):
378
            '''Parses non-USING joins'''
379
            right_table_col, left_table_col = entry
380
            
381
            # Switch order (right_table_col is on the left in the comparison)
382
            left = right_table_col
383
            right = left_table_col
384
            
385
            # Parse special values
386
            if right is join_same: right = left
387
            elif right is join_same_not_null:
388
                right = CompareCond(as_Col(left, right_table), '~=')
389
            
390
            right = as_ValueCond(right, right_table)
391
            return right.to_str(db, as_Col(left, left_table))
392
        
393
        # Create join condition
394
        type_ = self.type_
395
        joins = self.mapping
396
        if type_ is not filter_out and reduce(operator.and_,
397
            (v is join_same_not_null for v in joins.itervalues())):
398
            # all cols w/ USING, so can use simpler USING syntax
399
            cols = (as_Col(v).to_str(db) for v in joins.iterkeys())
400
            join_cond = 'USING ('+(', '.join(cols))+')'
401
        else:
402
            if len(joins) == 1: whitespace = ' '
403
            else: whitespace = '\n'
404
            join_cond = combine_conds(map(join, joins.iteritems()), 'ON')
405
        
406
        # Create join
407
        if type_ is filter_out: type_ = 'LEFT'
408
        str_ = ''
409
        if type_ != None: str_ += type_+' '
410
        str_ += 'JOIN '+left_table.to_str(db)+' '+join_cond
411
        return str_
412
    
413
    def __repr__(self): return self.to_str(mockDb, '<left_table>')
414

    
415
##### Value exprs
416

    
417
row_count = CustomCode('count(*)')
418

    
419
def EnsureNotNull(value, null=r'\N'):
420
    return FunctionCall(InternalFunction('coalesce'), as_Col(value), null)
421

    
422
##### Database structure
423

    
424
class TypedCol(Col):
425
    def __init__(self, name, type_):
426
        Col.__init__(self, name)
427
        
428
        self.type = type_
429
    
430
    def to_str(self, db): return Col.to_str(self, db)+' '+self.type
431
    
432
    def to_Col(self): return Col(self.name)
(25-25/36)