Project

General

Profile

1 2211 aaronmk
# SQL code generation
2
3 2276 aaronmk
import operator
4
5 2360 aaronmk
import objects
6 2222 aaronmk
import strings
7 2227 aaronmk
import util
8 2211 aaronmk
9 2499 aaronmk
##### 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 2219 aaronmk
##### SQL code objects
16
17 2349 aaronmk
class MockDb:
18 2367 aaronmk
    def esc_value(self, value): return repr(value)
19 2349 aaronmk
20 2499 aaronmk
    def esc_name(self, name): return esc_name(name)
21 2349 aaronmk
mockDb = MockDb()
22
23 2360 aaronmk
class Code(objects.BasicObject):
24 2211 aaronmk
    def to_str(self, db): raise NotImplemented()
25 2349 aaronmk
26
    def __str__(self): return self.to_str(mockDb)
27 2211 aaronmk
28 2269 aaronmk
class CustomCode(Code):
29 2256 aaronmk
    def __init__(self, str_): self.str_ = str_
30
31
    def to_str(self, db): return self.str_
32
33 2335 aaronmk
##### Literal values
34
35 2216 aaronmk
class Literal(Code):
36 2211 aaronmk
    def __init__(self, value): self.value = value
37 2213 aaronmk
38
    def to_str(self, db): return db.esc_value(self.value)
39 2211 aaronmk
40 2400 aaronmk
def as_Value(value):
41
    if isinstance(value, Code): return value
42
    else: return Literal(value)
43
44 2216 aaronmk
def is_null(value): return isinstance(value, Literal) and value.value == None
45
46 2335 aaronmk
##### Tables
47
48 2211 aaronmk
class Table(Code):
49
    def __init__(self, name, schema=None):
50
        '''
51
        @param schema str|None (for no schema)
52
        '''
53
        self.name = name
54
        self.schema = schema
55
56 2348 aaronmk
    def to_str(self, db):
57
        str_ = ''
58
        if self.schema != None: str_ += db.esc_name(self.schema)+'.'
59
        str_ += db.esc_name(self.name)
60
        return str_
61 2336 aaronmk
62
    def to_Table(self): return self
63 2211 aaronmk
64 2219 aaronmk
def as_Table(table):
65 2270 aaronmk
    if table == None or isinstance(table, Code): return table
66 2219 aaronmk
    else: return Table(table)
67
68 2336 aaronmk
class NamedTable(Table):
69
    def __init__(self, name, code, cols=None):
70
        Table.__init__(self, name)
71
72
        if not isinstance(code, Code): code = Table(code)
73
74
        self.code = code
75
        self.cols = cols
76
77
    def to_str(self, db):
78 2467 aaronmk
        str_ = self.code.to_str(db)+'\nAS '+Table.to_str(self, db)
79 2336 aaronmk
        if self.cols != None: str_ += ' ('+(', '.join(self.cols))+')'
80
        return str_
81
82
    def to_Table(self): return Table(self.name)
83
84 2335 aaronmk
##### Columns
85
86 2211 aaronmk
class Col(Code):
87
    def __init__(self, name, table=None):
88
        '''
89
        @param table Table|None (for no table)
90
        '''
91 2241 aaronmk
        if util.is_str(table): table = Table(table)
92 2211 aaronmk
        assert table == None or isinstance(table, Table)
93
94
        self.name = name
95
        self.table = table
96
97
    def to_str(self, db):
98
        str_ = ''
99
        if self.table != None: str_ += self.table.to_str(db)+'.'
100 2348 aaronmk
        str_ += db.esc_name(self.name)
101 2211 aaronmk
        return str_
102 2314 aaronmk
103
    def to_Col(self): return self
104 2211 aaronmk
105 2393 aaronmk
def is_table_col(col): return col.table != None
106
107 2260 aaronmk
def as_Col(col, table=None):
108 2333 aaronmk
    assert col != None
109
110
    if isinstance(col, Code): return col
111 2260 aaronmk
    else: return Col(col, table)
112
113 2401 aaronmk
def to_name_only_col(col, check_table=None):
114
    col = as_Col(col)
115
116
    if check_table != None:
117
        table = col.table
118
        assert table == None or table == check_table
119
    return Col(col.name)
120
121 2323 aaronmk
class NamedCol(Col):
122 2229 aaronmk
    def __init__(self, name, code):
123 2310 aaronmk
        Col.__init__(self, name)
124
125 2229 aaronmk
        if not isinstance(code, Code): code = Literal(code)
126
127
        self.code = code
128
129
    def to_str(self, db):
130 2310 aaronmk
        return self.code.to_str(db)+' AS '+Col.to_str(self, db)
131 2314 aaronmk
132
    def to_Col(self): return Col(self.name)
133 2229 aaronmk
134 2462 aaronmk
def remove_col_rename(col):
135
    if isinstance(col, NamedCol): col = col.code
136
    return col
137
138 2335 aaronmk
##### Conditions
139 2259 aaronmk
140 2398 aaronmk
class ColValueCond(Code):
141
    def __init__(self, col, value):
142
        value = as_ValueCond(value)
143
144
        self.col = col
145
        self.value = value
146
147
    def to_str(self, db): return self.value.to_str(db, self.col)
148
149
##### Condition column comparisons
150
151 2366 aaronmk
class ValueCond(objects.BasicObject):
152 2213 aaronmk
    def __init__(self, value):
153 2225 aaronmk
        if not isinstance(value, Code): value = Literal(value)
154 2462 aaronmk
        value = remove_col_rename(value)
155 2213 aaronmk
156
        self.value = value
157 2214 aaronmk
158 2216 aaronmk
    def to_str(self, db, left_value):
159 2214 aaronmk
        '''
160 2216 aaronmk
        @param left_value The Code object that the condition is being applied on
161 2214 aaronmk
        '''
162
        raise NotImplemented()
163 2228 aaronmk
164 2370 aaronmk
    def __str__(self): return self.to_str(mockDb, '<left_value>')
165 2211 aaronmk
166
class CompareCond(ValueCond):
167
    def __init__(self, value, operator='='):
168 2222 aaronmk
        '''
169
        @param operator By default, compares NULL values literally. Use '~=' or
170
            '~!=' to pass NULLs through.
171
        '''
172 2211 aaronmk
        ValueCond.__init__(self, value)
173
        self.operator = operator
174
175 2216 aaronmk
    def to_str(self, db, left_value):
176
        if not isinstance(left_value, Code): left_value = Col(left_value)
177 2462 aaronmk
        left_value = remove_col_rename(left_value)
178 2216 aaronmk
179 2222 aaronmk
        right_value = self.value
180
        left = left_value.to_str(db)
181
        right = right_value.to_str(db)
182
183
        # Parse operator
184 2216 aaronmk
        operator = self.operator
185 2222 aaronmk
        passthru_null_ref = [False]
186
        operator = strings.remove_prefix('~', operator, passthru_null_ref)
187
        neg_ref = [False]
188
        operator = strings.remove_prefix('!', operator, neg_ref)
189
        equals = operator.endswith('=')
190
        if equals and is_null(self.value): operator = 'IS'
191
192
        # Create str
193
        str_ = left+' '+operator+' '+right
194
        if equals and not passthru_null_ref[0] and isinstance(right_value, Col):
195
            str_ += ' OR ('+left+' IS NULL AND '+right+' IS NULL)'
196
        if neg_ref[0]: str_ = 'NOT ('+str_+')'
197
        return str_
198 2216 aaronmk
199 2260 aaronmk
# Tells as_ValueCond() to assume a non-ValueCond is a literal value
200
assume_literal = object()
201
202
def as_ValueCond(value, default_table=assume_literal):
203
    if not isinstance(value, ValueCond):
204
        if default_table is not assume_literal:
205
            value = as_Col(value, default_table)
206
        return CompareCond(value)
207 2216 aaronmk
    else: return value
208 2219 aaronmk
209 2335 aaronmk
##### Joins
210
211 2352 aaronmk
join_same = object() # tells Join the left and right columns have the same name
212 2260 aaronmk
213 2353 aaronmk
# Tells Join the left and right columns have the same name and are never NULL
214
join_same_not_null = object()
215
216 2260 aaronmk
filter_out = object() # tells Join to filter out rows that match the join
217
218 2366 aaronmk
class Join(objects.BasicObject):
219 2260 aaronmk
    def __init__(self, table, mapping, type_=None):
220
        '''
221
        @param mapping dict(right_table_col=left_table_col, ...)
222 2352 aaronmk
            * if left_table_col is join_same: left_table_col = right_table_col
223 2353 aaronmk
              * Note that right_table_col must be a string
224
            * if left_table_col is join_same_not_null:
225
              left_table_col = right_table_col and both have NOT NULL constraint
226
              * Note that right_table_col must be a string
227 2260 aaronmk
        @param type_ None (for plain join)|str (e.g. 'LEFT')|filter_out
228
            * filter_out: equivalent to 'LEFT' with the query filtered by
229
              `table_pkey IS NULL` (indicating no match)
230
        '''
231
        if util.is_str(table): table = Table(table)
232
        assert type_ == None or util.is_str(type_) or type_ is filter_out
233
234
        self.table = table
235
        self.mapping = mapping
236
        self.type_ = type_
237
238
    def to_str(self, db, left_table):
239 2353 aaronmk
        # Switch order (left_table is on the right in the comparison)
240
        right_table = left_table
241
        left_table = self.table # note left_table is reassigned
242
243 2260 aaronmk
        def join(entry):
244
            '''Parses non-USING joins'''
245
            right_table_col, left_table_col = entry
246
247 2353 aaronmk
            # Switch order (right_table_col is on the left in the comparison)
248
            left = right_table_col
249
            right = left_table_col
250
251 2260 aaronmk
            # Parse special values
252 2353 aaronmk
            if right is join_same: right = left
253
            elif right is join_same_not_null:
254
                right = CompareCond(as_Col(left, right_table), '~=')
255 2260 aaronmk
256 2353 aaronmk
            right = as_ValueCond(right, right_table)
257 2410 aaronmk
            return '('+right.to_str(db, as_Col(left, left_table))+')'
258 2260 aaronmk
259 2265 aaronmk
        # Create join condition
260
        type_ = self.type_
261 2276 aaronmk
        joins = self.mapping
262 2265 aaronmk
        if type_ is not filter_out and reduce(operator.and_,
263 2460 aaronmk
            (v is join_same_not_null for v in joins.itervalues())):
264 2260 aaronmk
            # all cols w/ USING, so can use simpler USING syntax
265 2298 aaronmk
            cols = (as_Col(v).to_str(db) for v in joins.iterkeys())
266
            join_cond = 'USING ('+(', '.join(cols))+')'
267 2467 aaronmk
        else: join_cond = 'ON\n'+('\nAND\n'.join(map(join, joins.iteritems())))
268 2260 aaronmk
269
        # Create join
270
        if type_ is filter_out: type_ = 'LEFT'
271 2266 aaronmk
        str_ = ''
272
        if type_ != None: str_ += type_+' '
273 2353 aaronmk
        str_ += 'JOIN '+left_table.to_str(db)+' '+join_cond
274 2266 aaronmk
        return str_
275 2349 aaronmk
276 2370 aaronmk
    def __str__(self): return self.to_str(mockDb, '<left_table>')
277 2424 aaronmk
278
##### Value exprs
279
280
row_count = CustomCode('count(*)')