1
|
# SQL code generation
|
2
|
|
3
|
import operator
|
4
|
|
5
|
import sql
|
6
|
import strings
|
7
|
import util
|
8
|
|
9
|
##### SQL code objects
|
10
|
|
11
|
class Code(strings.DebugPrintable):
|
12
|
def to_str(self, db): raise NotImplemented()
|
13
|
|
14
|
class CustomCode(Code):
|
15
|
def __init__(self, str_): self.str_ = str_
|
16
|
|
17
|
def to_str(self, db): return self.str_
|
18
|
|
19
|
class Literal(Code):
|
20
|
def __init__(self, value): self.value = value
|
21
|
|
22
|
def to_str(self, db): return db.esc_value(self.value)
|
23
|
|
24
|
def is_null(value): return isinstance(value, Literal) and value.value == None
|
25
|
|
26
|
class Table(Code):
|
27
|
def __init__(self, name, schema=None):
|
28
|
'''
|
29
|
@param schema str|None (for no schema)
|
30
|
'''
|
31
|
self.name = name
|
32
|
self.schema = schema
|
33
|
|
34
|
def to_str(self, db): return sql.qual_name(db, self.schema, self.name)
|
35
|
|
36
|
def as_Table(table):
|
37
|
if table == None or isinstance(table, Code): return table
|
38
|
else: return Table(table)
|
39
|
|
40
|
class Col(Code):
|
41
|
def __init__(self, name, table=None):
|
42
|
'''
|
43
|
@param table Table|None (for no table)
|
44
|
'''
|
45
|
if util.is_str(table): table = Table(table)
|
46
|
assert table == None or isinstance(table, Table)
|
47
|
|
48
|
self.name = name
|
49
|
self.table = table
|
50
|
|
51
|
def to_str(self, db):
|
52
|
str_ = ''
|
53
|
if self.table != None: str_ += self.table.to_str(db)+'.'
|
54
|
str_ += sql.esc_name(db, self.name)
|
55
|
return str_
|
56
|
|
57
|
def to_Col(self): return self
|
58
|
|
59
|
def as_Col(col, table=None):
|
60
|
assert col != None
|
61
|
|
62
|
if isinstance(col, Code): return col
|
63
|
else: return Col(col, table)
|
64
|
|
65
|
class NamedCol(Col):
|
66
|
def __init__(self, name, code):
|
67
|
Col.__init__(self, name)
|
68
|
|
69
|
if not isinstance(code, Code): code = Literal(code)
|
70
|
|
71
|
self.code = code
|
72
|
|
73
|
def to_str(self, db):
|
74
|
return self.code.to_str(db)+' AS '+Col.to_str(self, db)
|
75
|
|
76
|
def to_Col(self): return Col(self.name)
|
77
|
|
78
|
##### Parameterized SQL code objects
|
79
|
|
80
|
class ValueCond:
|
81
|
def __init__(self, value):
|
82
|
if not isinstance(value, Code): value = Literal(value)
|
83
|
if isinstance(value, NamedCol): value = value.code
|
84
|
|
85
|
self.value = value
|
86
|
|
87
|
def to_str(self, db, left_value):
|
88
|
'''
|
89
|
@param left_value The Code object that the condition is being applied on
|
90
|
'''
|
91
|
raise NotImplemented()
|
92
|
|
93
|
def __str__(self): return str(self.__dict__)
|
94
|
|
95
|
class CompareCond(ValueCond):
|
96
|
def __init__(self, value, operator='='):
|
97
|
'''
|
98
|
@param operator By default, compares NULL values literally. Use '~=' or
|
99
|
'~!=' to pass NULLs through.
|
100
|
'''
|
101
|
ValueCond.__init__(self, value)
|
102
|
self.operator = operator
|
103
|
|
104
|
def to_str(self, db, left_value):
|
105
|
if not isinstance(left_value, Code): left_value = Col(left_value)
|
106
|
|
107
|
right_value = self.value
|
108
|
left = left_value.to_str(db)
|
109
|
right = right_value.to_str(db)
|
110
|
|
111
|
# Parse operator
|
112
|
operator = self.operator
|
113
|
passthru_null_ref = [False]
|
114
|
operator = strings.remove_prefix('~', operator, passthru_null_ref)
|
115
|
neg_ref = [False]
|
116
|
operator = strings.remove_prefix('!', operator, neg_ref)
|
117
|
equals = operator.endswith('=')
|
118
|
if equals and is_null(self.value): operator = 'IS'
|
119
|
|
120
|
# Create str
|
121
|
str_ = left+' '+operator+' '+right
|
122
|
if equals and not passthru_null_ref[0] and isinstance(right_value, Col):
|
123
|
str_ += ' OR ('+left+' IS NULL AND '+right+' IS NULL)'
|
124
|
if neg_ref[0]: str_ = 'NOT ('+str_+')'
|
125
|
return str_
|
126
|
|
127
|
# Tells as_ValueCond() to assume a non-ValueCond is a literal value
|
128
|
assume_literal = object()
|
129
|
|
130
|
def as_ValueCond(value, default_table=assume_literal):
|
131
|
if not isinstance(value, ValueCond):
|
132
|
if default_table is not assume_literal:
|
133
|
value = as_Col(value, default_table)
|
134
|
return CompareCond(value)
|
135
|
else: return value
|
136
|
|
137
|
join_using = object() # tells Join to join the column with USING
|
138
|
|
139
|
filter_out = object() # tells Join to filter out rows that match the join
|
140
|
|
141
|
class Join(Code):
|
142
|
def __init__(self, table, mapping, type_=None):
|
143
|
'''
|
144
|
@param mapping dict(right_table_col=left_table_col, ...)
|
145
|
* if left_table_col is join_using: left_table_col = right_table_col
|
146
|
@param type_ None (for plain join)|str (e.g. 'LEFT')|filter_out
|
147
|
* filter_out: equivalent to 'LEFT' with the query filtered by
|
148
|
`table_pkey IS NULL` (indicating no match)
|
149
|
'''
|
150
|
if util.is_str(table): table = Table(table)
|
151
|
assert type_ == None or util.is_str(type_) or type_ is filter_out
|
152
|
|
153
|
self.table = table
|
154
|
self.mapping = mapping
|
155
|
self.type_ = type_
|
156
|
|
157
|
def to_str(self, db, left_table):
|
158
|
def join(entry):
|
159
|
'''Parses non-USING joins'''
|
160
|
right_table_col, left_table_col = entry
|
161
|
# Note that right_table_col is on the left in the comparison
|
162
|
|
163
|
# Parse special values
|
164
|
if left_table_col is join_using: left_table_col = right_table_col
|
165
|
|
166
|
cond = as_ValueCond(left_table_col, left_table)
|
167
|
return cond.to_str(db, as_Col(right_table_col, self.table))
|
168
|
|
169
|
# Create join condition
|
170
|
type_ = self.type_
|
171
|
joins = self.mapping
|
172
|
if type_ is not filter_out and reduce(operator.and_,
|
173
|
(v is join_using for v in joins.itervalues())):
|
174
|
# all cols w/ USING, so can use simpler USING syntax
|
175
|
cols = (as_Col(v).to_str(db) for v in joins.iterkeys())
|
176
|
join_cond = 'USING ('+(', '.join(cols))+')'
|
177
|
else: join_cond = 'ON '+(' AND '.join(map(join, joins.iteritems())))
|
178
|
|
179
|
# Create join
|
180
|
if type_ is filter_out: type_ = 'LEFT'
|
181
|
str_ = ''
|
182
|
if type_ != None: str_ += type_+' '
|
183
|
str_ += 'JOIN '+self.table.to_str(db)+' '+join_cond
|
184
|
return str_
|