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