Project

General

Profile

1
# SQL code generation
2

    
3
import operator
4

    
5
import objects
6
import strings
7
import util
8

    
9
##### SQL code objects
10

    
11
class MockDb:
12
    def esc_value(self, value): return repr(value)
13
    
14
    def esc_name(self, name): return '"'+name+'"'
15
mockDb = MockDb()
16

    
17
class Code(objects.BasicObject):
18
    def to_str(self, db): raise NotImplemented()
19
    
20
    def __str__(self): return self.to_str(mockDb)
21

    
22
class CustomCode(Code):
23
    def __init__(self, str_): self.str_ = str_
24
    
25
    def to_str(self, db): return self.str_
26

    
27
##### Literal values
28

    
29
class Literal(Code):
30
    def __init__(self, value): self.value = value
31
    
32
    def to_str(self, db): return db.esc_value(self.value)
33

    
34
def as_Value(value):
35
    if isinstance(value, Code): return value
36
    else: return Literal(value)
37

    
38
def is_null(value): return isinstance(value, Literal) and value.value == None
39

    
40
##### Tables
41

    
42
class Table(Code):
43
    def __init__(self, name, schema=None):
44
        '''
45
        @param schema str|None (for no schema)
46
        '''
47
        self.name = name
48
        self.schema = schema
49
    
50
    def to_str(self, db):
51
        str_ = ''
52
        if self.schema != None: str_ += db.esc_name(self.schema)+'.'
53
        str_ += db.esc_name(self.name)
54
        return str_
55
    
56
    def to_Table(self): return self
57

    
58
def as_Table(table):
59
    if table == None or isinstance(table, Code): return table
60
    else: return Table(table)
61

    
62
class NamedTable(Table):
63
    def __init__(self, name, code, cols=None):
64
        Table.__init__(self, name)
65
        
66
        if not isinstance(code, Code): code = Table(code)
67
        
68
        self.code = code
69
        self.cols = cols
70
    
71
    def to_str(self, db):
72
        str_ = self.code.to_str(db)+' AS '+Table.to_str(self, db)
73
        if self.cols != None: str_ += ' ('+(', '.join(self.cols))+')'
74
        return str_
75
    
76
    def to_Table(self): return Table(self.name)
77

    
78
##### Columns
79

    
80
class Col(Code):
81
    def __init__(self, name, table=None):
82
        '''
83
        @param table Table|None (for no table)
84
        '''
85
        if util.is_str(table): table = Table(table)
86
        assert table == None or isinstance(table, Table)
87
        
88
        self.name = name
89
        self.table = table
90
    
91
    def to_str(self, db):
92
        str_ = ''
93
        if self.table != None: str_ += self.table.to_str(db)+'.'
94
        str_ += db.esc_name(self.name)
95
        return str_
96
    
97
    def to_Col(self): return self
98

    
99
def is_table_col(col): return col.table != None
100

    
101
def as_Col(col, table=None):
102
    assert col != None
103
    
104
    if isinstance(col, Code): return col
105
    else: return Col(col, table)
106

    
107
def to_name_only_col(col, check_table=None):
108
    col = as_Col(col)
109
    
110
    if check_table != None:
111
        table = col.table
112
        assert table == None or table == check_table
113
    return Col(col.name)
114

    
115
class NamedCol(Col):
116
    def __init__(self, name, code):
117
        Col.__init__(self, name)
118
        
119
        if not isinstance(code, Code): code = Literal(code)
120
        
121
        self.code = code
122
    
123
    def to_str(self, db):
124
        return self.code.to_str(db)+' AS '+Col.to_str(self, db)
125
    
126
    def to_Col(self): return Col(self.name)
127

    
128
def remove_col_rename(col):
129
    if isinstance(col, NamedCol): col = col.code
130
    return col
131

    
132
##### Conditions
133

    
134
class ColValueCond(Code):
135
    def __init__(self, col, value):
136
        value = as_ValueCond(value)
137
        
138
        self.col = col
139
        self.value = value
140
    
141
    def to_str(self, db): return self.value.to_str(db, self.col)
142

    
143
##### Condition column comparisons
144

    
145
class ValueCond(objects.BasicObject):
146
    def __init__(self, value):
147
        if not isinstance(value, Code): value = Literal(value)
148
        value = remove_col_rename(value)
149
        
150
        self.value = value
151
    
152
    def to_str(self, db, left_value):
153
        '''
154
        @param left_value The Code object that the condition is being applied on
155
        '''
156
        raise NotImplemented()
157
    
158
    def __str__(self): return self.to_str(mockDb, '<left_value>')
159

    
160
class CompareCond(ValueCond):
161
    def __init__(self, value, operator='='):
162
        '''
163
        @param operator By default, compares NULL values literally. Use '~=' or
164
            '~!=' to pass NULLs through.
165
        '''
166
        ValueCond.__init__(self, value)
167
        self.operator = operator
168
    
169
    def to_str(self, db, left_value):
170
        if not isinstance(left_value, Code): left_value = Col(left_value)
171
        left_value = remove_col_rename(left_value)
172
        
173
        right_value = self.value
174
        left = left_value.to_str(db)
175
        right = right_value.to_str(db)
176
        
177
        # Parse operator
178
        operator = self.operator
179
        passthru_null_ref = [False]
180
        operator = strings.remove_prefix('~', operator, passthru_null_ref)
181
        neg_ref = [False]
182
        operator = strings.remove_prefix('!', operator, neg_ref)
183
        equals = operator.endswith('=')
184
        if equals and is_null(self.value): operator = 'IS'
185
        
186
        # Create str
187
        str_ = left+' '+operator+' '+right
188
        if equals and not passthru_null_ref[0] and isinstance(right_value, Col):
189
            str_ += ' OR ('+left+' IS NULL AND '+right+' IS NULL)'
190
        if neg_ref[0]: str_ = 'NOT ('+str_+')'
191
        return str_
192

    
193
# Tells as_ValueCond() to assume a non-ValueCond is a literal value
194
assume_literal = object()
195

    
196
def as_ValueCond(value, default_table=assume_literal):
197
    if not isinstance(value, ValueCond):
198
        if default_table is not assume_literal:
199
            value = as_Col(value, default_table)
200
        return CompareCond(value)
201
    else: return value
202

    
203
##### Joins
204

    
205
join_same = object() # tells Join the left and right columns have the same name
206

    
207
# Tells Join the left and right columns have the same name and are never NULL
208
join_same_not_null = object()
209

    
210
filter_out = object() # tells Join to filter out rows that match the join
211

    
212
class Join(objects.BasicObject):
213
    def __init__(self, table, mapping, type_=None):
214
        '''
215
        @param mapping dict(right_table_col=left_table_col, ...)
216
            * if left_table_col is join_same: left_table_col = right_table_col
217
              * Note that right_table_col must be a string
218
            * if left_table_col is join_same_not_null:
219
              left_table_col = right_table_col and both have NOT NULL constraint
220
              * Note that right_table_col must be a string
221
        @param type_ None (for plain join)|str (e.g. 'LEFT')|filter_out
222
            * filter_out: equivalent to 'LEFT' with the query filtered by
223
              `table_pkey IS NULL` (indicating no match)
224
        '''
225
        if util.is_str(table): table = Table(table)
226
        assert type_ == None or util.is_str(type_) or type_ is filter_out
227
        
228
        self.table = table
229
        self.mapping = mapping
230
        self.type_ = type_
231
    
232
    def to_str(self, db, left_table):
233
        # Switch order (left_table is on the right in the comparison)
234
        right_table = left_table
235
        left_table = self.table # note left_table is reassigned
236
        
237
        def join(entry):
238
            '''Parses non-USING joins'''
239
            right_table_col, left_table_col = entry
240
            
241
            # Switch order (right_table_col is on the left in the comparison)
242
            left = right_table_col
243
            right = left_table_col
244
            
245
            # Parse special values
246
            if right is join_same: right = left
247
            elif right is join_same_not_null:
248
                right = CompareCond(as_Col(left, right_table), '~=')
249
            
250
            right = as_ValueCond(right, right_table)
251
            return '('+right.to_str(db, as_Col(left, left_table))+')'
252
        
253
        # Create join condition
254
        type_ = self.type_
255
        joins = self.mapping
256
        if type_ is not filter_out and reduce(operator.and_,
257
            (v is join_same_not_null for v in joins.itervalues())):
258
            # all cols w/ USING, so can use simpler USING syntax
259
            cols = (as_Col(v).to_str(db) for v in joins.iterkeys())
260
            join_cond = 'USING ('+(', '.join(cols))+')'
261
        else: join_cond = 'ON '+(' AND '.join(map(join, joins.iteritems())))
262
        
263
        # Create join
264
        if type_ is filter_out: type_ = 'LEFT'
265
        str_ = ''
266
        if type_ != None: str_ += type_+' '
267
        str_ += 'JOIN '+left_table.to_str(db)+' '+join_cond
268
        return str_
269
    
270
    def __str__(self): return self.to_str(mockDb, '<left_table>')
271

    
272
##### Value exprs
273

    
274
row_count = CustomCode('count(*)')
(24-24/35)