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
140
    if check_table != None:
141
        table = col.table
142
        assert table == None or table == check_table
143
    return Col(col.name)
144
145 2323 aaronmk
class NamedCol(Col):
146 2229 aaronmk
    def __init__(self, name, code):
147 2310 aaronmk
        Col.__init__(self, name)
148
149 2229 aaronmk
        if not isinstance(code, Code): code = Literal(code)
150
151
        self.code = code
152
153
    def to_str(self, db):
154 2310 aaronmk
        return self.code.to_str(db)+' AS '+Col.to_str(self, db)
155 2314 aaronmk
156
    def to_Col(self): return Col(self.name)
157 2229 aaronmk
158 2462 aaronmk
def remove_col_rename(col):
159
    if isinstance(col, NamedCol): col = col.code
160
    return col
161
162 2564 aaronmk
class ColDict(dict):
163
    '''A dict that automatically makes inserted entries Col objects'''
164
165
    def __setitem__(self, key, value):
166
        return dict.__setitem__(self, key, as_Col(value, name=key))
167
168
    def update(self, dict_):
169
        for key, value in dict_.iteritems(): self[key] = value
170
171 2524 aaronmk
##### Functions
172
173
class Function(Table): pass
174
175
class FunctionCall(Code):
176
    def __init__(self, function, *args):
177
        '''
178
        @param args [Code...] The function's arguments
179
        '''
180
        if not isinstance(function, Code): function = Function(function)
181 2532 aaronmk
        args = map(remove_col_rename, args)
182 2524 aaronmk
183
        self.function = function
184
        self.args = args
185
186
    def to_str(self, db):
187
        args_str = ', '.join((v.to_str(db) for v in self.args))
188
        return self.function.to_str(db)+'('+args_str+')'
189
190 2533 aaronmk
def wrap_in_func(function, value):
191
    '''Wraps a value inside a function call.
192
    Propagates any column renaming to the returned value.
193
    '''
194
    name = None
195
    if isinstance(value, NamedCol): name = value.name
196
    value = FunctionCall(function, value)
197
    if name != None: value = NamedCol(name, value)
198
    return value
199
200 2561 aaronmk
def unwrap_func_call(func_call, check_name=None):
201
    '''Unwraps any function call to its first argument.
202
    Also removes any column renaming.
203
    '''
204
    func_call = remove_col_rename(func_call)
205
    if not isinstance(func_call, FunctionCall): return func_call
206
207
    if check_name != None:
208
        name = func_call.function.name
209
        assert name == None or name == check_name
210
    return func_call.args[0]
211
212 2335 aaronmk
##### Conditions
213 2259 aaronmk
214 2398 aaronmk
class ColValueCond(Code):
215
    def __init__(self, col, value):
216
        value = as_ValueCond(value)
217
218
        self.col = col
219
        self.value = value
220
221
    def to_str(self, db): return self.value.to_str(db, self.col)
222
223 2577 aaronmk
def combine_conds(conds, keyword=None):
224
    '''
225
    @param keyword The keyword to add before the conditions, if any
226
    '''
227
    str_ = ''
228
    if keyword != None:
229
        if conds == []: whitespace = ''
230
        elif len(conds) == 1: whitespace = ' '
231
        else: whitespace = '\n'
232
        str_ += keyword+whitespace
233
234
    str_ += '\nAND '.join(conds)
235
    return str_
236
237 2398 aaronmk
##### Condition column comparisons
238
239 2514 aaronmk
class ValueCond(BasicObject):
240 2213 aaronmk
    def __init__(self, value):
241 2225 aaronmk
        if not isinstance(value, Code): value = Literal(value)
242 2462 aaronmk
        value = remove_col_rename(value)
243 2213 aaronmk
244
        self.value = value
245 2214 aaronmk
246 2216 aaronmk
    def to_str(self, db, left_value):
247 2214 aaronmk
        '''
248 2216 aaronmk
        @param left_value The Code object that the condition is being applied on
249 2214 aaronmk
        '''
250
        raise NotImplemented()
251 2228 aaronmk
252 2514 aaronmk
    def __repr__(self): return self.to_str(mockDb, '<left_value>')
253 2211 aaronmk
254
class CompareCond(ValueCond):
255
    def __init__(self, value, operator='='):
256 2222 aaronmk
        '''
257
        @param operator By default, compares NULL values literally. Use '~=' or
258
            '~!=' to pass NULLs through.
259
        '''
260 2211 aaronmk
        ValueCond.__init__(self, value)
261
        self.operator = operator
262
263 2216 aaronmk
    def to_str(self, db, left_value):
264
        if not isinstance(left_value, Code): left_value = Col(left_value)
265 2462 aaronmk
        left_value = remove_col_rename(left_value)
266 2216 aaronmk
267 2222 aaronmk
        right_value = self.value
268
        left = left_value.to_str(db)
269
        right = right_value.to_str(db)
270
271
        # Parse operator
272 2216 aaronmk
        operator = self.operator
273 2222 aaronmk
        passthru_null_ref = [False]
274
        operator = strings.remove_prefix('~', operator, passthru_null_ref)
275
        neg_ref = [False]
276
        operator = strings.remove_prefix('!', operator, neg_ref)
277
        equals = operator.endswith('=')
278
        if equals and is_null(self.value): operator = 'IS'
279
280
        # Create str
281
        str_ = left+' '+operator+' '+right
282
        if equals and not passthru_null_ref[0] and isinstance(right_value, Col):
283 2578 aaronmk
            str_ = '('+str_+' OR ('+left+' IS NULL AND '+right+' IS NULL))'
284
        if neg_ref[0]: str_ = 'NOT '+str_
285 2222 aaronmk
        return str_
286 2216 aaronmk
287 2260 aaronmk
# Tells as_ValueCond() to assume a non-ValueCond is a literal value
288
assume_literal = object()
289
290
def as_ValueCond(value, default_table=assume_literal):
291
    if not isinstance(value, ValueCond):
292
        if default_table is not assume_literal:
293
            value = as_Col(value, default_table)
294
        return CompareCond(value)
295 2216 aaronmk
    else: return value
296 2219 aaronmk
297 2335 aaronmk
##### Joins
298
299 2352 aaronmk
join_same = object() # tells Join the left and right columns have the same name
300 2260 aaronmk
301 2353 aaronmk
# Tells Join the left and right columns have the same name and are never NULL
302
join_same_not_null = object()
303
304 2260 aaronmk
filter_out = object() # tells Join to filter out rows that match the join
305
306 2514 aaronmk
class Join(BasicObject):
307 2260 aaronmk
    def __init__(self, table, mapping, type_=None):
308
        '''
309
        @param mapping dict(right_table_col=left_table_col, ...)
310 2352 aaronmk
            * if left_table_col is join_same: left_table_col = right_table_col
311 2353 aaronmk
              * Note that right_table_col must be a string
312
            * if left_table_col is join_same_not_null:
313
              left_table_col = right_table_col and both have NOT NULL constraint
314
              * Note that right_table_col must be a string
315 2260 aaronmk
        @param type_ None (for plain join)|str (e.g. 'LEFT')|filter_out
316
            * filter_out: equivalent to 'LEFT' with the query filtered by
317
              `table_pkey IS NULL` (indicating no match)
318
        '''
319
        if util.is_str(table): table = Table(table)
320
        assert type_ == None or util.is_str(type_) or type_ is filter_out
321
322
        self.table = table
323
        self.mapping = mapping
324
        self.type_ = type_
325
326
    def to_str(self, db, left_table):
327 2353 aaronmk
        # Switch order (left_table is on the right in the comparison)
328
        right_table = left_table
329
        left_table = self.table # note left_table is reassigned
330
331 2260 aaronmk
        def join(entry):
332
            '''Parses non-USING joins'''
333
            right_table_col, left_table_col = entry
334
335 2353 aaronmk
            # Switch order (right_table_col is on the left in the comparison)
336
            left = right_table_col
337
            right = left_table_col
338
339 2260 aaronmk
            # Parse special values
340 2353 aaronmk
            if right is join_same: right = left
341
            elif right is join_same_not_null:
342
                right = CompareCond(as_Col(left, right_table), '~=')
343 2260 aaronmk
344 2353 aaronmk
            right = as_ValueCond(right, right_table)
345 2578 aaronmk
            return right.to_str(db, as_Col(left, left_table))
346 2260 aaronmk
347 2265 aaronmk
        # Create join condition
348
        type_ = self.type_
349 2276 aaronmk
        joins = self.mapping
350 2265 aaronmk
        if type_ is not filter_out and reduce(operator.and_,
351 2460 aaronmk
            (v is join_same_not_null for v in joins.itervalues())):
352 2260 aaronmk
            # all cols w/ USING, so can use simpler USING syntax
353 2298 aaronmk
            cols = (as_Col(v).to_str(db) for v in joins.iterkeys())
354
            join_cond = 'USING ('+(', '.join(cols))+')'
355 2576 aaronmk
        else:
356
            if len(joins) == 1: whitespace = ' '
357
            else: whitespace = '\n'
358 2577 aaronmk
            join_cond = combine_conds(map(join, joins.iteritems()), 'ON')
359 2260 aaronmk
360
        # Create join
361
        if type_ is filter_out: type_ = 'LEFT'
362 2266 aaronmk
        str_ = ''
363
        if type_ != None: str_ += type_+' '
364 2353 aaronmk
        str_ += 'JOIN '+left_table.to_str(db)+' '+join_cond
365 2266 aaronmk
        return str_
366 2349 aaronmk
367 2514 aaronmk
    def __repr__(self): return self.to_str(mockDb, '<left_table>')
368 2424 aaronmk
369
##### Value exprs
370
371
row_count = CustomCode('count(*)')