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