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