1
|
# SQL code generation
|
2
|
|
3
|
import operator
|
4
|
|
5
|
import objects
|
6
|
import sql
|
7
|
import strings
|
8
|
import util
|
9
|
|
10
|
##### SQL code objects
|
11
|
|
12
|
class MockDb:
|
13
|
def esc_value(self, value): return repr(value)
|
14
|
|
15
|
def esc_name(self, name): return sql.esc_name_by_module(None, name)
|
16
|
mockDb = MockDb()
|
17
|
|
18
|
class Code(objects.BasicObject):
|
19
|
def to_str(self, db): raise NotImplemented()
|
20
|
|
21
|
def __str__(self): return self.to_str(mockDb)
|
22
|
|
23
|
class CustomCode(Code):
|
24
|
def __init__(self, str_): self.str_ = str_
|
25
|
|
26
|
def to_str(self, db): return self.str_
|
27
|
|
28
|
##### Literal values
|
29
|
|
30
|
class Literal(Code):
|
31
|
def __init__(self, value): self.value = value
|
32
|
|
33
|
def to_str(self, db): return db.esc_value(self.value)
|
34
|
|
35
|
def as_Value(value):
|
36
|
if isinstance(value, Code): return value
|
37
|
else: return Literal(value)
|
38
|
|
39
|
def is_null(value): return isinstance(value, Literal) and value.value == None
|
40
|
|
41
|
##### Tables
|
42
|
|
43
|
class Table(Code):
|
44
|
def __init__(self, name, schema=None):
|
45
|
'''
|
46
|
@param schema str|None (for no schema)
|
47
|
'''
|
48
|
self.name = name
|
49
|
self.schema = schema
|
50
|
|
51
|
def to_str(self, db):
|
52
|
str_ = ''
|
53
|
if self.schema != None: str_ += db.esc_name(self.schema)+'.'
|
54
|
str_ += db.esc_name(self.name)
|
55
|
return str_
|
56
|
|
57
|
def to_Table(self): return self
|
58
|
|
59
|
def as_Table(table):
|
60
|
if table == None or isinstance(table, Code): return table
|
61
|
else: return Table(table)
|
62
|
|
63
|
class NamedTable(Table):
|
64
|
def __init__(self, name, code, cols=None):
|
65
|
Table.__init__(self, name)
|
66
|
|
67
|
if not isinstance(code, Code): code = Table(code)
|
68
|
|
69
|
self.code = code
|
70
|
self.cols = cols
|
71
|
|
72
|
def to_str(self, db):
|
73
|
str_ = self.code.to_str(db)+' AS '+Table.to_str(self, db)
|
74
|
if self.cols != None: str_ += ' ('+(', '.join(self.cols))+')'
|
75
|
return str_
|
76
|
|
77
|
def to_Table(self): return Table(self.name)
|
78
|
|
79
|
##### Columns
|
80
|
|
81
|
class Col(Code):
|
82
|
def __init__(self, name, table=None):
|
83
|
'''
|
84
|
@param table Table|None (for no table)
|
85
|
'''
|
86
|
if util.is_str(table): table = Table(table)
|
87
|
assert table == None or isinstance(table, Table)
|
88
|
|
89
|
self.name = name
|
90
|
self.table = table
|
91
|
|
92
|
def to_str(self, db):
|
93
|
str_ = ''
|
94
|
if self.table != None: str_ += self.table.to_str(db)+'.'
|
95
|
str_ += db.esc_name(self.name)
|
96
|
return str_
|
97
|
|
98
|
def to_Col(self): return self
|
99
|
|
100
|
def is_table_col(col): return col.table != None
|
101
|
|
102
|
def as_Col(col, table=None):
|
103
|
assert col != None
|
104
|
|
105
|
if isinstance(col, Code): return col
|
106
|
else: return Col(col, table)
|
107
|
|
108
|
def to_name_only_col(col, check_table=None):
|
109
|
col = as_Col(col)
|
110
|
|
111
|
if check_table != None:
|
112
|
table = col.table
|
113
|
assert table == None or table == check_table
|
114
|
return Col(col.name)
|
115
|
|
116
|
class NamedCol(Col):
|
117
|
def __init__(self, name, code):
|
118
|
Col.__init__(self, name)
|
119
|
|
120
|
if not isinstance(code, Code): code = Literal(code)
|
121
|
|
122
|
self.code = code
|
123
|
|
124
|
def to_str(self, db):
|
125
|
return self.code.to_str(db)+' AS '+Col.to_str(self, db)
|
126
|
|
127
|
def to_Col(self): return Col(self.name)
|
128
|
|
129
|
##### Conditions
|
130
|
|
131
|
class ColValueCond(Code):
|
132
|
def __init__(self, col, value):
|
133
|
value = as_ValueCond(value)
|
134
|
|
135
|
self.col = col
|
136
|
self.value = value
|
137
|
|
138
|
def to_str(self, db): return self.value.to_str(db, self.col)
|
139
|
|
140
|
##### Condition column comparisons
|
141
|
|
142
|
class ValueCond(objects.BasicObject):
|
143
|
def __init__(self, value):
|
144
|
if not isinstance(value, Code): value = Literal(value)
|
145
|
if isinstance(value, NamedCol): value = value.code
|
146
|
|
147
|
self.value = value
|
148
|
|
149
|
def to_str(self, db, left_value):
|
150
|
'''
|
151
|
@param left_value The Code object that the condition is being applied on
|
152
|
'''
|
153
|
raise NotImplemented()
|
154
|
|
155
|
def __str__(self): return self.to_str(mockDb, '<left_value>')
|
156
|
|
157
|
class CompareCond(ValueCond):
|
158
|
def __init__(self, value, operator='='):
|
159
|
'''
|
160
|
@param operator By default, compares NULL values literally. Use '~=' or
|
161
|
'~!=' to pass NULLs through.
|
162
|
'''
|
163
|
ValueCond.__init__(self, value)
|
164
|
self.operator = operator
|
165
|
|
166
|
def to_str(self, db, left_value):
|
167
|
if not isinstance(left_value, Code): left_value = Col(left_value)
|
168
|
|
169
|
right_value = self.value
|
170
|
left = left_value.to_str(db)
|
171
|
right = right_value.to_str(db)
|
172
|
|
173
|
# Parse operator
|
174
|
operator = self.operator
|
175
|
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
|
|
189
|
# 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
|
else: return value
|
198
|
|
199
|
##### Joins
|
200
|
|
201
|
join_same = object() # tells Join the left and right columns have the same name
|
202
|
|
203
|
# Tells Join the left and right columns have the same name and are never NULL
|
204
|
join_same_not_null = object()
|
205
|
|
206
|
filter_out = object() # tells Join to filter out rows that match the join
|
207
|
|
208
|
class Join(objects.BasicObject):
|
209
|
def __init__(self, table, mapping, type_=None):
|
210
|
'''
|
211
|
@param mapping dict(right_table_col=left_table_col, ...)
|
212
|
* if left_table_col is join_same: left_table_col = right_table_col
|
213
|
* 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
|
@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
|
# 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
|
def join(entry):
|
234
|
'''Parses non-USING joins'''
|
235
|
right_table_col, left_table_col = entry
|
236
|
|
237
|
# Switch order (right_table_col is on the left in the comparison)
|
238
|
left = right_table_col
|
239
|
right = left_table_col
|
240
|
|
241
|
# Parse special values
|
242
|
if right is join_same: right = left
|
243
|
elif right is join_same_not_null:
|
244
|
right = CompareCond(as_Col(left, right_table), '~=')
|
245
|
|
246
|
right = as_ValueCond(right, right_table)
|
247
|
return right.to_str(db, as_Col(left, left_table))
|
248
|
|
249
|
# Create join condition
|
250
|
type_ = self.type_
|
251
|
joins = self.mapping
|
252
|
if type_ is not filter_out and reduce(operator.and_,
|
253
|
(v is join_same for v in joins.itervalues())):
|
254
|
# all cols w/ USING, so can use simpler USING syntax
|
255
|
cols = (as_Col(v).to_str(db) for v in joins.iterkeys())
|
256
|
join_cond = 'USING ('+(', '.join(cols))+')'
|
257
|
else: join_cond = 'ON '+(' AND '.join(map(join, joins.iteritems())))
|
258
|
|
259
|
# Create join
|
260
|
if type_ is filter_out: type_ = 'LEFT'
|
261
|
str_ = ''
|
262
|
if type_ != None: str_ += type_+' '
|
263
|
str_ += 'JOIN '+left_table.to_str(db)+' '+join_cond
|
264
|
return str_
|
265
|
|
266
|
def __str__(self): return self.to_str(mockDb, '<left_table>')
|