Project

General

Profile

1
# SQL code generation
2

    
3
import operator
4
import re
5
import UserDict
6

    
7
import objects
8
import strings
9
import util
10

    
11
##### Names
12

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

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

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

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

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

    
40
##### General SQL code objects
41

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

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

    
53
##### Unparameterized code objects
54

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

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

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

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

    
74
##### Literal values
75

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

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

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

    
87
##### Tables
88

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

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

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

    
125
##### Columns
126

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

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

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

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

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

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

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

    
209
##### Functions
210

    
211
class Function(Table): pass
212

    
213
class FunctionCall(Code):
214
    def __init__(self, function, *args):
215
        '''
216
        @param args [Code...] The function's arguments
217
        '''
218
        if not isinstance(function, Code): function = Function(function)
219
        args = map(remove_col_rename, args)
220
        
221
        self.function = function
222
        self.args = args
223
    
224
    def to_str(self, db):
225
        args_str = ', '.join((v.to_str(db) for v in self.args))
226
        return self.function.to_str(db)+'('+args_str+')'
227

    
228
def wrap_in_func(function, value):
229
    '''Wraps a value inside a function call.
230
    Propagates any column renaming to the returned value.
231
    '''
232
    name = None
233
    if isinstance(value, NamedCol): name = value.name
234
    value = FunctionCall(function, value)
235
    if name != None: value = NamedCol(name, value)
236
    return value
237

    
238
def unwrap_func_call(func_call, check_name=None):
239
    '''Unwraps any function call to its first argument.
240
    Also removes any column renaming.
241
    '''
242
    func_call = remove_col_rename(func_call)
243
    if not isinstance(func_call, FunctionCall): return func_call
244
    
245
    if check_name != None:
246
        name = func_call.function.name
247
        assert name == None or name == check_name
248
    return func_call.args[0]
249

    
250
##### Conditions
251

    
252
class ColValueCond(Code):
253
    def __init__(self, col, value):
254
        value = as_ValueCond(value)
255
        
256
        self.col = col
257
        self.value = value
258
    
259
    def to_str(self, db): return self.value.to_str(db, self.col)
260

    
261
def combine_conds(conds, keyword=None):
262
    '''
263
    @param keyword The keyword to add before the conditions, if any
264
    '''
265
    str_ = ''
266
    if keyword != None:
267
        if conds == []: whitespace = ''
268
        elif len(conds) == 1: whitespace = ' '
269
        else: whitespace = '\n'
270
        str_ += keyword+whitespace
271
    
272
    str_ += '\nAND '.join(conds)
273
    return str_
274

    
275
##### Condition column comparisons
276

    
277
class ValueCond(BasicObject):
278
    def __init__(self, value):
279
        if not isinstance(value, Code): value = Literal(value)
280
        value = remove_col_rename(value)
281
        
282
        self.value = value
283
    
284
    def to_str(self, db, left_value):
285
        '''
286
        @param left_value The Code object that the condition is being applied on
287
        '''
288
        raise NotImplemented()
289
    
290
    def __repr__(self): return self.to_str(mockDb, '<left_value>')
291

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

    
325
# Tells as_ValueCond() to assume a non-ValueCond is a literal value
326
assume_literal = object()
327

    
328
def as_ValueCond(value, default_table=assume_literal):
329
    if not isinstance(value, ValueCond):
330
        if default_table is not assume_literal:
331
            value = as_Col(value, default_table)
332
        return CompareCond(value)
333
    else: return value
334

    
335
##### Joins
336

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

    
339
# Tells Join the left and right columns have the same name and are never NULL
340
join_same_not_null = object()
341

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

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

    
407
##### Value exprs
408

    
409
row_count = CustomCode('count(*)')
(25-25/36)