Project

General

Profile

1
# SQL code generation
2

    
3
import operator
4
import re
5

    
6
import objects
7
import strings
8
import util
9

    
10
##### Names
11

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

    
14
def add_suffix(str_, suffix):
15
    '''Preserves version so that it won't be truncated off the string, leading
16
    to collisions.'''
17
    if len(str_) == identifier_max_len: # preserve version
18
        str_, sep, version = str_.partition('#')
19
        suffix = sep+version+suffix
20
    return strings.add_suffix(str_, suffix, identifier_max_len)
21

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

    
30
def esc_name(name, quote='"'):
31
    return quote + name.replace(quote, quote+quote) + quote
32
        # doubling an embedded quote escapes it in both PostgreSQL and MySQL
33

    
34
def clean_name(name): return name.replace('"', '').replace('`', '')
35

    
36
##### SQL code objects
37

    
38
class MockDb:
39
    def esc_value(self, value): return strings.repr_no_u(value)
40
    
41
    def esc_name(self, name): return esc_name(name)
42
mockDb = MockDb()
43

    
44
class BasicObject(objects.BasicObject):
45
    def __init__(self, value): self.value = value
46
    
47
    def __str__(self): return clean_name(strings.repr_no_u(self))
48

    
49
class Code(BasicObject):
50
    def to_str(self, db): raise NotImplemented()
51
    
52
    def __repr__(self): return self.to_str(mockDb)
53

    
54
class CustomCode(Code):
55
    def __init__(self, str_): self.str_ = str_
56
    
57
    def to_str(self, db): return self.str_
58

    
59
class Expr(Code):
60
    def __init__(self, expr): self.expr = expr
61
    
62
    def to_str(self, db): return '('+self.expr.to_str(db)+')'
63

    
64
##### Literal values
65

    
66
class Literal(Code):
67
    def __init__(self, value): self.value = value
68
    
69
    def to_str(self, db): return db.esc_value(self.value)
70

    
71
def as_Value(value):
72
    if isinstance(value, Code): return value
73
    else: return Literal(value)
74

    
75
def is_null(value): return isinstance(value, Literal) and value.value == None
76

    
77
##### Tables
78

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

    
95
def as_Table(table):
96
    if table == None or isinstance(table, Code): return table
97
    else: return Table(table)
98

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

    
115
##### Columns
116

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

    
136
def is_table_col(col): return col.table != None
137

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

    
149
def to_name_only_col(col, check_table=None):
150
    col = as_Col(col)
151
    if not isinstance(col, Col): return col
152
    
153
    if check_table != None:
154
        table = col.table
155
        assert table == None or table == check_table
156
    return Col(col.name)
157

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

    
171
def remove_col_rename(col):
172
    if isinstance(col, NamedCol): col = col.code
173
    return col
174

    
175
class ColDict(dict):
176
    '''A dict that automatically makes inserted entries Col objects'''
177
    
178
    def __setitem__(self, key, value):
179
        return dict.__setitem__(self, key, as_Col(value, name=key))
180
    
181
    def update(self, dict_):
182
        for key, value in dict_.iteritems(): self[key] = value
183

    
184
##### Functions
185

    
186
class Function(Table): pass
187

    
188
class FunctionCall(Code):
189
    def __init__(self, function, *args):
190
        '''
191
        @param args [Code...] The function's arguments
192
        '''
193
        if not isinstance(function, Code): function = Function(function)
194
        args = map(remove_col_rename, args)
195
        
196
        self.function = function
197
        self.args = args
198
    
199
    def to_str(self, db):
200
        args_str = ', '.join((v.to_str(db) for v in self.args))
201
        return self.function.to_str(db)+'('+args_str+')'
202

    
203
def wrap_in_func(function, value):
204
    '''Wraps a value inside a function call.
205
    Propagates any column renaming to the returned value.
206
    '''
207
    name = None
208
    if isinstance(value, NamedCol): name = value.name
209
    value = FunctionCall(function, value)
210
    if name != None: value = NamedCol(name, value)
211
    return value
212

    
213
def unwrap_func_call(func_call, check_name=None):
214
    '''Unwraps any function call to its first argument.
215
    Also removes any column renaming.
216
    '''
217
    func_call = remove_col_rename(func_call)
218
    if not isinstance(func_call, FunctionCall): return func_call
219
    
220
    if check_name != None:
221
        name = func_call.function.name
222
        assert name == None or name == check_name
223
    return func_call.args[0]
224

    
225
##### Conditions
226

    
227
class ColValueCond(Code):
228
    def __init__(self, col, value):
229
        value = as_ValueCond(value)
230
        
231
        self.col = col
232
        self.value = value
233
    
234
    def to_str(self, db): return self.value.to_str(db, self.col)
235

    
236
def combine_conds(conds, keyword=None):
237
    '''
238
    @param keyword The keyword to add before the conditions, if any
239
    '''
240
    str_ = ''
241
    if keyword != None:
242
        if conds == []: whitespace = ''
243
        elif len(conds) == 1: whitespace = ' '
244
        else: whitespace = '\n'
245
        str_ += keyword+whitespace
246
    
247
    str_ += '\nAND '.join(conds)
248
    return str_
249

    
250
##### Condition column comparisons
251

    
252
class ValueCond(BasicObject):
253
    def __init__(self, value):
254
        if not isinstance(value, Code): value = Literal(value)
255
        value = remove_col_rename(value)
256
        
257
        self.value = value
258
    
259
    def to_str(self, db, left_value):
260
        '''
261
        @param left_value The Code object that the condition is being applied on
262
        '''
263
        raise NotImplemented()
264
    
265
    def __repr__(self): return self.to_str(mockDb, '<left_value>')
266

    
267
class CompareCond(ValueCond):
268
    def __init__(self, value, operator='='):
269
        '''
270
        @param operator By default, compares NULL values literally. Use '~=' or
271
            '~!=' to pass NULLs through.
272
        '''
273
        ValueCond.__init__(self, value)
274
        self.operator = operator
275
    
276
    def to_str(self, db, left_value):
277
        if not isinstance(left_value, Code): left_value = Col(left_value)
278
        left_value = remove_col_rename(left_value)
279
        
280
        right_value = self.value
281
        left = left_value.to_str(db)
282
        right = right_value.to_str(db)
283
        
284
        # Parse operator
285
        operator = self.operator
286
        passthru_null_ref = [False]
287
        operator = strings.remove_prefix('~', operator, passthru_null_ref)
288
        neg_ref = [False]
289
        operator = strings.remove_prefix('!', operator, neg_ref)
290
        equals = operator.endswith('=')
291
        if equals and is_null(self.value): operator = 'IS'
292
        
293
        # Create str
294
        str_ = left+' '+operator+' '+right
295
        if equals and not passthru_null_ref[0] and isinstance(right_value, Col):
296
            str_ = '('+str_+' OR ('+left+' IS NULL AND '+right+' IS NULL))'
297
        if neg_ref[0]: str_ = 'NOT '+str_
298
        return str_
299

    
300
# Tells as_ValueCond() to assume a non-ValueCond is a literal value
301
assume_literal = object()
302

    
303
def as_ValueCond(value, default_table=assume_literal):
304
    if not isinstance(value, ValueCond):
305
        if default_table is not assume_literal:
306
            value = as_Col(value, default_table)
307
        return CompareCond(value)
308
    else: return value
309

    
310
##### Joins
311

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

    
314
# Tells Join the left and right columns have the same name and are never NULL
315
join_same_not_null = object()
316

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

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

    
382
##### Value exprs
383

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