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
    def esc_value(self, value): return strings.ustr(value)
14
15
    def esc_name(self, name): return name
16
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 2260 aaronmk
def as_Col(col, table=None):
97 2333 aaronmk
    assert col != None
98
99
    if isinstance(col, Code): return col
100 2260 aaronmk
    else: return Col(col, table)
101
102 2323 aaronmk
class NamedCol(Col):
103 2229 aaronmk
    def __init__(self, name, code):
104 2310 aaronmk
        Col.__init__(self, name)
105
106 2229 aaronmk
        if not isinstance(code, Code): code = Literal(code)
107
108
        self.code = code
109
110
    def to_str(self, db):
111 2310 aaronmk
        return self.code.to_str(db)+' AS '+Col.to_str(self, db)
112 2314 aaronmk
113
    def to_Col(self): return Col(self.name)
114 2229 aaronmk
115 2335 aaronmk
##### Conditions
116 2259 aaronmk
117 2214 aaronmk
class ValueCond:
118 2213 aaronmk
    def __init__(self, value):
119 2225 aaronmk
        if not isinstance(value, Code): value = Literal(value)
120 2323 aaronmk
        if isinstance(value, NamedCol): value = value.code
121 2213 aaronmk
122
        self.value = value
123 2214 aaronmk
124 2216 aaronmk
    def to_str(self, db, left_value):
125 2214 aaronmk
        '''
126 2216 aaronmk
        @param left_value The Code object that the condition is being applied on
127 2214 aaronmk
        '''
128
        raise NotImplemented()
129 2228 aaronmk
130 2349 aaronmk
    def __str__(self): return self.to_str(mockDb, '')
131 2211 aaronmk
132
class CompareCond(ValueCond):
133
    def __init__(self, value, operator='='):
134 2222 aaronmk
        '''
135
        @param operator By default, compares NULL values literally. Use '~=' or
136
            '~!=' to pass NULLs through.
137
        '''
138 2211 aaronmk
        ValueCond.__init__(self, value)
139
        self.operator = operator
140
141 2216 aaronmk
    def to_str(self, db, left_value):
142
        if not isinstance(left_value, Code): left_value = Col(left_value)
143
144 2222 aaronmk
        right_value = self.value
145
        left = left_value.to_str(db)
146
        right = right_value.to_str(db)
147
148
        # Parse operator
149 2216 aaronmk
        operator = self.operator
150 2222 aaronmk
        passthru_null_ref = [False]
151
        operator = strings.remove_prefix('~', operator, passthru_null_ref)
152
        neg_ref = [False]
153
        operator = strings.remove_prefix('!', operator, neg_ref)
154
        equals = operator.endswith('=')
155
        if equals and is_null(self.value): operator = 'IS'
156
157
        # Create str
158
        str_ = left+' '+operator+' '+right
159
        if equals and not passthru_null_ref[0] and isinstance(right_value, Col):
160
            str_ += ' OR ('+left+' IS NULL AND '+right+' IS NULL)'
161
        if neg_ref[0]: str_ = 'NOT ('+str_+')'
162
        return str_
163 2216 aaronmk
164 2260 aaronmk
# Tells as_ValueCond() to assume a non-ValueCond is a literal value
165
assume_literal = object()
166
167
def as_ValueCond(value, default_table=assume_literal):
168
    if not isinstance(value, ValueCond):
169
        if default_table is not assume_literal:
170
            value = as_Col(value, default_table)
171
        return CompareCond(value)
172 2216 aaronmk
    else: return value
173 2219 aaronmk
174 2335 aaronmk
##### Joins
175
176 2352 aaronmk
join_same = object() # tells Join the left and right columns have the same name
177 2260 aaronmk
178 2353 aaronmk
# Tells Join the left and right columns have the same name and are never NULL
179
join_same_not_null = object()
180
181 2260 aaronmk
filter_out = object() # tells Join to filter out rows that match the join
182
183
class Join(Code):
184
    def __init__(self, table, mapping, type_=None):
185
        '''
186
        @param mapping dict(right_table_col=left_table_col, ...)
187 2352 aaronmk
            * if left_table_col is join_same: left_table_col = right_table_col
188 2353 aaronmk
              * Note that right_table_col must be a string
189
            * if left_table_col is join_same_not_null:
190
              left_table_col = right_table_col and both have NOT NULL constraint
191
              * Note that right_table_col must be a string
192 2260 aaronmk
        @param type_ None (for plain join)|str (e.g. 'LEFT')|filter_out
193
            * filter_out: equivalent to 'LEFT' with the query filtered by
194
              `table_pkey IS NULL` (indicating no match)
195
        '''
196
        if util.is_str(table): table = Table(table)
197
        assert type_ == None or util.is_str(type_) or type_ is filter_out
198
199
        self.table = table
200
        self.mapping = mapping
201
        self.type_ = type_
202
203
    def to_str(self, db, left_table):
204 2353 aaronmk
        # Switch order (left_table is on the right in the comparison)
205
        right_table = left_table
206
        left_table = self.table # note left_table is reassigned
207
208 2260 aaronmk
        def join(entry):
209
            '''Parses non-USING joins'''
210
            right_table_col, left_table_col = entry
211
212 2353 aaronmk
            # Switch order (right_table_col is on the left in the comparison)
213
            left = right_table_col
214
            right = left_table_col
215
216 2260 aaronmk
            # Parse special values
217 2353 aaronmk
            if right is join_same: right = left
218
            elif right is join_same_not_null:
219
                right = CompareCond(as_Col(left, right_table), '~=')
220 2260 aaronmk
221 2353 aaronmk
            right = as_ValueCond(right, right_table)
222
            return right.to_str(db, as_Col(left, left_table))
223 2260 aaronmk
224 2265 aaronmk
        # Create join condition
225
        type_ = self.type_
226 2276 aaronmk
        joins = self.mapping
227 2265 aaronmk
        if type_ is not filter_out and reduce(operator.and_,
228 2352 aaronmk
            (v is join_same for v in joins.itervalues())):
229 2260 aaronmk
            # all cols w/ USING, so can use simpler USING syntax
230 2298 aaronmk
            cols = (as_Col(v).to_str(db) for v in joins.iterkeys())
231
            join_cond = 'USING ('+(', '.join(cols))+')'
232 2260 aaronmk
        else: join_cond = 'ON '+(' AND '.join(map(join, joins.iteritems())))
233
234
        # Create join
235
        if type_ is filter_out: type_ = 'LEFT'
236 2266 aaronmk
        str_ = ''
237
        if type_ != None: str_ += type_+' '
238 2353 aaronmk
        str_ += 'JOIN '+left_table.to_str(db)+' '+join_cond
239 2266 aaronmk
        return str_
240 2349 aaronmk
241
    def __str__(self): return self.to_str(mockDb, '')