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