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:
12
    def to_str(self, db): raise NotImplemented()
13
    
14
    def __str__(self): return str(self.__dict__)
15

    
16
class CustomCode(Code):
17
    def __init__(self, str_): self.str_ = str_
18
    
19
    def to_str(self, db): return self.str_
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
class Table(Code):
29
    def __init__(self, name, schema=None):
30
        '''
31
        @param schema str|None (for no schema)
32
        '''
33
        self.name = name
34
        self.schema = schema
35
    
36
    def to_str(self, db): return sql.qual_name(db, self.schema, self.name)
37

    
38
def as_Table(table):
39
    if table == None or isinstance(table, Code): return table
40
    else: return Table(table)
41

    
42
class Col(Code):
43
    def __init__(self, name, table=None):
44
        '''
45
        @param table Table|None (for no table)
46
        '''
47
        if util.is_str(table): table = Table(table)
48
        assert table == None or isinstance(table, Table)
49
        
50
        self.name = name
51
        self.table = table
52
    
53
    def to_str(self, db):
54
        str_ = ''
55
        if self.table != None: str_ += self.table.to_str(db)+'.'
56
        str_ += sql.esc_name(db, self.name)
57
        return str_
58

    
59
def as_Col(col, table=None):
60
    if col == None or isinstance(col, Code): return col
61
    else: return Col(col, table)
62

    
63
class NamedCode(Code):
64
    def __init__(self, name, code):
65
        if not isinstance(code, Code): code = Literal(code)
66
        
67
        self.name = name
68
        self.code = code
69
    
70
    def to_str(self, db):
71
        return self.code.to_str(db)+' AS '+sql.esc_name(db, self.name)
72

    
73
##### Parameterized SQL code objects
74

    
75
class ValueCond:
76
    def __init__(self, value):
77
        if not isinstance(value, Code): value = Literal(value)
78
        
79
        self.value = value
80
    
81
    def to_str(self, db, left_value):
82
        '''
83
        @param left_value The Code object that the condition is being applied on
84
        '''
85
        raise NotImplemented()
86
    
87
    def __str__(self): return str(self.__dict__)
88

    
89
class CompareCond(ValueCond):
90
    def __init__(self, value, operator='='):
91
        '''
92
        @param operator By default, compares NULL values literally. Use '~=' or
93
            '~!=' to pass NULLs through.
94
        '''
95
        ValueCond.__init__(self, value)
96
        self.operator = operator
97
    
98
    def to_str(self, db, left_value):
99
        if not isinstance(left_value, Code): left_value = Col(left_value)
100
        
101
        right_value = self.value
102
        left = left_value.to_str(db)
103
        right = right_value.to_str(db)
104
        
105
        # Parse operator
106
        operator = self.operator
107
        passthru_null_ref = [False]
108
        operator = strings.remove_prefix('~', operator, passthru_null_ref)
109
        neg_ref = [False]
110
        operator = strings.remove_prefix('!', operator, neg_ref)
111
        equals = operator.endswith('=')
112
        if equals and is_null(self.value): operator = 'IS'
113
        
114
        # Create str
115
        str_ = left+' '+operator+' '+right
116
        if equals and not passthru_null_ref[0] and isinstance(right_value, Col):
117
            str_ += ' OR ('+left+' IS NULL AND '+right+' IS NULL)'
118
        if neg_ref[0]: str_ = 'NOT ('+str_+')'
119
        return str_
120

    
121
# Tells as_ValueCond() to assume a non-ValueCond is a literal value
122
assume_literal = object()
123

    
124
def as_ValueCond(value, default_table=assume_literal):
125
    if not isinstance(value, ValueCond):
126
        if default_table is not assume_literal:
127
            value = as_Col(value, default_table)
128
        return CompareCond(value)
129
    else: return value
130

    
131
join_using = object() # tells Join to join the column with USING
132

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

    
135
class Join(Code):
136
    def __init__(self, table, mapping, type_=None):
137
        '''
138
        @param mapping dict(right_table_col=left_table_col, ...)
139
            * if left_table_col is join_using: left_table_col = right_table_col
140
        @param type_ None (for plain join)|str (e.g. 'LEFT')|filter_out
141
            * filter_out: equivalent to 'LEFT' with the query filtered by
142
              `table_pkey IS NULL` (indicating no match)
143
        '''
144
        if util.is_str(table): table = Table(table)
145
        assert type_ == None or util.is_str(type_) or type_ is filter_out
146
        
147
        self.table = table
148
        self.mapping = mapping
149
        self.type_ = type_
150
    
151
    def to_str(self, db, left_table):
152
        def join(entry):
153
            '''Parses non-USING joins'''
154
            right_table_col, left_table_col = entry
155
            
156
            # Parse special values
157
            if left_table_col is join_using: left_table_col = right_table_col
158
            
159
            cond = as_ValueCond(right_table_col, self.table)
160
            return cond.to_str(db, as_Col(left_table_col, left_table))
161
        
162
        # Create join condition
163
        type_ = self.type_
164
        joins = self.mapping
165
        if type_ is not filter_out and reduce(operator.and_,
166
            (v is join_using for v in joins.itervalues())):
167
            # all cols w/ USING, so can use simpler USING syntax
168
            cols = (as_Col(v).to_str(db) for v in joins.iterkeys())
169
            join_cond = 'USING ('+(', '.join(cols))+')'
170
        else: join_cond = 'ON '+(' AND '.join(map(join, joins.iteritems())))
171
        
172
        # Create join
173
        if type_ is filter_out: type_ = 'LEFT'
174
        str_ = ''
175
        if type_ != None: str_ += type_+' '
176
        str_ += 'JOIN '+self.table.to_str(db)+' '+join_cond
177
        return str_
(23-23/34)