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 2575 aaronmk
def is_safe_name(name):
13 2583 aaronmk
    '''A name is safe *and unambiguous* if it:
14
    * contains only *lowercase* word (\w) characters
15
    * doesn't start with a digit
16
    * contains "_", so that it's not a keyword
17
    '''
18
    return re.match(r'^(?=.*_)(?!\d)[^\WA-Z]+$', name)
19 2568 aaronmk
20 2499 aaronmk
def esc_name(name, quote='"'):
21 2572 aaronmk
    if is_safe_name(name): return name
22 2499 aaronmk
    return quote + name.replace(quote, quote+quote) + quote
23
        # doubling an embedded quote escapes it in both PostgreSQL and MySQL
24
25 2513 aaronmk
def clean_name(name): return name.replace('"', '').replace('`', '')
26
27 2219 aaronmk
##### SQL code objects
28
29 2349 aaronmk
class MockDb:
30 2503 aaronmk
    def esc_value(self, value): return strings.repr_no_u(value)
31 2349 aaronmk
32 2499 aaronmk
    def esc_name(self, name): return esc_name(name)
33 2349 aaronmk
mockDb = MockDb()
34
35 2514 aaronmk
class BasicObject(objects.BasicObject):
36
    def __init__(self, value): self.value = value
37
38
    def __str__(self): return clean_name(strings.repr_no_u(self))
39
40
class Code(BasicObject):
41 2211 aaronmk
    def to_str(self, db): raise NotImplemented()
42 2349 aaronmk
43 2514 aaronmk
    def __repr__(self): return self.to_str(mockDb)
44 2211 aaronmk
45 2269 aaronmk
class CustomCode(Code):
46 2256 aaronmk
    def __init__(self, str_): self.str_ = str_
47
48
    def to_str(self, db): return self.str_
49
50 2540 aaronmk
class Expr(Code):
51
    def __init__(self, expr): self.expr = expr
52
53
    def to_str(self, db): return '('+self.expr.to_str(db)+')'
54
55 2335 aaronmk
##### Literal values
56
57 2216 aaronmk
class Literal(Code):
58 2211 aaronmk
    def __init__(self, value): self.value = value
59 2213 aaronmk
60
    def to_str(self, db): return db.esc_value(self.value)
61 2211 aaronmk
62 2400 aaronmk
def as_Value(value):
63
    if isinstance(value, Code): return value
64
    else: return Literal(value)
65
66 2216 aaronmk
def is_null(value): return isinstance(value, Literal) and value.value == None
67
68 2335 aaronmk
##### Tables
69
70 2211 aaronmk
class Table(Code):
71
    def __init__(self, name, schema=None):
72
        '''
73
        @param schema str|None (for no schema)
74
        '''
75
        self.name = name
76
        self.schema = schema
77
78 2348 aaronmk
    def to_str(self, db):
79
        str_ = ''
80
        if self.schema != None: str_ += db.esc_name(self.schema)+'.'
81
        str_ += db.esc_name(self.name)
82
        return str_
83 2336 aaronmk
84
    def to_Table(self): return self
85 2211 aaronmk
86 2219 aaronmk
def as_Table(table):
87 2270 aaronmk
    if table == None or isinstance(table, Code): return table
88 2219 aaronmk
    else: return Table(table)
89
90 2336 aaronmk
class NamedTable(Table):
91
    def __init__(self, name, code, cols=None):
92
        Table.__init__(self, name)
93
94
        if not isinstance(code, Code): code = Table(code)
95
96
        self.code = code
97
        self.cols = cols
98
99
    def to_str(self, db):
100 2467 aaronmk
        str_ = self.code.to_str(db)+'\nAS '+Table.to_str(self, db)
101 2336 aaronmk
        if self.cols != None: str_ += ' ('+(', '.join(self.cols))+')'
102
        return str_
103
104
    def to_Table(self): return Table(self.name)
105
106 2335 aaronmk
##### Columns
107
108 2211 aaronmk
class Col(Code):
109
    def __init__(self, name, table=None):
110
        '''
111
        @param table Table|None (for no table)
112
        '''
113 2241 aaronmk
        if util.is_str(table): table = Table(table)
114 2211 aaronmk
        assert table == None or isinstance(table, Table)
115
116
        self.name = name
117
        self.table = table
118
119
    def to_str(self, db):
120
        str_ = ''
121
        if self.table != None: str_ += self.table.to_str(db)+'.'
122 2348 aaronmk
        str_ += db.esc_name(self.name)
123 2211 aaronmk
        return str_
124 2314 aaronmk
125
    def to_Col(self): return self
126 2211 aaronmk
127 2393 aaronmk
def is_table_col(col): return col.table != None
128
129 2563 aaronmk
def as_Col(col, table=None, name=None):
130
    '''
131
    @param name If not None, any non-Col input will be renamed using NamedCol.
132
    '''
133
    if name != None:
134
        col = as_Value(col)
135
        if not isinstance(col, Col): col = NamedCol(name, col)
136 2333 aaronmk
137
    if isinstance(col, Code): return col
138 2260 aaronmk
    else: return Col(col, table)
139
140 2401 aaronmk
def to_name_only_col(col, check_table=None):
141
    col = as_Col(col)
142 2579 aaronmk
    if not isinstance(col, Col): return col
143 2401 aaronmk
144
    if check_table != None:
145
        table = col.table
146
        assert table == None or table == check_table
147
    return Col(col.name)
148
149 2323 aaronmk
class NamedCol(Col):
150 2229 aaronmk
    def __init__(self, name, code):
151 2310 aaronmk
        Col.__init__(self, name)
152
153 2229 aaronmk
        if not isinstance(code, Code): code = Literal(code)
154
155
        self.code = code
156
157
    def to_str(self, db):
158 2310 aaronmk
        return self.code.to_str(db)+' AS '+Col.to_str(self, db)
159 2314 aaronmk
160
    def to_Col(self): return Col(self.name)
161 2229 aaronmk
162 2462 aaronmk
def remove_col_rename(col):
163
    if isinstance(col, NamedCol): col = col.code
164
    return col
165
166 2564 aaronmk
class ColDict(dict):
167
    '''A dict that automatically makes inserted entries Col objects'''
168
169
    def __setitem__(self, key, value):
170
        return dict.__setitem__(self, key, as_Col(value, name=key))
171
172
    def update(self, dict_):
173
        for key, value in dict_.iteritems(): self[key] = value
174
175 2524 aaronmk
##### Functions
176
177
class Function(Table): pass
178
179
class FunctionCall(Code):
180
    def __init__(self, function, *args):
181
        '''
182
        @param args [Code...] The function's arguments
183
        '''
184
        if not isinstance(function, Code): function = Function(function)
185 2532 aaronmk
        args = map(remove_col_rename, args)
186 2524 aaronmk
187
        self.function = function
188
        self.args = args
189
190
    def to_str(self, db):
191
        args_str = ', '.join((v.to_str(db) for v in self.args))
192
        return self.function.to_str(db)+'('+args_str+')'
193
194 2533 aaronmk
def wrap_in_func(function, value):
195
    '''Wraps a value inside a function call.
196
    Propagates any column renaming to the returned value.
197
    '''
198
    name = None
199
    if isinstance(value, NamedCol): name = value.name
200
    value = FunctionCall(function, value)
201
    if name != None: value = NamedCol(name, value)
202
    return value
203
204 2561 aaronmk
def unwrap_func_call(func_call, check_name=None):
205
    '''Unwraps any function call to its first argument.
206
    Also removes any column renaming.
207
    '''
208
    func_call = remove_col_rename(func_call)
209
    if not isinstance(func_call, FunctionCall): return func_call
210
211
    if check_name != None:
212
        name = func_call.function.name
213
        assert name == None or name == check_name
214
    return func_call.args[0]
215
216 2335 aaronmk
##### Conditions
217 2259 aaronmk
218 2398 aaronmk
class ColValueCond(Code):
219
    def __init__(self, col, value):
220
        value = as_ValueCond(value)
221
222
        self.col = col
223
        self.value = value
224
225
    def to_str(self, db): return self.value.to_str(db, self.col)
226
227 2577 aaronmk
def combine_conds(conds, keyword=None):
228
    '''
229
    @param keyword The keyword to add before the conditions, if any
230
    '''
231
    str_ = ''
232
    if keyword != None:
233
        if conds == []: whitespace = ''
234
        elif len(conds) == 1: whitespace = ' '
235
        else: whitespace = '\n'
236
        str_ += keyword+whitespace
237
238
    str_ += '\nAND '.join(conds)
239
    return str_
240
241 2398 aaronmk
##### Condition column comparisons
242
243 2514 aaronmk
class ValueCond(BasicObject):
244 2213 aaronmk
    def __init__(self, value):
245 2225 aaronmk
        if not isinstance(value, Code): value = Literal(value)
246 2462 aaronmk
        value = remove_col_rename(value)
247 2213 aaronmk
248
        self.value = value
249 2214 aaronmk
250 2216 aaronmk
    def to_str(self, db, left_value):
251 2214 aaronmk
        '''
252 2216 aaronmk
        @param left_value The Code object that the condition is being applied on
253 2214 aaronmk
        '''
254
        raise NotImplemented()
255 2228 aaronmk
256 2514 aaronmk
    def __repr__(self): return self.to_str(mockDb, '<left_value>')
257 2211 aaronmk
258
class CompareCond(ValueCond):
259
    def __init__(self, value, operator='='):
260 2222 aaronmk
        '''
261
        @param operator By default, compares NULL values literally. Use '~=' or
262
            '~!=' to pass NULLs through.
263
        '''
264 2211 aaronmk
        ValueCond.__init__(self, value)
265
        self.operator = operator
266
267 2216 aaronmk
    def to_str(self, db, left_value):
268
        if not isinstance(left_value, Code): left_value = Col(left_value)
269 2462 aaronmk
        left_value = remove_col_rename(left_value)
270 2216 aaronmk
271 2222 aaronmk
        right_value = self.value
272
        left = left_value.to_str(db)
273
        right = right_value.to_str(db)
274
275
        # Parse operator
276 2216 aaronmk
        operator = self.operator
277 2222 aaronmk
        passthru_null_ref = [False]
278
        operator = strings.remove_prefix('~', operator, passthru_null_ref)
279
        neg_ref = [False]
280
        operator = strings.remove_prefix('!', operator, neg_ref)
281
        equals = operator.endswith('=')
282
        if equals and is_null(self.value): operator = 'IS'
283
284
        # Create str
285
        str_ = left+' '+operator+' '+right
286
        if equals and not passthru_null_ref[0] and isinstance(right_value, Col):
287 2578 aaronmk
            str_ = '('+str_+' OR ('+left+' IS NULL AND '+right+' IS NULL))'
288
        if neg_ref[0]: str_ = 'NOT '+str_
289 2222 aaronmk
        return str_
290 2216 aaronmk
291 2260 aaronmk
# Tells as_ValueCond() to assume a non-ValueCond is a literal value
292
assume_literal = object()
293
294
def as_ValueCond(value, default_table=assume_literal):
295
    if not isinstance(value, ValueCond):
296
        if default_table is not assume_literal:
297
            value = as_Col(value, default_table)
298
        return CompareCond(value)
299 2216 aaronmk
    else: return value
300 2219 aaronmk
301 2335 aaronmk
##### Joins
302
303 2352 aaronmk
join_same = object() # tells Join the left and right columns have the same name
304 2260 aaronmk
305 2353 aaronmk
# Tells Join the left and right columns have the same name and are never NULL
306
join_same_not_null = object()
307
308 2260 aaronmk
filter_out = object() # tells Join to filter out rows that match the join
309
310 2514 aaronmk
class Join(BasicObject):
311 2260 aaronmk
    def __init__(self, table, mapping, type_=None):
312
        '''
313
        @param mapping dict(right_table_col=left_table_col, ...)
314 2352 aaronmk
            * if left_table_col is join_same: left_table_col = right_table_col
315 2353 aaronmk
              * Note that right_table_col must be a string
316
            * if left_table_col is join_same_not_null:
317
              left_table_col = right_table_col and both have NOT NULL constraint
318
              * Note that right_table_col must be a string
319 2260 aaronmk
        @param type_ None (for plain join)|str (e.g. 'LEFT')|filter_out
320
            * filter_out: equivalent to 'LEFT' with the query filtered by
321
              `table_pkey IS NULL` (indicating no match)
322
        '''
323
        if util.is_str(table): table = Table(table)
324
        assert type_ == None or util.is_str(type_) or type_ is filter_out
325
326
        self.table = table
327
        self.mapping = mapping
328
        self.type_ = type_
329
330
    def to_str(self, db, left_table):
331 2353 aaronmk
        # Switch order (left_table is on the right in the comparison)
332
        right_table = left_table
333
        left_table = self.table # note left_table is reassigned
334
335 2260 aaronmk
        def join(entry):
336
            '''Parses non-USING joins'''
337
            right_table_col, left_table_col = entry
338
339 2353 aaronmk
            # Switch order (right_table_col is on the left in the comparison)
340
            left = right_table_col
341
            right = left_table_col
342
343 2260 aaronmk
            # Parse special values
344 2353 aaronmk
            if right is join_same: right = left
345
            elif right is join_same_not_null:
346
                right = CompareCond(as_Col(left, right_table), '~=')
347 2260 aaronmk
348 2353 aaronmk
            right = as_ValueCond(right, right_table)
349 2578 aaronmk
            return right.to_str(db, as_Col(left, left_table))
350 2260 aaronmk
351 2265 aaronmk
        # Create join condition
352
        type_ = self.type_
353 2276 aaronmk
        joins = self.mapping
354 2265 aaronmk
        if type_ is not filter_out and reduce(operator.and_,
355 2460 aaronmk
            (v is join_same_not_null for v in joins.itervalues())):
356 2260 aaronmk
            # all cols w/ USING, so can use simpler USING syntax
357 2298 aaronmk
            cols = (as_Col(v).to_str(db) for v in joins.iterkeys())
358
            join_cond = 'USING ('+(', '.join(cols))+')'
359 2576 aaronmk
        else:
360
            if len(joins) == 1: whitespace = ' '
361
            else: whitespace = '\n'
362 2577 aaronmk
            join_cond = combine_conds(map(join, joins.iteritems()), 'ON')
363 2260 aaronmk
364
        # Create join
365
        if type_ is filter_out: type_ = 'LEFT'
366 2266 aaronmk
        str_ = ''
367
        if type_ != None: str_ += type_+' '
368 2353 aaronmk
        str_ += 'JOIN '+left_table.to_str(db)+' '+join_cond
369 2266 aaronmk
        return str_
370 2349 aaronmk
371 2514 aaronmk
    def __repr__(self): return self.to_str(mockDb, '<left_table>')
372 2424 aaronmk
373
##### Value exprs
374
375
row_count = CustomCode('count(*)')