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
    return quote + name.replace(quote, quote+quote) + quote
27
        # doubling an embedded quote escapes it in both PostgreSQL and MySQL
28

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

    
31
##### SQL code objects
32

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

    
39
class BasicObject(objects.BasicObject):
40
    def __init__(self, value): self.value = value
41
    
42
    def __str__(self): return clean_name(strings.repr_no_u(self))
43

    
44
class Code(BasicObject):
45
    def to_str(self, db): raise NotImplemented()
46
    
47
    def __repr__(self): return self.to_str(mockDb)
48

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

    
54
class Expr(Code):
55
    def __init__(self, expr): self.expr = expr
56
    
57
    def to_str(self, db): return '('+self.expr.to_str(db)+')'
58

    
59
##### Literal values
60

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

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

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

    
72
##### Tables
73

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

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

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

    
110
##### Columns
111

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

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

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

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

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

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

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

    
179
##### Functions
180

    
181
class Function(Table): pass
182

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

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

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

    
220
##### Conditions
221

    
222
class ColValueCond(Code):
223
    def __init__(self, col, value):
224
        value = as_ValueCond(value)
225
        
226
        self.col = col
227
        self.value = value
228
    
229
    def to_str(self, db): return self.value.to_str(db, self.col)
230

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

    
245
##### Condition column comparisons
246

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

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

    
295
# Tells as_ValueCond() to assume a non-ValueCond is a literal value
296
assume_literal = object()
297

    
298
def as_ValueCond(value, default_table=assume_literal):
299
    if not isinstance(value, ValueCond):
300
        if default_table is not assume_literal:
301
            value = as_Col(value, default_table)
302
        return CompareCond(value)
303
    else: return value
304

    
305
##### Joins
306

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

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

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

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

    
377
##### Value exprs
378

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