Project

General

Profile

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