Project

General

Profile

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 is_null(value): return isinstance(value, Literal) and value.value == None
36

    
37
##### Tables
38

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

    
55
def as_Table(table):
56
    if table == None or isinstance(table, Code): return table
57
    else: return Table(table)
58

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

    
75
##### Columns
76

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

    
96
def is_table_col(col): return col.table != None
97

    
98
def as_Col(col, table=None):
99
    assert col != None
100
    
101
    if isinstance(col, Code): return col
102
    else: return Col(col, table)
103

    
104
class NamedCol(Col):
105
    def __init__(self, name, code):
106
        Col.__init__(self, name)
107
        
108
        if not isinstance(code, Code): code = Literal(code)
109
        
110
        self.code = code
111
    
112
    def to_str(self, db):
113
        return self.code.to_str(db)+' AS '+Col.to_str(self, db)
114
    
115
    def to_Col(self): return Col(self.name)
116

    
117
##### Conditions
118

    
119
class ColValueCond(Code):
120
    def __init__(self, col, value):
121
        value = as_ValueCond(value)
122
        
123
        self.col = col
124
        self.value = value
125
    
126
    def to_str(self, db): return self.value.to_str(db, self.col)
127

    
128
##### Condition column comparisons
129

    
130
class ValueCond(objects.BasicObject):
131
    def __init__(self, value):
132
        if not isinstance(value, Code): value = Literal(value)
133
        if isinstance(value, NamedCol): value = value.code
134
        
135
        self.value = value
136
    
137
    def to_str(self, db, left_value):
138
        '''
139
        @param left_value The Code object that the condition is being applied on
140
        '''
141
        raise NotImplemented()
142
    
143
    def __str__(self): return self.to_str(mockDb, '<left_value>')
144

    
145
class CompareCond(ValueCond):
146
    def __init__(self, value, operator='='):
147
        '''
148
        @param operator By default, compares NULL values literally. Use '~=' or
149
            '~!=' to pass NULLs through.
150
        '''
151
        ValueCond.__init__(self, value)
152
        self.operator = operator
153
    
154
    def to_str(self, db, left_value):
155
        if not isinstance(left_value, Code): left_value = Col(left_value)
156
        
157
        right_value = self.value
158
        left = left_value.to_str(db)
159
        right = right_value.to_str(db)
160
        
161
        # Parse operator
162
        operator = self.operator
163
        passthru_null_ref = [False]
164
        operator = strings.remove_prefix('~', operator, passthru_null_ref)
165
        neg_ref = [False]
166
        operator = strings.remove_prefix('!', operator, neg_ref)
167
        equals = operator.endswith('=')
168
        if equals and is_null(self.value): operator = 'IS'
169
        
170
        # Create str
171
        str_ = left+' '+operator+' '+right
172
        if equals and not passthru_null_ref[0] and isinstance(right_value, Col):
173
            str_ += ' OR ('+left+' IS NULL AND '+right+' IS NULL)'
174
        if neg_ref[0]: str_ = 'NOT ('+str_+')'
175
        return str_
176

    
177
# Tells as_ValueCond() to assume a non-ValueCond is a literal value
178
assume_literal = object()
179

    
180
def as_ValueCond(value, default_table=assume_literal):
181
    if not isinstance(value, ValueCond):
182
        if default_table is not assume_literal:
183
            value = as_Col(value, default_table)
184
        return CompareCond(value)
185
    else: return value
186

    
187
##### Joins
188

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

    
191
# Tells Join the left and right columns have the same name and are never NULL
192
join_same_not_null = object()
193

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

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