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): return re.match(r'^[^\WA-Z]+$', name) # no uppercase
13

    
14
def esc_name(name, quote='"'):
15
    return quote + name.replace(quote, quote+quote) + quote
16
        # doubling an embedded quote escapes it in both PostgreSQL and MySQL
17

    
18
def clean_name(name): return name.replace('"', '').replace('`', '')
19

    
20
##### SQL code objects
21

    
22
class MockDb:
23
    def esc_value(self, value): return strings.repr_no_u(value)
24
    
25
    def esc_name(self, name): return esc_name(name)
26
mockDb = MockDb()
27

    
28
class BasicObject(objects.BasicObject):
29
    def __init__(self, value): self.value = value
30
    
31
    def __str__(self): return clean_name(strings.repr_no_u(self))
32

    
33
class Code(BasicObject):
34
    def to_str(self, db): raise NotImplemented()
35
    
36
    def __repr__(self): return self.to_str(mockDb)
37

    
38
class CustomCode(Code):
39
    def __init__(self, str_): self.str_ = str_
40
    
41
    def to_str(self, db): return self.str_
42

    
43
class Expr(Code):
44
    def __init__(self, expr): self.expr = expr
45
    
46
    def to_str(self, db): return '('+self.expr.to_str(db)+')'
47

    
48
##### Literal values
49

    
50
class Literal(Code):
51
    def __init__(self, value): self.value = value
52
    
53
    def to_str(self, db): return db.esc_value(self.value)
54

    
55
def as_Value(value):
56
    if isinstance(value, Code): return value
57
    else: return Literal(value)
58

    
59
def is_null(value): return isinstance(value, Literal) and value.value == None
60

    
61
##### Tables
62

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

    
79
def as_Table(table):
80
    if table == None or isinstance(table, Code): return table
81
    else: return Table(table)
82

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

    
99
##### Columns
100

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

    
120
def is_table_col(col): return col.table != None
121

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

    
133
def to_name_only_col(col, check_table=None):
134
    col = as_Col(col)
135
    
136
    if check_table != None:
137
        table = col.table
138
        assert table == None or table == check_table
139
    return Col(col.name)
140

    
141
class NamedCol(Col):
142
    def __init__(self, name, code):
143
        Col.__init__(self, name)
144
        
145
        if not isinstance(code, Code): code = Literal(code)
146
        
147
        self.code = code
148
    
149
    def to_str(self, db):
150
        return self.code.to_str(db)+' AS '+Col.to_str(self, db)
151
    
152
    def to_Col(self): return Col(self.name)
153

    
154
def remove_col_rename(col):
155
    if isinstance(col, NamedCol): col = col.code
156
    return col
157

    
158
class ColDict(dict):
159
    '''A dict that automatically makes inserted entries Col objects'''
160
    
161
    def __setitem__(self, key, value):
162
        return dict.__setitem__(self, key, as_Col(value, name=key))
163
    
164
    def update(self, dict_):
165
        for key, value in dict_.iteritems(): self[key] = value
166

    
167
##### Functions
168

    
169
class Function(Table): pass
170

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

    
186
def wrap_in_func(function, value):
187
    '''Wraps a value inside a function call.
188
    Propagates any column renaming to the returned value.
189
    '''
190
    name = None
191
    if isinstance(value, NamedCol): name = value.name
192
    value = FunctionCall(function, value)
193
    if name != None: value = NamedCol(name, value)
194
    return value
195

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

    
208
##### Conditions
209

    
210
class ColValueCond(Code):
211
    def __init__(self, col, value):
212
        value = as_ValueCond(value)
213
        
214
        self.col = col
215
        self.value = value
216
    
217
    def to_str(self, db): return self.value.to_str(db, self.col)
218

    
219
##### Condition column comparisons
220

    
221
class ValueCond(BasicObject):
222
    def __init__(self, value):
223
        if not isinstance(value, Code): value = Literal(value)
224
        value = remove_col_rename(value)
225
        
226
        self.value = value
227
    
228
    def to_str(self, db, left_value):
229
        '''
230
        @param left_value The Code object that the condition is being applied on
231
        '''
232
        raise NotImplemented()
233
    
234
    def __repr__(self): return self.to_str(mockDb, '<left_value>')
235

    
236
class CompareCond(ValueCond):
237
    def __init__(self, value, operator='='):
238
        '''
239
        @param operator By default, compares NULL values literally. Use '~=' or
240
            '~!=' to pass NULLs through.
241
        '''
242
        ValueCond.__init__(self, value)
243
        self.operator = operator
244
    
245
    def to_str(self, db, left_value):
246
        if not isinstance(left_value, Code): left_value = Col(left_value)
247
        left_value = remove_col_rename(left_value)
248
        
249
        right_value = self.value
250
        left = left_value.to_str(db)
251
        right = right_value.to_str(db)
252
        
253
        # Parse operator
254
        operator = self.operator
255
        passthru_null_ref = [False]
256
        operator = strings.remove_prefix('~', operator, passthru_null_ref)
257
        neg_ref = [False]
258
        operator = strings.remove_prefix('!', operator, neg_ref)
259
        equals = operator.endswith('=')
260
        if equals and is_null(self.value): operator = 'IS'
261
        
262
        # Create str
263
        str_ = left+' '+operator+' '+right
264
        if equals and not passthru_null_ref[0] and isinstance(right_value, Col):
265
            str_ += ' OR ('+left+' IS NULL AND '+right+' IS NULL)'
266
        if neg_ref[0]: str_ = 'NOT ('+str_+')'
267
        return str_
268

    
269
# Tells as_ValueCond() to assume a non-ValueCond is a literal value
270
assume_literal = object()
271

    
272
def as_ValueCond(value, default_table=assume_literal):
273
    if not isinstance(value, ValueCond):
274
        if default_table is not assume_literal:
275
            value = as_Col(value, default_table)
276
        return CompareCond(value)
277
    else: return value
278

    
279
##### Joins
280

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

    
283
# Tells Join the left and right columns have the same name and are never NULL
284
join_same_not_null = object()
285

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

    
288
class Join(BasicObject):
289
    def __init__(self, table, mapping, type_=None):
290
        '''
291
        @param mapping dict(right_table_col=left_table_col, ...)
292
            * if left_table_col is join_same: left_table_col = right_table_col
293
              * Note that right_table_col must be a string
294
            * if left_table_col is join_same_not_null:
295
              left_table_col = right_table_col and both have NOT NULL constraint
296
              * Note that right_table_col must be a string
297
        @param type_ None (for plain join)|str (e.g. 'LEFT')|filter_out
298
            * filter_out: equivalent to 'LEFT' with the query filtered by
299
              `table_pkey IS NULL` (indicating no match)
300
        '''
301
        if util.is_str(table): table = Table(table)
302
        assert type_ == None or util.is_str(type_) or type_ is filter_out
303
        
304
        self.table = table
305
        self.mapping = mapping
306
        self.type_ = type_
307
    
308
    def to_str(self, db, left_table):
309
        # Switch order (left_table is on the right in the comparison)
310
        right_table = left_table
311
        left_table = self.table # note left_table is reassigned
312
        
313
        def join(entry):
314
            '''Parses non-USING joins'''
315
            right_table_col, left_table_col = entry
316
            
317
            # Switch order (right_table_col is on the left in the comparison)
318
            left = right_table_col
319
            right = left_table_col
320
            
321
            # Parse special values
322
            if right is join_same: right = left
323
            elif right is join_same_not_null:
324
                right = CompareCond(as_Col(left, right_table), '~=')
325
            
326
            right = as_ValueCond(right, right_table)
327
            return '('+right.to_str(db, as_Col(left, left_table))+')'
328
        
329
        # Create join condition
330
        type_ = self.type_
331
        joins = self.mapping
332
        if type_ is not filter_out and reduce(operator.and_,
333
            (v is join_same_not_null for v in joins.itervalues())):
334
            # all cols w/ USING, so can use simpler USING syntax
335
            cols = (as_Col(v).to_str(db) for v in joins.iterkeys())
336
            join_cond = 'USING ('+(', '.join(cols))+')'
337
        else: join_cond = 'ON\n'+('\nAND\n'.join(map(join, joins.iteritems())))
338
        
339
        # Create join
340
        if type_ is filter_out: type_ = 'LEFT'
341
        str_ = ''
342
        if type_ != None: str_ += type_+' '
343
        str_ += 'JOIN '+left_table.to_str(db)+' '+join_cond
344
        return str_
345
    
346
    def __repr__(self): return self.to_str(mockDb, '<left_table>')
347

    
348
##### Value exprs
349

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