Project

General

Profile

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