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): return sql.qual_name(db, self.schema, self.name)
39
    
40
    def to_Table(self): return self
41

    
42
def as_Table(table):
43
    if table == None or isinstance(table, Code): return table
44
    else: return Table(table)
45

    
46
class NamedTable(Table):
47
    def __init__(self, name, code, cols=None):
48
        Table.__init__(self, name)
49
        
50
        if not isinstance(code, Code): code = Table(code)
51
        
52
        self.code = code
53
        self.cols = cols
54
    
55
    def to_str(self, db):
56
        str_ = self.code.to_str(db)+' AS '+Table.to_str(self, db)
57
        if self.cols != None: str_ += ' ('+(', '.join(self.cols))+')'
58
        return str_
59
    
60
    def to_Table(self): return Table(self.name)
61

    
62
##### Columns
63

    
64
class Col(Code):
65
    def __init__(self, name, table=None):
66
        '''
67
        @param table Table|None (for no table)
68
        '''
69
        if util.is_str(table): table = Table(table)
70
        assert table == None or isinstance(table, Table)
71
        
72
        self.name = name
73
        self.table = table
74
    
75
    def to_str(self, db):
76
        str_ = ''
77
        if self.table != None: str_ += self.table.to_str(db)+'.'
78
        str_ += sql.esc_name(db, self.name)
79
        return str_
80
    
81
    def to_Col(self): return self
82

    
83
def as_Col(col, table=None):
84
    assert col != None
85
    
86
    if isinstance(col, Code): return col
87
    else: return Col(col, table)
88

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

    
102
##### Conditions
103

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

    
119
class CompareCond(ValueCond):
120
    def __init__(self, value, operator='='):
121
        '''
122
        @param operator By default, compares NULL values literally. Use '~=' or
123
            '~!=' to pass NULLs through.
124
        '''
125
        ValueCond.__init__(self, value)
126
        self.operator = operator
127
    
128
    def to_str(self, db, left_value):
129
        if not isinstance(left_value, Code): left_value = Col(left_value)
130
        
131
        right_value = self.value
132
        left = left_value.to_str(db)
133
        right = right_value.to_str(db)
134
        
135
        # Parse operator
136
        operator = self.operator
137
        passthru_null_ref = [False]
138
        operator = strings.remove_prefix('~', operator, passthru_null_ref)
139
        neg_ref = [False]
140
        operator = strings.remove_prefix('!', operator, neg_ref)
141
        equals = operator.endswith('=')
142
        if equals and is_null(self.value): operator = 'IS'
143
        
144
        # Create str
145
        str_ = left+' '+operator+' '+right
146
        if equals and not passthru_null_ref[0] and isinstance(right_value, Col):
147
            str_ += ' OR ('+left+' IS NULL AND '+right+' IS NULL)'
148
        if neg_ref[0]: str_ = 'NOT ('+str_+')'
149
        return str_
150

    
151
# Tells as_ValueCond() to assume a non-ValueCond is a literal value
152
assume_literal = object()
153

    
154
def as_ValueCond(value, default_table=assume_literal):
155
    if not isinstance(value, ValueCond):
156
        if default_table is not assume_literal:
157
            value = as_Col(value, default_table)
158
        return CompareCond(value)
159
    else: return value
160

    
161
##### Joins
162

    
163
join_using = object() # tells Join to join the column with USING
164

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

    
167
class Join(Code):
168
    def __init__(self, table, mapping, type_=None):
169
        '''
170
        @param mapping dict(right_table_col=left_table_col, ...)
171
            * if left_table_col is join_using: left_table_col = right_table_col
172
        @param type_ None (for plain join)|str (e.g. 'LEFT')|filter_out
173
            * filter_out: equivalent to 'LEFT' with the query filtered by
174
              `table_pkey IS NULL` (indicating no match)
175
        '''
176
        if util.is_str(table): table = Table(table)
177
        assert type_ == None or util.is_str(type_) or type_ is filter_out
178
        
179
        self.table = table
180
        self.mapping = mapping
181
        self.type_ = type_
182
    
183
    def to_str(self, db, left_table):
184
        def join(entry):
185
            '''Parses non-USING joins'''
186
            right_table_col, left_table_col = entry
187
            # Note that right_table_col is on the left in the comparison
188
            
189
            # Parse special values
190
            if left_table_col is join_using: left_table_col = right_table_col
191
            
192
            cond = as_ValueCond(left_table_col, left_table)
193
            return cond.to_str(db, as_Col(right_table_col, self.table))
194
        
195
        # Create join condition
196
        type_ = self.type_
197
        joins = self.mapping
198
        if type_ is not filter_out and reduce(operator.and_,
199
            (v is join_using for v in joins.itervalues())):
200
            # all cols w/ USING, so can use simpler USING syntax
201
            cols = (as_Col(v).to_str(db) for v in joins.iterkeys())
202
            join_cond = 'USING ('+(', '.join(cols))+')'
203
        else: join_cond = 'ON '+(' AND '.join(map(join, joins.iteritems())))
204
        
205
        # Create join
206
        if type_ is filter_out: type_ = 'LEFT'
207
        str_ = ''
208
        if type_ != None: str_ += type_+' '
209
        str_ += 'JOIN '+self.table.to_str(db)+' '+join_cond
210
        return str_
(23-23/34)