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