Project

General

Profile

1
# SQL code generation
2

    
3
import operator
4

    
5
import sql
6
import strings
7
import util
8

    
9
##### SQL code objects
10

    
11
class Code(strings.DebugPrintable):
12
    def to_str(self, db): raise NotImplemented()
13

    
14
class CustomCode(Code):
15
    def __init__(self, str_): self.str_ = str_
16
    
17
    def to_str(self, db): return self.str_
18

    
19
##### Literal values
20

    
21
class Literal(Code):
22
    def __init__(self, value): self.value = value
23
    
24
    def to_str(self, db): return db.esc_value(self.value)
25

    
26
def is_null(value): return isinstance(value, Literal) and value.value == None
27

    
28
##### Tables
29

    
30
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
    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
    
44
    def to_Table(self): return self
45

    
46
def as_Table(table):
47
    if table == None or isinstance(table, Code): return table
48
    else: return Table(table)
49

    
50
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
##### Columns
67

    
68
class Col(Code):
69
    def __init__(self, name, table=None):
70
        '''
71
        @param table Table|None (for no table)
72
        '''
73
        if util.is_str(table): table = Table(table)
74
        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
        str_ += db.esc_name(self.name)
83
        return str_
84
    
85
    def to_Col(self): return self
86

    
87
def as_Col(col, table=None):
88
    assert col != None
89
    
90
    if isinstance(col, Code): return col
91
    else: return Col(col, table)
92

    
93
class NamedCol(Col):
94
    def __init__(self, name, code):
95
        Col.__init__(self, name)
96
        
97
        if not isinstance(code, Code): code = Literal(code)
98
        
99
        self.code = code
100
    
101
    def to_str(self, db):
102
        return self.code.to_str(db)+' AS '+Col.to_str(self, db)
103
    
104
    def to_Col(self): return Col(self.name)
105

    
106
##### Conditions
107

    
108
class ValueCond:
109
    def __init__(self, value):
110
        if not isinstance(value, Code): value = Literal(value)
111
        if isinstance(value, NamedCol): value = value.code
112
        
113
        self.value = value
114
    
115
    def to_str(self, db, left_value):
116
        '''
117
        @param left_value The Code object that the condition is being applied on
118
        '''
119
        raise NotImplemented()
120
    
121
    def __str__(self): return str(self.__dict__)
122

    
123
class CompareCond(ValueCond):
124
    def __init__(self, value, operator='='):
125
        '''
126
        @param operator By default, compares NULL values literally. Use '~=' or
127
            '~!=' to pass NULLs through.
128
        '''
129
        ValueCond.__init__(self, value)
130
        self.operator = operator
131
    
132
    def to_str(self, db, left_value):
133
        if not isinstance(left_value, Code): left_value = Col(left_value)
134
        
135
        right_value = self.value
136
        left = left_value.to_str(db)
137
        right = right_value.to_str(db)
138
        
139
        # Parse operator
140
        operator = self.operator
141
        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

    
155
# 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
    else: return value
164

    
165
##### Joins
166

    
167
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
            # Note that right_table_col is on the left in the comparison
192
            
193
            # Parse special values
194
            if left_table_col is join_using: left_table_col = right_table_col
195
            
196
            cond = as_ValueCond(left_table_col, left_table)
197
            return cond.to_str(db, as_Col(right_table_col, self.table))
198
        
199
        # Create join condition
200
        type_ = self.type_
201
        joins = self.mapping
202
        if type_ is not filter_out and reduce(operator.and_,
203
            (v is join_using for v in joins.itervalues())):
204
            # all cols w/ USING, so can use simpler USING syntax
205
            cols = (as_Col(v).to_str(db) for v in joins.iterkeys())
206
            join_cond = 'USING ('+(', '.join(cols))+')'
207
        else: join_cond = 'ON '+(' AND '.join(map(join, joins.iteritems())))
208
        
209
        # Create join
210
        if type_ is filter_out: type_ = 'LEFT'
211
        str_ = ''
212
        if type_ != None: str_ += type_+' '
213
        str_ += 'JOIN '+self.table.to_str(db)+' '+join_cond
214
        return str_
(23-23/34)