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 util.class_name(self)+repr(self.__dict__)
15
    
16
    def __repr__(self): return str(self)
17

    
18
class CustomCode(Code):
19
    def __init__(self, str_): self.str_ = str_
20
    
21
    def to_str(self, db): return self.str_
22

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

    
28
def is_null(value): return isinstance(value, Literal) and value.value == None
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 as_Table(table):
41
    if table == None or isinstance(table, Code): return table
42
    else: return Table(table)
43

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

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

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

    
75
##### Parameterized SQL code objects
76

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

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

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

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

    
133
join_using = object() # tells Join to join the column with USING
134

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

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