Project

General

Profile

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