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
##### 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
class Code(BasicObject):
54
    def to_str(self, db): raise NotImplemented()
55
    
56
    def __repr__(self): return self.to_str(mockDb)
57

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

    
63
class Expr(Code):
64
    def __init__(self, expr): self.expr = expr
65
    
66
    def to_str(self, db): return '('+self.expr.to_str(db)+')'
67

    
68
##### Literal values
69

    
70
class Literal(Code):
71
    def __init__(self, value): self.value = value
72
    
73
    def to_str(self, db): return db.esc_value(self.value)
74

    
75
def as_Value(value):
76
    if isinstance(value, Code): return value
77
    else: return Literal(value)
78

    
79
def is_null(value): return isinstance(value, Literal) and value.value == None
80

    
81
##### Tables
82

    
83
class Table(Code):
84
    def __init__(self, name, schema=None):
85
        '''
86
        @param schema str|None (for no schema)
87
        '''
88
        self.name = name
89
        self.schema = schema
90
    
91
    def to_str(self, db):
92
        str_ = ''
93
        if self.schema != None: str_ += db.esc_name(self.schema)+'.'
94
        str_ += db.esc_name(self.name)
95
        return str_
96
    
97
    def to_Table(self): return self
98

    
99
def as_Table(table):
100
    if table == None or isinstance(table, Code): return table
101
    else: return Table(table)
102

    
103
class NamedTable(Table):
104
    def __init__(self, name, code, cols=None):
105
        Table.__init__(self, name)
106
        
107
        if not isinstance(code, Code): code = Table(code)
108
        
109
        self.code = code
110
        self.cols = cols
111
    
112
    def to_str(self, db):
113
        str_ = self.code.to_str(db)+'\nAS '+Table.to_str(self, db)
114
        if self.cols != None: str_ += ' ('+(', '.join(self.cols))+')'
115
        return str_
116
    
117
    def to_Table(self): return Table(self.name)
118

    
119
##### Columns
120

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

    
140
def is_table_col(col): return col.table != None
141

    
142
def as_Col(col, table=None, name=None):
143
    '''
144
    @param name If not None, any non-Col input will be renamed using NamedCol.
145
    '''
146
    if name != None:
147
        col = as_Value(col)
148
        if not isinstance(col, Col): col = NamedCol(name, col)
149
    
150
    if isinstance(col, Code): return col
151
    else: return Col(col, table)
152

    
153
def to_name_only_col(col, check_table=None):
154
    col = as_Col(col)
155
    if not isinstance(col, Col): return col
156
    
157
    if check_table != None:
158
        table = col.table
159
        assert table == None or table == check_table
160
    return Col(col.name)
161

    
162
class NamedCol(Col):
163
    def __init__(self, name, code):
164
        Col.__init__(self, name)
165
        
166
        if not isinstance(code, Code): code = Literal(code)
167
        
168
        self.code = code
169
    
170
    def to_str(self, db):
171
        return self.code.to_str(db)+' AS '+Col.to_str(self, db)
172
    
173
    def to_Col(self): return Col(self.name)
174

    
175
def remove_col_rename(col):
176
    if isinstance(col, NamedCol): col = col.code
177
    return col
178

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

    
203
##### Functions
204

    
205
class Function(Table): pass
206

    
207
class FunctionCall(Code):
208
    def __init__(self, function, *args):
209
        '''
210
        @param args [Code...] The function's arguments
211
        '''
212
        if not isinstance(function, Code): function = Function(function)
213
        args = map(remove_col_rename, args)
214
        
215
        self.function = function
216
        self.args = args
217
    
218
    def to_str(self, db):
219
        args_str = ', '.join((v.to_str(db) for v in self.args))
220
        return self.function.to_str(db)+'('+args_str+')'
221

    
222
def wrap_in_func(function, value):
223
    '''Wraps a value inside a function call.
224
    Propagates any column renaming to the returned value.
225
    '''
226
    name = None
227
    if isinstance(value, NamedCol): name = value.name
228
    value = FunctionCall(function, value)
229
    if name != None: value = NamedCol(name, value)
230
    return value
231

    
232
def unwrap_func_call(func_call, check_name=None):
233
    '''Unwraps any function call to its first argument.
234
    Also removes any column renaming.
235
    '''
236
    func_call = remove_col_rename(func_call)
237
    if not isinstance(func_call, FunctionCall): return func_call
238
    
239
    if check_name != None:
240
        name = func_call.function.name
241
        assert name == None or name == check_name
242
    return func_call.args[0]
243

    
244
##### Conditions
245

    
246
class ColValueCond(Code):
247
    def __init__(self, col, value):
248
        value = as_ValueCond(value)
249
        
250
        self.col = col
251
        self.value = value
252
    
253
    def to_str(self, db): return self.value.to_str(db, self.col)
254

    
255
def combine_conds(conds, keyword=None):
256
    '''
257
    @param keyword The keyword to add before the conditions, if any
258
    '''
259
    str_ = ''
260
    if keyword != None:
261
        if conds == []: whitespace = ''
262
        elif len(conds) == 1: whitespace = ' '
263
        else: whitespace = '\n'
264
        str_ += keyword+whitespace
265
    
266
    str_ += '\nAND '.join(conds)
267
    return str_
268

    
269
##### Condition column comparisons
270

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

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

    
319
# Tells as_ValueCond() to assume a non-ValueCond is a literal value
320
assume_literal = object()
321

    
322
def as_ValueCond(value, default_table=assume_literal):
323
    if not isinstance(value, ValueCond):
324
        if default_table is not assume_literal:
325
            value = as_Col(value, default_table)
326
        return CompareCond(value)
327
    else: return value
328

    
329
##### Joins
330

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

    
333
# Tells Join the left and right columns have the same name and are never NULL
334
join_same_not_null = object()
335

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

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

    
401
##### Value exprs
402

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