Project

General

Profile

1 2211 aaronmk
# SQL code generation
2
3 2276 aaronmk
import operator
4 2568 aaronmk
import re
5 2276 aaronmk
6 2360 aaronmk
import objects
7 2222 aaronmk
import strings
8 2227 aaronmk
import util
9 2211 aaronmk
10 2499 aaronmk
##### Escaping
11
12 2568 aaronmk
def is_safe_name(name): return re.match(r'^\w+$', name)
13
14 2499 aaronmk
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 2513 aaronmk
def clean_name(name): return name.replace('"', '').replace('`', '')
19
20 2219 aaronmk
##### SQL code objects
21
22 2349 aaronmk
class MockDb:
23 2503 aaronmk
    def esc_value(self, value): return strings.repr_no_u(value)
24 2349 aaronmk
25 2499 aaronmk
    def esc_name(self, name): return esc_name(name)
26 2349 aaronmk
mockDb = MockDb()
27
28 2514 aaronmk
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 2211 aaronmk
    def to_str(self, db): raise NotImplemented()
35 2349 aaronmk
36 2514 aaronmk
    def __repr__(self): return self.to_str(mockDb)
37 2211 aaronmk
38 2269 aaronmk
class CustomCode(Code):
39 2256 aaronmk
    def __init__(self, str_): self.str_ = str_
40
41
    def to_str(self, db): return self.str_
42
43 2540 aaronmk
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 2335 aaronmk
##### Literal values
49
50 2216 aaronmk
class Literal(Code):
51 2211 aaronmk
    def __init__(self, value): self.value = value
52 2213 aaronmk
53
    def to_str(self, db): return db.esc_value(self.value)
54 2211 aaronmk
55 2400 aaronmk
def as_Value(value):
56
    if isinstance(value, Code): return value
57
    else: return Literal(value)
58
59 2216 aaronmk
def is_null(value): return isinstance(value, Literal) and value.value == None
60
61 2335 aaronmk
##### Tables
62
63 2211 aaronmk
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 2348 aaronmk
    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 2336 aaronmk
77
    def to_Table(self): return self
78 2211 aaronmk
79 2219 aaronmk
def as_Table(table):
80 2270 aaronmk
    if table == None or isinstance(table, Code): return table
81 2219 aaronmk
    else: return Table(table)
82
83 2336 aaronmk
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 2467 aaronmk
        str_ = self.code.to_str(db)+'\nAS '+Table.to_str(self, db)
94 2336 aaronmk
        if self.cols != None: str_ += ' ('+(', '.join(self.cols))+')'
95
        return str_
96
97
    def to_Table(self): return Table(self.name)
98
99 2335 aaronmk
##### Columns
100
101 2211 aaronmk
class Col(Code):
102
    def __init__(self, name, table=None):
103
        '''
104
        @param table Table|None (for no table)
105
        '''
106 2241 aaronmk
        if util.is_str(table): table = Table(table)
107 2211 aaronmk
        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 2348 aaronmk
        str_ += db.esc_name(self.name)
116 2211 aaronmk
        return str_
117 2314 aaronmk
118
    def to_Col(self): return self
119 2211 aaronmk
120 2393 aaronmk
def is_table_col(col): return col.table != None
121
122 2563 aaronmk
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 2333 aaronmk
130
    if isinstance(col, Code): return col
131 2260 aaronmk
    else: return Col(col, table)
132
133 2401 aaronmk
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 2323 aaronmk
class NamedCol(Col):
142 2229 aaronmk
    def __init__(self, name, code):
143 2310 aaronmk
        Col.__init__(self, name)
144
145 2229 aaronmk
        if not isinstance(code, Code): code = Literal(code)
146
147
        self.code = code
148
149
    def to_str(self, db):
150 2310 aaronmk
        return self.code.to_str(db)+' AS '+Col.to_str(self, db)
151 2314 aaronmk
152
    def to_Col(self): return Col(self.name)
153 2229 aaronmk
154 2462 aaronmk
def remove_col_rename(col):
155
    if isinstance(col, NamedCol): col = col.code
156
    return col
157
158 2564 aaronmk
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 2524 aaronmk
##### 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 2532 aaronmk
        args = map(remove_col_rename, args)
178 2524 aaronmk
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 2533 aaronmk
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 2561 aaronmk
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 2335 aaronmk
##### Conditions
209 2259 aaronmk
210 2398 aaronmk
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 2514 aaronmk
class ValueCond(BasicObject):
222 2213 aaronmk
    def __init__(self, value):
223 2225 aaronmk
        if not isinstance(value, Code): value = Literal(value)
224 2462 aaronmk
        value = remove_col_rename(value)
225 2213 aaronmk
226
        self.value = value
227 2214 aaronmk
228 2216 aaronmk
    def to_str(self, db, left_value):
229 2214 aaronmk
        '''
230 2216 aaronmk
        @param left_value The Code object that the condition is being applied on
231 2214 aaronmk
        '''
232
        raise NotImplemented()
233 2228 aaronmk
234 2514 aaronmk
    def __repr__(self): return self.to_str(mockDb, '<left_value>')
235 2211 aaronmk
236
class CompareCond(ValueCond):
237
    def __init__(self, value, operator='='):
238 2222 aaronmk
        '''
239
        @param operator By default, compares NULL values literally. Use '~=' or
240
            '~!=' to pass NULLs through.
241
        '''
242 2211 aaronmk
        ValueCond.__init__(self, value)
243
        self.operator = operator
244
245 2216 aaronmk
    def to_str(self, db, left_value):
246
        if not isinstance(left_value, Code): left_value = Col(left_value)
247 2462 aaronmk
        left_value = remove_col_rename(left_value)
248 2216 aaronmk
249 2222 aaronmk
        right_value = self.value
250
        left = left_value.to_str(db)
251
        right = right_value.to_str(db)
252
253
        # Parse operator
254 2216 aaronmk
        operator = self.operator
255 2222 aaronmk
        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 2216 aaronmk
269 2260 aaronmk
# 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 2216 aaronmk
    else: return value
278 2219 aaronmk
279 2335 aaronmk
##### Joins
280
281 2352 aaronmk
join_same = object() # tells Join the left and right columns have the same name
282 2260 aaronmk
283 2353 aaronmk
# Tells Join the left and right columns have the same name and are never NULL
284
join_same_not_null = object()
285
286 2260 aaronmk
filter_out = object() # tells Join to filter out rows that match the join
287
288 2514 aaronmk
class Join(BasicObject):
289 2260 aaronmk
    def __init__(self, table, mapping, type_=None):
290
        '''
291
        @param mapping dict(right_table_col=left_table_col, ...)
292 2352 aaronmk
            * if left_table_col is join_same: left_table_col = right_table_col
293 2353 aaronmk
              * 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 2260 aaronmk
        @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 2353 aaronmk
        # 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 2260 aaronmk
        def join(entry):
314
            '''Parses non-USING joins'''
315
            right_table_col, left_table_col = entry
316
317 2353 aaronmk
            # Switch order (right_table_col is on the left in the comparison)
318
            left = right_table_col
319
            right = left_table_col
320
321 2260 aaronmk
            # Parse special values
322 2353 aaronmk
            if right is join_same: right = left
323
            elif right is join_same_not_null:
324
                right = CompareCond(as_Col(left, right_table), '~=')
325 2260 aaronmk
326 2353 aaronmk
            right = as_ValueCond(right, right_table)
327 2410 aaronmk
            return '('+right.to_str(db, as_Col(left, left_table))+')'
328 2260 aaronmk
329 2265 aaronmk
        # Create join condition
330
        type_ = self.type_
331 2276 aaronmk
        joins = self.mapping
332 2265 aaronmk
        if type_ is not filter_out and reduce(operator.and_,
333 2460 aaronmk
            (v is join_same_not_null for v in joins.itervalues())):
334 2260 aaronmk
            # all cols w/ USING, so can use simpler USING syntax
335 2298 aaronmk
            cols = (as_Col(v).to_str(db) for v in joins.iterkeys())
336
            join_cond = 'USING ('+(', '.join(cols))+')'
337 2467 aaronmk
        else: join_cond = 'ON\n'+('\nAND\n'.join(map(join, joins.iteritems())))
338 2260 aaronmk
339
        # Create join
340
        if type_ is filter_out: type_ = 'LEFT'
341 2266 aaronmk
        str_ = ''
342
        if type_ != None: str_ += type_+' '
343 2353 aaronmk
        str_ += 'JOIN '+left_table.to_str(db)+' '+join_cond
344 2266 aaronmk
        return str_
345 2349 aaronmk
346 2514 aaronmk
    def __repr__(self): return self.to_str(mockDb, '<left_table>')
347 2424 aaronmk
348
##### Value exprs
349
350
row_count = CustomCode('count(*)')