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
##### Escaping
11

    
12
def is_safe_name(name):
13
    '''A name is safe *and unambiguous* if it contains only lowercase word (\w)
14
    characters and doesn't start with a digit''' 
15
    return re.match(r'^(?!\d)[^\WA-Z]+$', name) 
16

    
17
def esc_name(name, quote='"'):
18
    if is_safe_name(name): return name
19
    return quote + name.replace(quote, quote+quote) + quote
20
        # doubling an embedded quote escapes it in both PostgreSQL and MySQL
21

    
22
def clean_name(name): return name.replace('"', '').replace('`', '')
23

    
24
##### SQL code objects
25

    
26
class MockDb:
27
    def esc_value(self, value): return strings.repr_no_u(value)
28
    
29
    def esc_name(self, name): return esc_name(name)
30
mockDb = MockDb()
31

    
32
class BasicObject(objects.BasicObject):
33
    def __init__(self, value): self.value = value
34
    
35
    def __str__(self): return clean_name(strings.repr_no_u(self))
36

    
37
class Code(BasicObject):
38
    def to_str(self, db): raise NotImplemented()
39
    
40
    def __repr__(self): return self.to_str(mockDb)
41

    
42
class CustomCode(Code):
43
    def __init__(self, str_): self.str_ = str_
44
    
45
    def to_str(self, db): return self.str_
46

    
47
class Expr(Code):
48
    def __init__(self, expr): self.expr = expr
49
    
50
    def to_str(self, db): return '('+self.expr.to_str(db)+')'
51

    
52
##### Literal values
53

    
54
class Literal(Code):
55
    def __init__(self, value): self.value = value
56
    
57
    def to_str(self, db): return db.esc_value(self.value)
58

    
59
def as_Value(value):
60
    if isinstance(value, Code): return value
61
    else: return Literal(value)
62

    
63
def is_null(value): return isinstance(value, Literal) and value.value == None
64

    
65
##### Tables
66

    
67
class Table(Code):
68
    def __init__(self, name, schema=None):
69
        '''
70
        @param schema str|None (for no schema)
71
        '''
72
        self.name = name
73
        self.schema = schema
74
    
75
    def to_str(self, db):
76
        str_ = ''
77
        if self.schema != None: str_ += db.esc_name(self.schema)+'.'
78
        str_ += db.esc_name(self.name)
79
        return str_
80
    
81
    def to_Table(self): return self
82

    
83
def as_Table(table):
84
    if table == None or isinstance(table, Code): return table
85
    else: return Table(table)
86

    
87
class NamedTable(Table):
88
    def __init__(self, name, code, cols=None):
89
        Table.__init__(self, name)
90
        
91
        if not isinstance(code, Code): code = Table(code)
92
        
93
        self.code = code
94
        self.cols = cols
95
    
96
    def to_str(self, db):
97
        str_ = self.code.to_str(db)+'\nAS '+Table.to_str(self, db)
98
        if self.cols != None: str_ += ' ('+(', '.join(self.cols))+')'
99
        return str_
100
    
101
    def to_Table(self): return Table(self.name)
102

    
103
##### Columns
104

    
105
class Col(Code):
106
    def __init__(self, name, table=None):
107
        '''
108
        @param table Table|None (for no table)
109
        '''
110
        if util.is_str(table): table = Table(table)
111
        assert table == None or isinstance(table, Table)
112
        
113
        self.name = name
114
        self.table = table
115
    
116
    def to_str(self, db):
117
        str_ = ''
118
        if self.table != None: str_ += self.table.to_str(db)+'.'
119
        str_ += db.esc_name(self.name)
120
        return str_
121
    
122
    def to_Col(self): return self
123

    
124
def is_table_col(col): return col.table != None
125

    
126
def as_Col(col, table=None, name=None):
127
    '''
128
    @param name If not None, any non-Col input will be renamed using NamedCol.
129
    '''
130
    if name != None:
131
        col = as_Value(col)
132
        if not isinstance(col, Col): col = NamedCol(name, col)
133
    
134
    if isinstance(col, Code): return col
135
    else: return Col(col, table)
136

    
137
def to_name_only_col(col, check_table=None):
138
    col = as_Col(col)
139
    if not isinstance(col, Col): return col
140
    
141
    if check_table != None:
142
        table = col.table
143
        assert table == None or table == check_table
144
    return Col(col.name)
145

    
146
class NamedCol(Col):
147
    def __init__(self, name, code):
148
        Col.__init__(self, name)
149
        
150
        if not isinstance(code, Code): code = Literal(code)
151
        
152
        self.code = code
153
    
154
    def to_str(self, db):
155
        return self.code.to_str(db)+' AS '+Col.to_str(self, db)
156
    
157
    def to_Col(self): return Col(self.name)
158

    
159
def remove_col_rename(col):
160
    if isinstance(col, NamedCol): col = col.code
161
    return col
162

    
163
class ColDict(dict):
164
    '''A dict that automatically makes inserted entries Col objects'''
165
    
166
    def __setitem__(self, key, value):
167
        return dict.__setitem__(self, key, as_Col(value, name=key))
168
    
169
    def update(self, dict_):
170
        for key, value in dict_.iteritems(): self[key] = value
171

    
172
##### Functions
173

    
174
class Function(Table): pass
175

    
176
class FunctionCall(Code):
177
    def __init__(self, function, *args):
178
        '''
179
        @param args [Code...] The function's arguments
180
        '''
181
        if not isinstance(function, Code): function = Function(function)
182
        args = map(remove_col_rename, args)
183
        
184
        self.function = function
185
        self.args = args
186
    
187
    def to_str(self, db):
188
        args_str = ', '.join((v.to_str(db) for v in self.args))
189
        return self.function.to_str(db)+'('+args_str+')'
190

    
191
def wrap_in_func(function, value):
192
    '''Wraps a value inside a function call.
193
    Propagates any column renaming to the returned value.
194
    '''
195
    name = None
196
    if isinstance(value, NamedCol): name = value.name
197
    value = FunctionCall(function, value)
198
    if name != None: value = NamedCol(name, value)
199
    return value
200

    
201
def unwrap_func_call(func_call, check_name=None):
202
    '''Unwraps any function call to its first argument.
203
    Also removes any column renaming.
204
    '''
205
    func_call = remove_col_rename(func_call)
206
    if not isinstance(func_call, FunctionCall): return func_call
207
    
208
    if check_name != None:
209
        name = func_call.function.name
210
        assert name == None or name == check_name
211
    return func_call.args[0]
212

    
213
##### Conditions
214

    
215
class ColValueCond(Code):
216
    def __init__(self, col, value):
217
        value = as_ValueCond(value)
218
        
219
        self.col = col
220
        self.value = value
221
    
222
    def to_str(self, db): return self.value.to_str(db, self.col)
223

    
224
def combine_conds(conds, keyword=None):
225
    '''
226
    @param keyword The keyword to add before the conditions, if any
227
    '''
228
    str_ = ''
229
    if keyword != None:
230
        if conds == []: whitespace = ''
231
        elif len(conds) == 1: whitespace = ' '
232
        else: whitespace = '\n'
233
        str_ += keyword+whitespace
234
    
235
    str_ += '\nAND '.join(conds)
236
    return str_
237

    
238
##### Condition column comparisons
239

    
240
class ValueCond(BasicObject):
241
    def __init__(self, value):
242
        if not isinstance(value, Code): value = Literal(value)
243
        value = remove_col_rename(value)
244
        
245
        self.value = value
246
    
247
    def to_str(self, db, left_value):
248
        '''
249
        @param left_value The Code object that the condition is being applied on
250
        '''
251
        raise NotImplemented()
252
    
253
    def __repr__(self): return self.to_str(mockDb, '<left_value>')
254

    
255
class CompareCond(ValueCond):
256
    def __init__(self, value, operator='='):
257
        '''
258
        @param operator By default, compares NULL values literally. Use '~=' or
259
            '~!=' to pass NULLs through.
260
        '''
261
        ValueCond.__init__(self, value)
262
        self.operator = operator
263
    
264
    def to_str(self, db, left_value):
265
        if not isinstance(left_value, Code): left_value = Col(left_value)
266
        left_value = remove_col_rename(left_value)
267
        
268
        right_value = self.value
269
        left = left_value.to_str(db)
270
        right = right_value.to_str(db)
271
        
272
        # Parse operator
273
        operator = self.operator
274
        passthru_null_ref = [False]
275
        operator = strings.remove_prefix('~', operator, passthru_null_ref)
276
        neg_ref = [False]
277
        operator = strings.remove_prefix('!', operator, neg_ref)
278
        equals = operator.endswith('=')
279
        if equals and is_null(self.value): operator = 'IS'
280
        
281
        # Create str
282
        str_ = left+' '+operator+' '+right
283
        if equals and not passthru_null_ref[0] and isinstance(right_value, Col):
284
            str_ = '('+str_+' OR ('+left+' IS NULL AND '+right+' IS NULL))'
285
        if neg_ref[0]: str_ = 'NOT '+str_
286
        return str_
287

    
288
# Tells as_ValueCond() to assume a non-ValueCond is a literal value
289
assume_literal = object()
290

    
291
def as_ValueCond(value, default_table=assume_literal):
292
    if not isinstance(value, ValueCond):
293
        if default_table is not assume_literal:
294
            value = as_Col(value, default_table)
295
        return CompareCond(value)
296
    else: return value
297

    
298
##### Joins
299

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

    
302
# Tells Join the left and right columns have the same name and are never NULL
303
join_same_not_null = object()
304

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

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

    
370
##### Value exprs
371

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