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