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:
14
    * contains only *lowercase* word (\w) characters
15
    * doesn't start with a digit
16
    * contains "_", so that it's not a keyword
17
    ''' 
18
    return re.match(r'^(?=.*_)(?!\d)[^\WA-Z]+$', name) 
19

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

    
25
def clean_name(name): return name.replace('"', '').replace('`', '')
26

    
27
##### SQL code objects
28

    
29
class MockDb:
30
    def esc_value(self, value): return strings.repr_no_u(value)
31
    
32
    def esc_name(self, name): return esc_name(name)
33
mockDb = MockDb()
34

    
35
class BasicObject(objects.BasicObject):
36
    def __init__(self, value): self.value = value
37
    
38
    def __str__(self): return clean_name(strings.repr_no_u(self))
39

    
40
class Code(BasicObject):
41
    def to_str(self, db): raise NotImplemented()
42
    
43
    def __repr__(self): return self.to_str(mockDb)
44

    
45
class CustomCode(Code):
46
    def __init__(self, str_): self.str_ = str_
47
    
48
    def to_str(self, db): return self.str_
49

    
50
class Expr(Code):
51
    def __init__(self, expr): self.expr = expr
52
    
53
    def to_str(self, db): return '('+self.expr.to_str(db)+')'
54

    
55
##### Literal values
56

    
57
class Literal(Code):
58
    def __init__(self, value): self.value = value
59
    
60
    def to_str(self, db): return db.esc_value(self.value)
61

    
62
def as_Value(value):
63
    if isinstance(value, Code): return value
64
    else: return Literal(value)
65

    
66
def is_null(value): return isinstance(value, Literal) and value.value == None
67

    
68
##### Tables
69

    
70
class Table(Code):
71
    def __init__(self, name, schema=None):
72
        '''
73
        @param schema str|None (for no schema)
74
        '''
75
        self.name = name
76
        self.schema = schema
77
    
78
    def to_str(self, db):
79
        str_ = ''
80
        if self.schema != None: str_ += db.esc_name(self.schema)+'.'
81
        str_ += db.esc_name(self.name)
82
        return str_
83
    
84
    def to_Table(self): return self
85

    
86
def as_Table(table):
87
    if table == None or isinstance(table, Code): return table
88
    else: return Table(table)
89

    
90
class NamedTable(Table):
91
    def __init__(self, name, code, cols=None):
92
        Table.__init__(self, name)
93
        
94
        if not isinstance(code, Code): code = Table(code)
95
        
96
        self.code = code
97
        self.cols = cols
98
    
99
    def to_str(self, db):
100
        str_ = self.code.to_str(db)+'\nAS '+Table.to_str(self, db)
101
        if self.cols != None: str_ += ' ('+(', '.join(self.cols))+')'
102
        return str_
103
    
104
    def to_Table(self): return Table(self.name)
105

    
106
##### Columns
107

    
108
class Col(Code):
109
    def __init__(self, name, table=None):
110
        '''
111
        @param table Table|None (for no table)
112
        '''
113
        if util.is_str(table): table = Table(table)
114
        assert table == None or isinstance(table, Table)
115
        
116
        self.name = name
117
        self.table = table
118
    
119
    def to_str(self, db):
120
        str_ = ''
121
        if self.table != None: str_ += self.table.to_str(db)+'.'
122
        str_ += db.esc_name(self.name)
123
        return str_
124
    
125
    def to_Col(self): return self
126

    
127
def is_table_col(col): return col.table != None
128

    
129
def as_Col(col, table=None, name=None):
130
    '''
131
    @param name If not None, any non-Col input will be renamed using NamedCol.
132
    '''
133
    if name != None:
134
        col = as_Value(col)
135
        if not isinstance(col, Col): col = NamedCol(name, col)
136
    
137
    if isinstance(col, Code): return col
138
    else: return Col(col, table)
139

    
140
def to_name_only_col(col, check_table=None):
141
    col = as_Col(col)
142
    if not isinstance(col, Col): return col
143
    
144
    if check_table != None:
145
        table = col.table
146
        assert table == None or table == check_table
147
    return Col(col.name)
148

    
149
class NamedCol(Col):
150
    def __init__(self, name, code):
151
        Col.__init__(self, name)
152
        
153
        if not isinstance(code, Code): code = Literal(code)
154
        
155
        self.code = code
156
    
157
    def to_str(self, db):
158
        return self.code.to_str(db)+' AS '+Col.to_str(self, db)
159
    
160
    def to_Col(self): return Col(self.name)
161

    
162
def remove_col_rename(col):
163
    if isinstance(col, NamedCol): col = col.code
164
    return col
165

    
166
class ColDict(dict):
167
    '''A dict that automatically makes inserted entries Col objects'''
168
    
169
    def __setitem__(self, key, value):
170
        return dict.__setitem__(self, key, as_Col(value, name=key))
171
    
172
    def update(self, dict_):
173
        for key, value in dict_.iteritems(): self[key] = value
174

    
175
##### Functions
176

    
177
class Function(Table): pass
178

    
179
class FunctionCall(Code):
180
    def __init__(self, function, *args):
181
        '''
182
        @param args [Code...] The function's arguments
183
        '''
184
        if not isinstance(function, Code): function = Function(function)
185
        args = map(remove_col_rename, args)
186
        
187
        self.function = function
188
        self.args = args
189
    
190
    def to_str(self, db):
191
        args_str = ', '.join((v.to_str(db) for v in self.args))
192
        return self.function.to_str(db)+'('+args_str+')'
193

    
194
def wrap_in_func(function, value):
195
    '''Wraps a value inside a function call.
196
    Propagates any column renaming to the returned value.
197
    '''
198
    name = None
199
    if isinstance(value, NamedCol): name = value.name
200
    value = FunctionCall(function, value)
201
    if name != None: value = NamedCol(name, value)
202
    return value
203

    
204
def unwrap_func_call(func_call, check_name=None):
205
    '''Unwraps any function call to its first argument.
206
    Also removes any column renaming.
207
    '''
208
    func_call = remove_col_rename(func_call)
209
    if not isinstance(func_call, FunctionCall): return func_call
210
    
211
    if check_name != None:
212
        name = func_call.function.name
213
        assert name == None or name == check_name
214
    return func_call.args[0]
215

    
216
##### Conditions
217

    
218
class ColValueCond(Code):
219
    def __init__(self, col, value):
220
        value = as_ValueCond(value)
221
        
222
        self.col = col
223
        self.value = value
224
    
225
    def to_str(self, db): return self.value.to_str(db, self.col)
226

    
227
def combine_conds(conds, keyword=None):
228
    '''
229
    @param keyword The keyword to add before the conditions, if any
230
    '''
231
    str_ = ''
232
    if keyword != None:
233
        if conds == []: whitespace = ''
234
        elif len(conds) == 1: whitespace = ' '
235
        else: whitespace = '\n'
236
        str_ += keyword+whitespace
237
    
238
    str_ += '\nAND '.join(conds)
239
    return str_
240

    
241
##### Condition column comparisons
242

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

    
258
class CompareCond(ValueCond):
259
    def __init__(self, value, operator='='):
260
        '''
261
        @param operator By default, compares NULL values literally. Use '~=' or
262
            '~!=' to pass NULLs through.
263
        '''
264
        ValueCond.__init__(self, value)
265
        self.operator = operator
266
    
267
    def to_str(self, db, left_value):
268
        if not isinstance(left_value, Code): left_value = Col(left_value)
269
        left_value = remove_col_rename(left_value)
270
        
271
        right_value = self.value
272
        left = left_value.to_str(db)
273
        right = right_value.to_str(db)
274
        
275
        # Parse operator
276
        operator = self.operator
277
        passthru_null_ref = [False]
278
        operator = strings.remove_prefix('~', operator, passthru_null_ref)
279
        neg_ref = [False]
280
        operator = strings.remove_prefix('!', operator, neg_ref)
281
        equals = operator.endswith('=')
282
        if equals and is_null(self.value): operator = 'IS'
283
        
284
        # Create str
285
        str_ = left+' '+operator+' '+right
286
        if equals and not passthru_null_ref[0] and isinstance(right_value, Col):
287
            str_ = '('+str_+' OR ('+left+' IS NULL AND '+right+' IS NULL))'
288
        if neg_ref[0]: str_ = 'NOT '+str_
289
        return str_
290

    
291
# Tells as_ValueCond() to assume a non-ValueCond is a literal value
292
assume_literal = object()
293

    
294
def as_ValueCond(value, default_table=assume_literal):
295
    if not isinstance(value, ValueCond):
296
        if default_table is not assume_literal:
297
            value = as_Col(value, default_table)
298
        return CompareCond(value)
299
    else: return value
300

    
301
##### Joins
302

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

    
305
# Tells Join the left and right columns have the same name and are never NULL
306
join_same_not_null = object()
307

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

    
310
class Join(BasicObject):
311
    def __init__(self, table, mapping, type_=None):
312
        '''
313
        @param mapping dict(right_table_col=left_table_col, ...)
314
            * if left_table_col is join_same: left_table_col = right_table_col
315
              * Note that right_table_col must be a string
316
            * if left_table_col is join_same_not_null:
317
              left_table_col = right_table_col and both have NOT NULL constraint
318
              * Note that right_table_col must be a string
319
        @param type_ None (for plain join)|str (e.g. 'LEFT')|filter_out
320
            * filter_out: equivalent to 'LEFT' with the query filtered by
321
              `table_pkey IS NULL` (indicating no match)
322
        '''
323
        if util.is_str(table): table = Table(table)
324
        assert type_ == None or util.is_str(type_) or type_ is filter_out
325
        
326
        self.table = table
327
        self.mapping = mapping
328
        self.type_ = type_
329
    
330
    def to_str(self, db, left_table):
331
        # Switch order (left_table is on the right in the comparison)
332
        right_table = left_table
333
        left_table = self.table # note left_table is reassigned
334
        
335
        def join(entry):
336
            '''Parses non-USING joins'''
337
            right_table_col, left_table_col = entry
338
            
339
            # Switch order (right_table_col is on the left in the comparison)
340
            left = right_table_col
341
            right = left_table_col
342
            
343
            # Parse special values
344
            if right is join_same: right = left
345
            elif right is join_same_not_null:
346
                right = CompareCond(as_Col(left, right_table), '~=')
347
            
348
            right = as_ValueCond(right, right_table)
349
            return right.to_str(db, as_Col(left, left_table))
350
        
351
        # Create join condition
352
        type_ = self.type_
353
        joins = self.mapping
354
        if type_ is not filter_out and reduce(operator.and_,
355
            (v is join_same_not_null for v in joins.itervalues())):
356
            # all cols w/ USING, so can use simpler USING syntax
357
            cols = (as_Col(v).to_str(db) for v in joins.iterkeys())
358
            join_cond = 'USING ('+(', '.join(cols))+')'
359
        else:
360
            if len(joins) == 1: whitespace = ' '
361
            else: whitespace = '\n'
362
            join_cond = combine_conds(map(join, joins.iteritems()), 'ON')
363
        
364
        # Create join
365
        if type_ is filter_out: type_ = 'LEFT'
366
        str_ = ''
367
        if type_ != None: str_ += type_+' '
368
        str_ += 'JOIN '+left_table.to_str(db)+' '+join_cond
369
        return str_
370
    
371
    def __repr__(self): return self.to_str(mockDb, '<left_table>')
372

    
373
##### Value exprs
374

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