Project

General

Profile

1
# SQL code generation
2

    
3
import operator
4
import re
5
import UserDict
6

    
7
import objects
8
import strings
9
import util
10

    
11
##### Names
12

    
13
identifier_max_len = 63 # works for both PostgreSQL and MySQL
14

    
15
def add_suffix(str_, suffix):
16
    '''Preserves version so that it won't be truncated off the string, leading
17
    to collisions.'''
18
    # Preserve version
19
    before, sep, version = str_.rpartition('#')
20
    if sep != '': # found match
21
        str_ = before
22
        suffix = sep+version+suffix
23
    
24
    return strings.add_suffix(str_, suffix, identifier_max_len)
25

    
26
def is_safe_name(name):
27
    '''A name is safe *and unambiguous* if it:
28
    * contains only *lowercase* word (\w) characters
29
    * doesn't start with a digit
30
    * contains "_", so that it's not a keyword
31
    ''' 
32
    return re.match(r'^(?=.*_)(?!\d)[^\WA-Z]+$', name) 
33

    
34
def esc_name(name, quote='"'):
35
    return quote + name.replace(quote, quote+quote) + quote
36
        # doubling an embedded quote escapes it in both PostgreSQL and MySQL
37

    
38
def clean_name(name): return name.replace('"', '').replace('`', '')
39

    
40
##### SQL code objects
41

    
42
class MockDb:
43
    def esc_value(self, value): return strings.repr_no_u(value)
44
    
45
    def esc_name(self, name): return esc_name(name)
46
mockDb = MockDb()
47

    
48
class BasicObject(objects.BasicObject):
49
    def __init__(self, value): self.value = value
50
    
51
    def __str__(self): return clean_name(strings.repr_no_u(self))
52

    
53
class Code(BasicObject):
54
    def to_str(self, db): raise NotImplemented()
55
    
56
    def __repr__(self): return self.to_str(mockDb)
57

    
58
class CustomCode(Code):
59
    def __init__(self, str_): self.str_ = str_
60
    
61
    def to_str(self, db): return self.str_
62

    
63
class Expr(Code):
64
    def __init__(self, expr): self.expr = expr
65
    
66
    def to_str(self, db): return '('+self.expr.to_str(db)+')'
67

    
68
##### Literal values
69

    
70
class Literal(Code):
71
    def __init__(self, value): self.value = value
72
    
73
    def to_str(self, db): return db.esc_value(self.value)
74

    
75
def as_Value(value):
76
    if isinstance(value, Code): return value
77
    else: return Literal(value)
78

    
79
def is_null(value): return isinstance(value, Literal) and value.value == None
80

    
81
##### Tables
82

    
83
class Table(Code):
84
    def __init__(self, name, schema=None):
85
        '''
86
        @param schema str|None (for no schema)
87
        '''
88
        self.name = name
89
        self.schema = schema
90
    
91
    def to_str(self, db):
92
        str_ = ''
93
        if self.schema != None: str_ += db.esc_name(self.schema)+'.'
94
        str_ += db.esc_name(self.name)
95
        return str_
96
    
97
    def to_Table(self): return self
98

    
99
def as_Table(table):
100
    if table == None or isinstance(table, Code): return table
101
    else: return Table(table)
102

    
103
class NamedTable(Table):
104
    def __init__(self, name, code, cols=None):
105
        Table.__init__(self, name)
106
        
107
        if not isinstance(code, Code): code = Table(code)
108
        
109
        self.code = code
110
        self.cols = cols
111
    
112
    def to_str(self, db):
113
        str_ = self.code.to_str(db)+'\nAS '+Table.to_str(self, db)
114
        if self.cols != None: str_ += ' ('+(', '.join(self.cols))+')'
115
        return str_
116
    
117
    def to_Table(self): return Table(self.name)
118

    
119
##### Columns
120

    
121
class Col(Code):
122
    def __init__(self, name, table=None):
123
        '''
124
        @param table Table|None (for no table)
125
        '''
126
        if util.is_str(table): table = Table(table)
127
        assert table == None or isinstance(table, Table)
128
        
129
        self.name = name
130
        self.table = table
131
    
132
    def to_str(self, db):
133
        str_ = ''
134
        if self.table != None: str_ += self.table.to_str(db)+'.'
135
        str_ += db.esc_name(self.name)
136
        return str_
137
    
138
    def to_Col(self): return self
139

    
140
def is_table_col(col): return col.table != None
141

    
142
def as_Col(col, table=None, name=None):
143
    '''
144
    @param name If not None, any non-Col input will be renamed using NamedCol.
145
    '''
146
    if name != None:
147
        col = as_Value(col)
148
        if not isinstance(col, Col): col = NamedCol(name, col)
149
    
150
    if isinstance(col, Code): return col
151
    else: return Col(col, table)
152

    
153
def to_name_only_col(col, check_table=None):
154
    col = as_Col(col)
155
    if not isinstance(col, Col): return col
156
    
157
    if check_table != None:
158
        table = col.table
159
        assert table == None or table == check_table
160
    return Col(col.name)
161

    
162
class NamedCol(Col):
163
    def __init__(self, name, code):
164
        Col.__init__(self, name)
165
        
166
        if not isinstance(code, Code): code = Literal(code)
167
        
168
        self.code = code
169
    
170
    def to_str(self, db):
171
        return self.code.to_str(db)+' AS '+Col.to_str(self, db)
172
    
173
    def to_Col(self): return Col(self.name)
174

    
175
def remove_col_rename(col):
176
    if isinstance(col, NamedCol): col = col.code
177
    return col
178

    
179
class ColDict(UserDict.DictMixin):
180
    '''A dict that automatically makes inserted entries Col objects'''
181
    
182
    def __init__(self, db, keys_table, dict_={}):
183
        keys_table = as_Table(keys_table)
184
        
185
        self.db = db
186
        self.table = keys_table
187
        self.dict = {}
188
        self.update(dict_) # after setting vars because __setitem__() needs them
189
    
190
    def keys(self): return self.dict.keys()
191
    
192
    def __getitem__(self, key):
193
        return self.dict[self._key(key)]
194
    
195
    def __setitem__(self, key, value):
196
        key = self._key(key)
197
        self.dict[key] = as_Col(value, name=key.name)
198
    
199
    def _key(self, key): return as_Col(key, self.table)
200

    
201
##### Functions
202

    
203
class Function(Table): pass
204

    
205
class FunctionCall(Code):
206
    def __init__(self, function, *args):
207
        '''
208
        @param args [Code...] The function's arguments
209
        '''
210
        if not isinstance(function, Code): function = Function(function)
211
        args = map(remove_col_rename, args)
212
        
213
        self.function = function
214
        self.args = args
215
    
216
    def to_str(self, db):
217
        args_str = ', '.join((v.to_str(db) for v in self.args))
218
        return self.function.to_str(db)+'('+args_str+')'
219

    
220
def wrap_in_func(function, value):
221
    '''Wraps a value inside a function call.
222
    Propagates any column renaming to the returned value.
223
    '''
224
    name = None
225
    if isinstance(value, NamedCol): name = value.name
226
    value = FunctionCall(function, value)
227
    if name != None: value = NamedCol(name, value)
228
    return value
229

    
230
def unwrap_func_call(func_call, check_name=None):
231
    '''Unwraps any function call to its first argument.
232
    Also removes any column renaming.
233
    '''
234
    func_call = remove_col_rename(func_call)
235
    if not isinstance(func_call, FunctionCall): return func_call
236
    
237
    if check_name != None:
238
        name = func_call.function.name
239
        assert name == None or name == check_name
240
    return func_call.args[0]
241

    
242
##### Conditions
243

    
244
class ColValueCond(Code):
245
    def __init__(self, col, value):
246
        value = as_ValueCond(value)
247
        
248
        self.col = col
249
        self.value = value
250
    
251
    def to_str(self, db): return self.value.to_str(db, self.col)
252

    
253
def combine_conds(conds, keyword=None):
254
    '''
255
    @param keyword The keyword to add before the conditions, if any
256
    '''
257
    str_ = ''
258
    if keyword != None:
259
        if conds == []: whitespace = ''
260
        elif len(conds) == 1: whitespace = ' '
261
        else: whitespace = '\n'
262
        str_ += keyword+whitespace
263
    
264
    str_ += '\nAND '.join(conds)
265
    return str_
266

    
267
##### Condition column comparisons
268

    
269
class ValueCond(BasicObject):
270
    def __init__(self, value):
271
        if not isinstance(value, Code): value = Literal(value)
272
        value = remove_col_rename(value)
273
        
274
        self.value = value
275
    
276
    def to_str(self, db, left_value):
277
        '''
278
        @param left_value The Code object that the condition is being applied on
279
        '''
280
        raise NotImplemented()
281
    
282
    def __repr__(self): return self.to_str(mockDb, '<left_value>')
283

    
284
class CompareCond(ValueCond):
285
    def __init__(self, value, operator='='):
286
        '''
287
        @param operator By default, compares NULL values literally. Use '~=' or
288
            '~!=' to pass NULLs through.
289
        '''
290
        ValueCond.__init__(self, value)
291
        self.operator = operator
292
    
293
    def to_str(self, db, left_value):
294
        if not isinstance(left_value, Code): left_value = Col(left_value)
295
        left_value = remove_col_rename(left_value)
296
        
297
        right_value = self.value
298
        left = left_value.to_str(db)
299
        right = right_value.to_str(db)
300
        
301
        # Parse operator
302
        operator = self.operator
303
        passthru_null_ref = [False]
304
        operator = strings.remove_prefix('~', operator, passthru_null_ref)
305
        neg_ref = [False]
306
        operator = strings.remove_prefix('!', operator, neg_ref)
307
        equals = operator.endswith('=')
308
        if equals and is_null(self.value): operator = 'IS'
309
        
310
        # Create str
311
        str_ = left+' '+operator+' '+right
312
        if equals and not passthru_null_ref[0] and isinstance(right_value, Col):
313
            str_ = '('+str_+' OR ('+left+' IS NULL AND '+right+' IS NULL))'
314
        if neg_ref[0]: str_ = 'NOT '+str_
315
        return str_
316

    
317
# Tells as_ValueCond() to assume a non-ValueCond is a literal value
318
assume_literal = object()
319

    
320
def as_ValueCond(value, default_table=assume_literal):
321
    if not isinstance(value, ValueCond):
322
        if default_table is not assume_literal:
323
            value = as_Col(value, default_table)
324
        return CompareCond(value)
325
    else: return value
326

    
327
##### Joins
328

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

    
331
# Tells Join the left and right columns have the same name and are never NULL
332
join_same_not_null = object()
333

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

    
336
class Join(BasicObject):
337
    def __init__(self, table, mapping, type_=None):
338
        '''
339
        @param mapping dict(right_table_col=left_table_col, ...)
340
            * if left_table_col is join_same: left_table_col = right_table_col
341
              * Note that right_table_col must be a string
342
            * if left_table_col is join_same_not_null:
343
              left_table_col = right_table_col and both have NOT NULL constraint
344
              * Note that right_table_col must be a string
345
        @param type_ None (for plain join)|str (e.g. 'LEFT')|filter_out
346
            * filter_out: equivalent to 'LEFT' with the query filtered by
347
              `table_pkey IS NULL` (indicating no match)
348
        '''
349
        if util.is_str(table): table = Table(table)
350
        assert type_ == None or util.is_str(type_) or type_ is filter_out
351
        
352
        self.table = table
353
        self.mapping = mapping
354
        self.type_ = type_
355
    
356
    def to_str(self, db, left_table):
357
        # Switch order (left_table is on the right in the comparison)
358
        right_table = left_table
359
        left_table = self.table # note left_table is reassigned
360
        
361
        def join(entry):
362
            '''Parses non-USING joins'''
363
            right_table_col, left_table_col = entry
364
            
365
            # Switch order (right_table_col is on the left in the comparison)
366
            left = right_table_col
367
            right = left_table_col
368
            
369
            # Parse special values
370
            if right is join_same: right = left
371
            elif right is join_same_not_null:
372
                right = CompareCond(as_Col(left, right_table), '~=')
373
            
374
            right = as_ValueCond(right, right_table)
375
            return right.to_str(db, as_Col(left, left_table))
376
        
377
        # Create join condition
378
        type_ = self.type_
379
        joins = self.mapping
380
        if type_ is not filter_out and reduce(operator.and_,
381
            (v is join_same_not_null for v in joins.itervalues())):
382
            # all cols w/ USING, so can use simpler USING syntax
383
            cols = (as_Col(v).to_str(db) for v in joins.iterkeys())
384
            join_cond = 'USING ('+(', '.join(cols))+')'
385
        else:
386
            if len(joins) == 1: whitespace = ' '
387
            else: whitespace = '\n'
388
            join_cond = combine_conds(map(join, joins.iteritems()), 'ON')
389
        
390
        # Create join
391
        if type_ is filter_out: type_ = 'LEFT'
392
        str_ = ''
393
        if type_ != None: str_ += type_+' '
394
        str_ += 'JOIN '+left_table.to_str(db)+' '+join_cond
395
        return str_
396
    
397
    def __repr__(self): return self.to_str(mockDb, '<left_table>')
398

    
399
##### Value exprs
400

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