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
##### Names
11

    
12
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
def is_safe_name(name):
18
    '''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

    
25
def esc_name(name, quote='"'):
26
    if is_safe_name(name): return name
27
    return quote + name.replace(quote, quote+quote) + quote
28
        # doubling an embedded quote escapes it in both PostgreSQL and MySQL
29

    
30
def clean_name(name): return name.replace('"', '').replace('`', '')
31

    
32
##### SQL code objects
33

    
34
class MockDb:
35
    def esc_value(self, value): return strings.repr_no_u(value)
36
    
37
    def esc_name(self, name): return esc_name(name)
38
mockDb = MockDb()
39

    
40
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
    def to_str(self, db): raise NotImplemented()
47
    
48
    def __repr__(self): return self.to_str(mockDb)
49

    
50
class CustomCode(Code):
51
    def __init__(self, str_): self.str_ = str_
52
    
53
    def to_str(self, db): return self.str_
54

    
55
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
##### Literal values
61

    
62
class Literal(Code):
63
    def __init__(self, value): self.value = value
64
    
65
    def to_str(self, db): return db.esc_value(self.value)
66

    
67
def as_Value(value):
68
    if isinstance(value, Code): return value
69
    else: return Literal(value)
70

    
71
def is_null(value): return isinstance(value, Literal) and value.value == None
72

    
73
##### Tables
74

    
75
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
    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
    
89
    def to_Table(self): return self
90

    
91
def as_Table(table):
92
    if table == None or isinstance(table, Code): return table
93
    else: return Table(table)
94

    
95
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
        str_ = self.code.to_str(db)+'\nAS '+Table.to_str(self, db)
106
        if self.cols != None: str_ += ' ('+(', '.join(self.cols))+')'
107
        return str_
108
    
109
    def to_Table(self): return Table(self.name)
110

    
111
##### Columns
112

    
113
class Col(Code):
114
    def __init__(self, name, table=None):
115
        '''
116
        @param table Table|None (for no table)
117
        '''
118
        if util.is_str(table): table = Table(table)
119
        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
        str_ += db.esc_name(self.name)
128
        return str_
129
    
130
    def to_Col(self): return self
131

    
132
def is_table_col(col): return col.table != None
133

    
134
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
    
142
    if isinstance(col, Code): return col
143
    else: return Col(col, table)
144

    
145
def to_name_only_col(col, check_table=None):
146
    col = as_Col(col)
147
    if not isinstance(col, Col): return col
148
    
149
    if check_table != None:
150
        table = col.table
151
        assert table == None or table == check_table
152
    return Col(col.name)
153

    
154
class NamedCol(Col):
155
    def __init__(self, name, code):
156
        Col.__init__(self, name)
157
        
158
        if not isinstance(code, Code): code = Literal(code)
159
        
160
        self.code = code
161
    
162
    def to_str(self, db):
163
        return self.code.to_str(db)+' AS '+Col.to_str(self, db)
164
    
165
    def to_Col(self): return Col(self.name)
166

    
167
def remove_col_rename(col):
168
    if isinstance(col, NamedCol): col = col.code
169
    return col
170

    
171
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
##### 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
        args = map(remove_col_rename, args)
191
        
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
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
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
##### Conditions
222

    
223
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
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
##### Condition column comparisons
247

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

    
263
class CompareCond(ValueCond):
264
    def __init__(self, value, operator='='):
265
        '''
266
        @param operator By default, compares NULL values literally. Use '~=' or
267
            '~!=' to pass NULLs through.
268
        '''
269
        ValueCond.__init__(self, value)
270
        self.operator = operator
271
    
272
    def to_str(self, db, left_value):
273
        if not isinstance(left_value, Code): left_value = Col(left_value)
274
        left_value = remove_col_rename(left_value)
275
        
276
        right_value = self.value
277
        left = left_value.to_str(db)
278
        right = right_value.to_str(db)
279
        
280
        # Parse operator
281
        operator = self.operator
282
        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
            str_ = '('+str_+' OR ('+left+' IS NULL AND '+right+' IS NULL))'
293
        if neg_ref[0]: str_ = 'NOT '+str_
294
        return str_
295

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

    
306
##### Joins
307

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

    
310
# Tells Join the left and right columns have the same name and are never NULL
311
join_same_not_null = object()
312

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

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

    
378
##### Value exprs
379

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