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
##### Literal values
41

    
42
class Literal(Code):
43
    def __init__(self, value): self.value = value
44
    
45
    def to_str(self, db): return db.esc_value(self.value)
46

    
47
def as_Value(value):
48
    if isinstance(value, Code): return value
49
    else: return Literal(value)
50

    
51
def is_null(value): return isinstance(value, Literal) and value.value == None
52

    
53
##### Tables
54

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

    
71
def as_Table(table):
72
    if table == None or isinstance(table, Code): return table
73
    else: return Table(table)
74

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

    
91
##### Columns
92

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

    
112
def is_table_col(col): return col.table != None
113

    
114
def as_Col(col, table=None):
115
    assert col != None
116
    
117
    if isinstance(col, Code): return col
118
    else: return Col(col, table)
119

    
120
def to_name_only_col(col, check_table=None):
121
    col = as_Col(col)
122
    
123
    if check_table != None:
124
        table = col.table
125
        assert table == None or table == check_table
126
    return Col(col.name)
127

    
128
class NamedCol(Col):
129
    def __init__(self, name, code):
130
        Col.__init__(self, name)
131
        
132
        if not isinstance(code, Code): code = Literal(code)
133
        
134
        self.code = code
135
    
136
    def to_str(self, db):
137
        return self.code.to_str(db)+' AS '+Col.to_str(self, db)
138
    
139
    def to_Col(self): return Col(self.name)
140

    
141
def remove_col_rename(col):
142
    if isinstance(col, NamedCol): col = col.code
143
    return col
144

    
145
##### Functions
146

    
147
class Function(Table): pass
148

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

    
164
def wrap_in_func(function, value):
165
    '''Wraps a value inside a function call.
166
    Propagates any column renaming to the returned value.
167
    '''
168
    name = None
169
    if isinstance(value, NamedCol): name = value.name
170
    value = FunctionCall(function, value)
171
    if name != None: value = NamedCol(name, value)
172
    return value
173

    
174
##### Conditions
175

    
176
class ColValueCond(Code):
177
    def __init__(self, col, value):
178
        value = as_ValueCond(value)
179
        
180
        self.col = col
181
        self.value = value
182
    
183
    def to_str(self, db): return self.value.to_str(db, self.col)
184

    
185
##### Condition column comparisons
186

    
187
class ValueCond(BasicObject):
188
    def __init__(self, value):
189
        if not isinstance(value, Code): value = Literal(value)
190
        value = remove_col_rename(value)
191
        
192
        self.value = value
193
    
194
    def to_str(self, db, left_value):
195
        '''
196
        @param left_value The Code object that the condition is being applied on
197
        '''
198
        raise NotImplemented()
199
    
200
    def __repr__(self): return self.to_str(mockDb, '<left_value>')
201

    
202
class CompareCond(ValueCond):
203
    def __init__(self, value, operator='='):
204
        '''
205
        @param operator By default, compares NULL values literally. Use '~=' or
206
            '~!=' to pass NULLs through.
207
        '''
208
        ValueCond.__init__(self, value)
209
        self.operator = operator
210
    
211
    def to_str(self, db, left_value):
212
        if not isinstance(left_value, Code): left_value = Col(left_value)
213
        left_value = remove_col_rename(left_value)
214
        
215
        right_value = self.value
216
        left = left_value.to_str(db)
217
        right = right_value.to_str(db)
218
        
219
        # Parse operator
220
        operator = self.operator
221
        passthru_null_ref = [False]
222
        operator = strings.remove_prefix('~', operator, passthru_null_ref)
223
        neg_ref = [False]
224
        operator = strings.remove_prefix('!', operator, neg_ref)
225
        equals = operator.endswith('=')
226
        if equals and is_null(self.value): operator = 'IS'
227
        
228
        # Create str
229
        str_ = left+' '+operator+' '+right
230
        if equals and not passthru_null_ref[0] and isinstance(right_value, Col):
231
            str_ += ' OR ('+left+' IS NULL AND '+right+' IS NULL)'
232
        if neg_ref[0]: str_ = 'NOT ('+str_+')'
233
        return str_
234

    
235
# Tells as_ValueCond() to assume a non-ValueCond is a literal value
236
assume_literal = object()
237

    
238
def as_ValueCond(value, default_table=assume_literal):
239
    if not isinstance(value, ValueCond):
240
        if default_table is not assume_literal:
241
            value = as_Col(value, default_table)
242
        return CompareCond(value)
243
    else: return value
244

    
245
##### Joins
246

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

    
249
# Tells Join the left and right columns have the same name and are never NULL
250
join_same_not_null = object()
251

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

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

    
314
##### Value exprs
315

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