Project

General

Profile

1 2211 aaronmk
# SQL code generation
2
3 2276 aaronmk
import operator
4
5 2211 aaronmk
import sql
6 2222 aaronmk
import strings
7 2227 aaronmk
import util
8 2211 aaronmk
9 2219 aaronmk
##### SQL code objects
10
11 2302 aaronmk
class Code(strings.DebugPrintable):
12 2211 aaronmk
    def to_str(self, db): raise NotImplemented()
13
14 2269 aaronmk
class CustomCode(Code):
15 2256 aaronmk
    def __init__(self, str_): self.str_ = str_
16
17
    def to_str(self, db): return self.str_
18
19 2216 aaronmk
class Literal(Code):
20 2211 aaronmk
    def __init__(self, value): self.value = value
21 2213 aaronmk
22
    def to_str(self, db): return db.esc_value(self.value)
23 2211 aaronmk
24 2216 aaronmk
def is_null(value): return isinstance(value, Literal) and value.value == None
25
26 2211 aaronmk
class Table(Code):
27
    def __init__(self, name, schema=None):
28
        '''
29
        @param schema str|None (for no schema)
30
        '''
31
        self.name = name
32
        self.schema = schema
33
34
    def to_str(self, db): return sql.qual_name(db, self.schema, self.name)
35
36 2219 aaronmk
def as_Table(table):
37 2270 aaronmk
    if table == None or isinstance(table, Code): return table
38 2219 aaronmk
    else: return Table(table)
39
40 2211 aaronmk
class Col(Code):
41
    def __init__(self, name, table=None):
42
        '''
43
        @param table Table|None (for no table)
44
        '''
45 2241 aaronmk
        if util.is_str(table): table = Table(table)
46 2211 aaronmk
        assert table == None or isinstance(table, Table)
47
48
        self.name = name
49
        self.table = table
50
51
    def to_str(self, db):
52
        str_ = ''
53
        if self.table != None: str_ += self.table.to_str(db)+'.'
54
        str_ += sql.esc_name(db, self.name)
55
        return str_
56
57 2260 aaronmk
def as_Col(col, table=None):
58
    if col == None or isinstance(col, Code): return col
59
    else: return Col(col, table)
60
61 2310 aaronmk
class NamedCode(Col):
62 2229 aaronmk
    def __init__(self, name, code):
63 2310 aaronmk
        Col.__init__(self, name)
64
65 2229 aaronmk
        if not isinstance(code, Code): code = Literal(code)
66
67
        self.code = code
68
69
    def to_str(self, db):
70 2310 aaronmk
        return self.code.to_str(db)+' AS '+Col.to_str(self, db)
71 2229 aaronmk
72 2259 aaronmk
##### Parameterized SQL code objects
73
74 2214 aaronmk
class ValueCond:
75 2213 aaronmk
    def __init__(self, value):
76 2225 aaronmk
        if not isinstance(value, Code): value = Literal(value)
77 2213 aaronmk
78
        self.value = value
79 2214 aaronmk
80 2216 aaronmk
    def to_str(self, db, left_value):
81 2214 aaronmk
        '''
82 2216 aaronmk
        @param left_value The Code object that the condition is being applied on
83 2214 aaronmk
        '''
84
        raise NotImplemented()
85 2228 aaronmk
86
    def __str__(self): return str(self.__dict__)
87 2211 aaronmk
88
class CompareCond(ValueCond):
89
    def __init__(self, value, operator='='):
90 2222 aaronmk
        '''
91
        @param operator By default, compares NULL values literally. Use '~=' or
92
            '~!=' to pass NULLs through.
93
        '''
94 2211 aaronmk
        ValueCond.__init__(self, value)
95
        self.operator = operator
96
97 2216 aaronmk
    def to_str(self, db, left_value):
98
        if not isinstance(left_value, Code): left_value = Col(left_value)
99
100 2222 aaronmk
        right_value = self.value
101
        left = left_value.to_str(db)
102
        right = right_value.to_str(db)
103
104
        # Parse operator
105 2216 aaronmk
        operator = self.operator
106 2222 aaronmk
        passthru_null_ref = [False]
107
        operator = strings.remove_prefix('~', operator, passthru_null_ref)
108
        neg_ref = [False]
109
        operator = strings.remove_prefix('!', operator, neg_ref)
110
        equals = operator.endswith('=')
111
        if equals and is_null(self.value): operator = 'IS'
112
113
        # Create str
114
        str_ = left+' '+operator+' '+right
115
        if equals and not passthru_null_ref[0] and isinstance(right_value, Col):
116
            str_ += ' OR ('+left+' IS NULL AND '+right+' IS NULL)'
117
        if neg_ref[0]: str_ = 'NOT ('+str_+')'
118
        return str_
119 2216 aaronmk
120 2260 aaronmk
# Tells as_ValueCond() to assume a non-ValueCond is a literal value
121
assume_literal = object()
122
123
def as_ValueCond(value, default_table=assume_literal):
124
    if not isinstance(value, ValueCond):
125
        if default_table is not assume_literal:
126
            value = as_Col(value, default_table)
127
        return CompareCond(value)
128 2216 aaronmk
    else: return value
129 2219 aaronmk
130 2260 aaronmk
join_using = object() # tells Join to join the column with USING
131
132
filter_out = object() # tells Join to filter out rows that match the join
133
134
class Join(Code):
135
    def __init__(self, table, mapping, type_=None):
136
        '''
137
        @param mapping dict(right_table_col=left_table_col, ...)
138
            * if left_table_col is join_using: left_table_col = right_table_col
139
        @param type_ None (for plain join)|str (e.g. 'LEFT')|filter_out
140
            * filter_out: equivalent to 'LEFT' with the query filtered by
141
              `table_pkey IS NULL` (indicating no match)
142
        '''
143
        if util.is_str(table): table = Table(table)
144
        assert type_ == None or util.is_str(type_) or type_ is filter_out
145
146
        self.table = table
147
        self.mapping = mapping
148
        self.type_ = type_
149
150
    def to_str(self, db, left_table):
151
        def join(entry):
152
            '''Parses non-USING joins'''
153
            right_table_col, left_table_col = entry
154 2304 aaronmk
            # Note that right_table_col is on the left in the comparison
155 2260 aaronmk
156
            # Parse special values
157
            if left_table_col is join_using: left_table_col = right_table_col
158
159 2304 aaronmk
            cond = as_ValueCond(left_table_col, left_table)
160
            return cond.to_str(db, as_Col(right_table_col, self.table))
161 2260 aaronmk
162 2265 aaronmk
        # Create join condition
163
        type_ = self.type_
164 2276 aaronmk
        joins = self.mapping
165 2265 aaronmk
        if type_ is not filter_out and reduce(operator.and_,
166
            (v is join_using for v in joins.itervalues())):
167 2260 aaronmk
            # all cols w/ USING, so can use simpler USING syntax
168 2298 aaronmk
            cols = (as_Col(v).to_str(db) for v in joins.iterkeys())
169
            join_cond = 'USING ('+(', '.join(cols))+')'
170 2260 aaronmk
        else: join_cond = 'ON '+(' AND '.join(map(join, joins.iteritems())))
171
172
        # Create join
173
        if type_ is filter_out: type_ = 'LEFT'
174 2266 aaronmk
        str_ = ''
175
        if type_ != None: str_ += type_+' '
176 2276 aaronmk
        str_ += 'JOIN '+self.table.to_str(db)+' '+join_cond
177 2266 aaronmk
        return str_