Project

General

Profile

1
# SQL code generation
2

    
3
import operator
4
import re
5

    
6
import objects
7
import strings
8
import util
9

    
10
##### Escaping
11

    
12
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

    
17
def esc_name(name, quote='"'):
18
    if is_safe_name(name): return name
19
    return quote + name.replace(quote, quote+quote) + quote
20
        # doubling an embedded quote escapes it in both PostgreSQL and MySQL
21

    
22
def clean_name(name): return name.replace('"', '').replace('`', '')
23

    
24
##### SQL code objects
25

    
26
class MockDb:
27
    def esc_value(self, value): return strings.repr_no_u(value)
28
    
29
    def esc_name(self, name): return esc_name(name)
30
mockDb = MockDb()
31

    
32
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
    def to_str(self, db): raise NotImplemented()
39
    
40
    def __repr__(self): return self.to_str(mockDb)
41

    
42
class CustomCode(Code):
43
    def __init__(self, str_): self.str_ = str_
44
    
45
    def to_str(self, db): return self.str_
46

    
47
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
##### Literal values
53

    
54
class Literal(Code):
55
    def __init__(self, value): self.value = value
56
    
57
    def to_str(self, db): return db.esc_value(self.value)
58

    
59
def as_Value(value):
60
    if isinstance(value, Code): return value
61
    else: return Literal(value)
62

    
63
def is_null(value): return isinstance(value, Literal) and value.value == None
64

    
65
##### Tables
66

    
67
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
    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
    
81
    def to_Table(self): return self
82

    
83
def as_Table(table):
84
    if table == None or isinstance(table, Code): return table
85
    else: return Table(table)
86

    
87
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
        str_ = self.code.to_str(db)+'\nAS '+Table.to_str(self, db)
98
        if self.cols != None: str_ += ' ('+(', '.join(self.cols))+')'
99
        return str_
100
    
101
    def to_Table(self): return Table(self.name)
102

    
103
##### Columns
104

    
105
class Col(Code):
106
    def __init__(self, name, table=None):
107
        '''
108
        @param table Table|None (for no table)
109
        '''
110
        if util.is_str(table): table = Table(table)
111
        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
        str_ += db.esc_name(self.name)
120
        return str_
121
    
122
    def to_Col(self): return self
123

    
124
def is_table_col(col): return col.table != None
125

    
126
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
    
134
    if isinstance(col, Code): return col
135
    else: return Col(col, table)
136

    
137
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
class NamedCol(Col):
146
    def __init__(self, name, code):
147
        Col.__init__(self, name)
148
        
149
        if not isinstance(code, Code): code = Literal(code)
150
        
151
        self.code = code
152
    
153
    def to_str(self, db):
154
        return self.code.to_str(db)+' AS '+Col.to_str(self, db)
155
    
156
    def to_Col(self): return Col(self.name)
157

    
158
def remove_col_rename(col):
159
    if isinstance(col, NamedCol): col = col.code
160
    return col
161

    
162
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
##### 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
        args = map(remove_col_rename, args)
182
        
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
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
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
##### Conditions
213

    
214
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
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
##### Condition column comparisons
238

    
239
class ValueCond(BasicObject):
240
    def __init__(self, value):
241
        if not isinstance(value, Code): value = Literal(value)
242
        value = remove_col_rename(value)
243
        
244
        self.value = value
245
    
246
    def to_str(self, db, left_value):
247
        '''
248
        @param left_value The Code object that the condition is being applied on
249
        '''
250
        raise NotImplemented()
251
    
252
    def __repr__(self): return self.to_str(mockDb, '<left_value>')
253

    
254
class CompareCond(ValueCond):
255
    def __init__(self, value, operator='='):
256
        '''
257
        @param operator By default, compares NULL values literally. Use '~=' or
258
            '~!=' to pass NULLs through.
259
        '''
260
        ValueCond.__init__(self, value)
261
        self.operator = operator
262
    
263
    def to_str(self, db, left_value):
264
        if not isinstance(left_value, Code): left_value = Col(left_value)
265
        left_value = remove_col_rename(left_value)
266
        
267
        right_value = self.value
268
        left = left_value.to_str(db)
269
        right = right_value.to_str(db)
270
        
271
        # Parse operator
272
        operator = self.operator
273
        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
            str_ = '('+str_+' OR ('+left+' IS NULL AND '+right+' IS NULL))'
284
        if neg_ref[0]: str_ = 'NOT '+str_
285
        return str_
286

    
287
# 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
    else: return value
296

    
297
##### Joins
298

    
299
join_same = object() # tells Join the left and right columns have the same name
300

    
301
# Tells Join the left and right columns have the same name and are never NULL
302
join_same_not_null = object()
303

    
304
filter_out = object() # tells Join to filter out rows that match the join
305

    
306
class Join(BasicObject):
307
    def __init__(self, table, mapping, type_=None):
308
        '''
309
        @param mapping dict(right_table_col=left_table_col, ...)
310
            * if left_table_col is join_same: left_table_col = right_table_col
311
              * 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
        @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
        # 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
        def join(entry):
332
            '''Parses non-USING joins'''
333
            right_table_col, left_table_col = entry
334
            
335
            # Switch order (right_table_col is on the left in the comparison)
336
            left = right_table_col
337
            right = left_table_col
338
            
339
            # Parse special values
340
            if right is join_same: right = left
341
            elif right is join_same_not_null:
342
                right = CompareCond(as_Col(left, right_table), '~=')
343
            
344
            right = as_ValueCond(right, right_table)
345
            return right.to_str(db, as_Col(left, left_table))
346
        
347
        # Create join condition
348
        type_ = self.type_
349
        joins = self.mapping
350
        if type_ is not filter_out and reduce(operator.and_,
351
            (v is join_same_not_null for v in joins.itervalues())):
352
            # all cols w/ USING, so can use simpler USING syntax
353
            cols = (as_Col(v).to_str(db) for v in joins.iterkeys())
354
            join_cond = 'USING ('+(', '.join(cols))+')'
355
        else:
356
            if len(joins) == 1: whitespace = ' '
357
            else: whitespace = '\n'
358
            join_cond = combine_conds(map(join, joins.iteritems()), 'ON')
359
        
360
        # Create join
361
        if type_ is filter_out: type_ = 'LEFT'
362
        str_ = ''
363
        if type_ != None: str_ += type_+' '
364
        str_ += 'JOIN '+left_table.to_str(db)+' '+join_cond
365
        return str_
366
    
367
    def __repr__(self): return self.to_str(mockDb, '<left_table>')
368

    
369
##### Value exprs
370

    
371
row_count = CustomCode('count(*)')
(25-25/36)