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