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 ValueCond(objects.BasicObject):
120
    def __init__(self, value):
121
        if not isinstance(value, Code): value = Literal(value)
122
        if isinstance(value, NamedCol): value = value.code
123
        
124
        self.value = value
125
    
126
    def to_str(self, db, left_value):
127
        '''
128
        @param left_value The Code object that the condition is being applied on
129
        '''
130
        raise NotImplemented()
131
    
132
    def __str__(self): return self.to_str(mockDb, '<left_value>')
133

    
134
class CompareCond(ValueCond):
135
    def __init__(self, value, operator='='):
136
        '''
137
        @param operator By default, compares NULL values literally. Use '~=' or
138
            '~!=' to pass NULLs through.
139
        '''
140
        ValueCond.__init__(self, value)
141
        self.operator = operator
142
    
143
    def to_str(self, db, left_value):
144
        if not isinstance(left_value, Code): left_value = Col(left_value)
145
        
146
        right_value = self.value
147
        left = left_value.to_str(db)
148
        right = right_value.to_str(db)
149
        
150
        # Parse operator
151
        operator = self.operator
152
        passthru_null_ref = [False]
153
        operator = strings.remove_prefix('~', operator, passthru_null_ref)
154
        neg_ref = [False]
155
        operator = strings.remove_prefix('!', operator, neg_ref)
156
        equals = operator.endswith('=')
157
        if equals and is_null(self.value): operator = 'IS'
158
        
159
        # Create str
160
        str_ = left+' '+operator+' '+right
161
        if equals and not passthru_null_ref[0] and isinstance(right_value, Col):
162
            str_ += ' OR ('+left+' IS NULL AND '+right+' IS NULL)'
163
        if neg_ref[0]: str_ = 'NOT ('+str_+')'
164
        return str_
165

    
166
# Tells as_ValueCond() to assume a non-ValueCond is a literal value
167
assume_literal = object()
168

    
169
def as_ValueCond(value, default_table=assume_literal):
170
    if not isinstance(value, ValueCond):
171
        if default_table is not assume_literal:
172
            value = as_Col(value, default_table)
173
        return CompareCond(value)
174
    else: return value
175

    
176
##### Joins
177

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

    
180
# Tells Join the left and right columns have the same name and are never NULL
181
join_same_not_null = object()
182

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

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