Project

General

Profile

1
# SQL code generation
2

    
3
import operator
4

    
5
import objects
6
import strings
7
import util
8

    
9
##### Escaping
10

    
11
def esc_name(name, quote='"'):
12
    return quote + name.replace(quote, quote+quote) + quote
13
        # doubling an embedded quote escapes it in both PostgreSQL and MySQL
14

    
15
def clean_name(name): return name.replace('"', '').replace('`', '')
16

    
17
##### SQL code objects
18

    
19
class MockDb:
20
    def esc_value(self, value): return strings.repr_no_u(value)
21
    
22
    def esc_name(self, name): return esc_name(name)
23
mockDb = MockDb()
24

    
25
class BasicObject(objects.BasicObject):
26
    def __init__(self, value): self.value = value
27
    
28
    def __str__(self): return clean_name(strings.repr_no_u(self))
29

    
30
class Code(BasicObject):
31
    def to_str(self, db): raise NotImplemented()
32
    
33
    def __repr__(self): return self.to_str(mockDb)
34

    
35
class CustomCode(Code):
36
    def __init__(self, str_): self.str_ = str_
37
    
38
    def to_str(self, db): return self.str_
39

    
40
class Expr(Code):
41
    def __init__(self, expr): self.expr = expr
42
    
43
    def to_str(self, db): return '('+self.expr.to_str(db)+')'
44

    
45
##### Literal values
46

    
47
class Literal(Code):
48
    def __init__(self, value): self.value = value
49
    
50
    def to_str(self, db): return db.esc_value(self.value)
51

    
52
def as_Value(value):
53
    if isinstance(value, Code): return value
54
    else: return Literal(value)
55

    
56
def is_null(value): return isinstance(value, Literal) and value.value == None
57

    
58
##### Tables
59

    
60
class Table(Code):
61
    def __init__(self, name, schema=None):
62
        '''
63
        @param schema str|None (for no schema)
64
        '''
65
        self.name = name
66
        self.schema = schema
67
    
68
    def to_str(self, db):
69
        str_ = ''
70
        if self.schema != None: str_ += db.esc_name(self.schema)+'.'
71
        str_ += db.esc_name(self.name)
72
        return str_
73
    
74
    def to_Table(self): return self
75

    
76
def as_Table(table):
77
    if table == None or isinstance(table, Code): return table
78
    else: return Table(table)
79

    
80
class NamedTable(Table):
81
    def __init__(self, name, code, cols=None):
82
        Table.__init__(self, name)
83
        
84
        if not isinstance(code, Code): code = Table(code)
85
        
86
        self.code = code
87
        self.cols = cols
88
    
89
    def to_str(self, db):
90
        str_ = self.code.to_str(db)+'\nAS '+Table.to_str(self, db)
91
        if self.cols != None: str_ += ' ('+(', '.join(self.cols))+')'
92
        return str_
93
    
94
    def to_Table(self): return Table(self.name)
95

    
96
##### Columns
97

    
98
class Col(Code):
99
    def __init__(self, name, table=None):
100
        '''
101
        @param table Table|None (for no table)
102
        '''
103
        if util.is_str(table): table = Table(table)
104
        assert table == None or isinstance(table, Table)
105
        
106
        self.name = name
107
        self.table = table
108
    
109
    def to_str(self, db):
110
        str_ = ''
111
        if self.table != None: str_ += self.table.to_str(db)+'.'
112
        str_ += db.esc_name(self.name)
113
        return str_
114
    
115
    def to_Col(self): return self
116

    
117
def is_table_col(col): return col.table != None
118

    
119
def as_Col(col, table=None):
120
    assert col != None
121
    
122
    if isinstance(col, Code): return col
123
    else: return Col(col, table)
124

    
125
def to_name_only_col(col, check_table=None):
126
    col = as_Col(col)
127
    
128
    if check_table != None:
129
        table = col.table
130
        assert table == None or table == check_table
131
    return Col(col.name)
132

    
133
class NamedCol(Col):
134
    def __init__(self, name, code):
135
        Col.__init__(self, name)
136
        
137
        if not isinstance(code, Code): code = Literal(code)
138
        
139
        self.code = code
140
    
141
    def to_str(self, db):
142
        return self.code.to_str(db)+' AS '+Col.to_str(self, db)
143
    
144
    def to_Col(self): return Col(self.name)
145

    
146
def remove_col_rename(col):
147
    if isinstance(col, NamedCol): col = col.code
148
    return col
149

    
150
##### Functions
151

    
152
class Function(Table): pass
153

    
154
class FunctionCall(Code):
155
    def __init__(self, function, *args):
156
        '''
157
        @param args [Code...] The function's arguments
158
        '''
159
        if not isinstance(function, Code): function = Function(function)
160
        args = map(remove_col_rename, args)
161
        
162
        self.function = function
163
        self.args = args
164
    
165
    def to_str(self, db):
166
        args_str = ', '.join((v.to_str(db) for v in self.args))
167
        return self.function.to_str(db)+'('+args_str+')'
168

    
169
def wrap_in_func(function, value):
170
    '''Wraps a value inside a function call.
171
    Propagates any column renaming to the returned value.
172
    '''
173
    name = None
174
    if isinstance(value, NamedCol): name = value.name
175
    value = FunctionCall(function, value)
176
    if name != None: value = NamedCol(name, value)
177
    return value
178

    
179
def unwrap_func_call(func_call, check_name=None):
180
    '''Unwraps any function call to its first argument.
181
    Also removes any column renaming.
182
    '''
183
    func_call = remove_col_rename(func_call)
184
    if not isinstance(func_call, FunctionCall): return func_call
185
    
186
    if check_name != None:
187
        name = func_call.function.name
188
        assert name == None or name == check_name
189
    return func_call.args[0]
190

    
191
##### Conditions
192

    
193
class ColValueCond(Code):
194
    def __init__(self, col, value):
195
        value = as_ValueCond(value)
196
        
197
        self.col = col
198
        self.value = value
199
    
200
    def to_str(self, db): return self.value.to_str(db, self.col)
201

    
202
##### Condition column comparisons
203

    
204
class ValueCond(BasicObject):
205
    def __init__(self, value):
206
        if not isinstance(value, Code): value = Literal(value)
207
        value = remove_col_rename(value)
208
        
209
        self.value = value
210
    
211
    def to_str(self, db, left_value):
212
        '''
213
        @param left_value The Code object that the condition is being applied on
214
        '''
215
        raise NotImplemented()
216
    
217
    def __repr__(self): return self.to_str(mockDb, '<left_value>')
218

    
219
class CompareCond(ValueCond):
220
    def __init__(self, value, operator='='):
221
        '''
222
        @param operator By default, compares NULL values literally. Use '~=' or
223
            '~!=' to pass NULLs through.
224
        '''
225
        ValueCond.__init__(self, value)
226
        self.operator = operator
227
    
228
    def to_str(self, db, left_value):
229
        if not isinstance(left_value, Code): left_value = Col(left_value)
230
        left_value = remove_col_rename(left_value)
231
        
232
        right_value = self.value
233
        left = left_value.to_str(db)
234
        right = right_value.to_str(db)
235
        
236
        # Parse operator
237
        operator = self.operator
238
        passthru_null_ref = [False]
239
        operator = strings.remove_prefix('~', operator, passthru_null_ref)
240
        neg_ref = [False]
241
        operator = strings.remove_prefix('!', operator, neg_ref)
242
        equals = operator.endswith('=')
243
        if equals and is_null(self.value): operator = 'IS'
244
        
245
        # Create str
246
        str_ = left+' '+operator+' '+right
247
        if equals and not passthru_null_ref[0] and isinstance(right_value, Col):
248
            str_ += ' OR ('+left+' IS NULL AND '+right+' IS NULL)'
249
        if neg_ref[0]: str_ = 'NOT ('+str_+')'
250
        return str_
251

    
252
# Tells as_ValueCond() to assume a non-ValueCond is a literal value
253
assume_literal = object()
254

    
255
def as_ValueCond(value, default_table=assume_literal):
256
    if not isinstance(value, ValueCond):
257
        if default_table is not assume_literal:
258
            value = as_Col(value, default_table)
259
        return CompareCond(value)
260
    else: return value
261

    
262
##### Joins
263

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

    
266
# Tells Join the left and right columns have the same name and are never NULL
267
join_same_not_null = object()
268

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

    
271
class Join(BasicObject):
272
    def __init__(self, table, mapping, type_=None):
273
        '''
274
        @param mapping dict(right_table_col=left_table_col, ...)
275
            * if left_table_col is join_same: left_table_col = right_table_col
276
              * Note that right_table_col must be a string
277
            * if left_table_col is join_same_not_null:
278
              left_table_col = right_table_col and both have NOT NULL constraint
279
              * Note that right_table_col must be a string
280
        @param type_ None (for plain join)|str (e.g. 'LEFT')|filter_out
281
            * filter_out: equivalent to 'LEFT' with the query filtered by
282
              `table_pkey IS NULL` (indicating no match)
283
        '''
284
        if util.is_str(table): table = Table(table)
285
        assert type_ == None or util.is_str(type_) or type_ is filter_out
286
        
287
        self.table = table
288
        self.mapping = mapping
289
        self.type_ = type_
290
    
291
    def to_str(self, db, left_table):
292
        # Switch order (left_table is on the right in the comparison)
293
        right_table = left_table
294
        left_table = self.table # note left_table is reassigned
295
        
296
        def join(entry):
297
            '''Parses non-USING joins'''
298
            right_table_col, left_table_col = entry
299
            
300
            # Switch order (right_table_col is on the left in the comparison)
301
            left = right_table_col
302
            right = left_table_col
303
            
304
            # Parse special values
305
            if right is join_same: right = left
306
            elif right is join_same_not_null:
307
                right = CompareCond(as_Col(left, right_table), '~=')
308
            
309
            right = as_ValueCond(right, right_table)
310
            return '('+right.to_str(db, as_Col(left, left_table))+')'
311
        
312
        # Create join condition
313
        type_ = self.type_
314
        joins = self.mapping
315
        if type_ is not filter_out and reduce(operator.and_,
316
            (v is join_same_not_null for v in joins.itervalues())):
317
            # all cols w/ USING, so can use simpler USING syntax
318
            cols = (as_Col(v).to_str(db) for v in joins.iterkeys())
319
            join_cond = 'USING ('+(', '.join(cols))+')'
320
        else: join_cond = 'ON\n'+('\nAND\n'.join(map(join, joins.iteritems())))
321
        
322
        # Create join
323
        if type_ is filter_out: type_ = 'LEFT'
324
        str_ = ''
325
        if type_ != None: str_ += type_+' '
326
        str_ += 'JOIN '+left_table.to_str(db)+' '+join_cond
327
        return str_
328
    
329
    def __repr__(self): return self.to_str(mockDb, '<left_table>')
330

    
331
##### Value exprs
332

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