Project

General

Profile

1 2211 aaronmk
# SQL code generation
2
3
import sql
4 2222 aaronmk
import strings
5 2227 aaronmk
import util
6 2211 aaronmk
7 2219 aaronmk
##### SQL code objects
8
9 2211 aaronmk
class Code:
10
    def to_str(self, db): raise NotImplemented()
11 2228 aaronmk
12
    def __str__(self): return str(self.__dict__)
13 2211 aaronmk
14 2256 aaronmk
class CustomCode:
15
    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
    if table == None or isinstance(table, Table): return table
38
    elif isinstance(table, tuple):
39
        schema, table = table
40
        return Table(table, schema)
41
    else: return Table(table)
42
43 2211 aaronmk
class Col(Code):
44
    def __init__(self, name, table=None):
45
        '''
46
        @param table Table|None (for no table)
47
        '''
48 2241 aaronmk
        if util.is_str(table): table = Table(table)
49 2211 aaronmk
        assert table == None or isinstance(table, Table)
50
51
        self.name = name
52
        self.table = table
53
54
    def to_str(self, db):
55
        str_ = ''
56
        if self.table != None: str_ += self.table.to_str(db)+'.'
57
        str_ += sql.esc_name(db, self.name)
58
        return str_
59
60 2229 aaronmk
class NamedCode(Code):
61
    def __init__(self, name, code):
62
        if not isinstance(code, Code): code = Literal(code)
63
64
        self.name = name
65
        self.code = code
66
67
    def to_str(self, db):
68
        return self.code.to_str(db)+' AS '+sql.esc_name(db, self.name)
69
70 2214 aaronmk
class ValueCond:
71 2213 aaronmk
    def __init__(self, value):
72 2225 aaronmk
        if not isinstance(value, Code): value = Literal(value)
73 2213 aaronmk
74
        self.value = value
75 2214 aaronmk
76 2216 aaronmk
    def to_str(self, db, left_value):
77 2214 aaronmk
        '''
78 2216 aaronmk
        @param left_value The Code object that the condition is being applied on
79 2214 aaronmk
        '''
80
        raise NotImplemented()
81 2228 aaronmk
82
    def __str__(self): return str(self.__dict__)
83 2211 aaronmk
84
class CompareCond(ValueCond):
85
    def __init__(self, value, operator='='):
86 2222 aaronmk
        '''
87
        @param operator By default, compares NULL values literally. Use '~=' or
88
            '~!=' to pass NULLs through.
89
        '''
90 2211 aaronmk
        ValueCond.__init__(self, value)
91
        self.operator = operator
92
93 2216 aaronmk
    def to_str(self, db, left_value):
94
        if not isinstance(left_value, Code): left_value = Col(left_value)
95
96 2222 aaronmk
        right_value = self.value
97
        left = left_value.to_str(db)
98
        right = right_value.to_str(db)
99
100
        # Parse operator
101 2216 aaronmk
        operator = self.operator
102 2222 aaronmk
        passthru_null_ref = [False]
103
        operator = strings.remove_prefix('~', operator, passthru_null_ref)
104
        neg_ref = [False]
105
        operator = strings.remove_prefix('!', operator, neg_ref)
106
        equals = operator.endswith('=')
107
        if equals and is_null(self.value): operator = 'IS'
108
109
        # Create str
110
        str_ = left+' '+operator+' '+right
111
        if equals and not passthru_null_ref[0] and isinstance(right_value, Col):
112
            str_ += ' OR ('+left+' IS NULL AND '+right+' IS NULL)'
113
        if neg_ref[0]: str_ = 'NOT ('+str_+')'
114
        return str_
115 2216 aaronmk
116
def as_ValueCond(value):
117
    if not isinstance(value, ValueCond): return CompareCond(value)
118
    else: return value
119 2219 aaronmk
120
##### Old-style format support
121
122
def unescape_table(table):
123
    '''Currently only works with PostgreSQL.'''
124
    if table == None: return table
125
126
    assert table.count('.') <= 1
127
    parts = tuple((v.replace('"', '') for v in table.split('"."', 2)))
128
    if len(parts) == 1: parts, = parts
129
    return parts
130
131 2223 aaronmk
def col2sql_gen(col, default_table=None, table_is_esc=False):
132
    '''Converts old-style (tuple-based) columns to sql_gen-compatible columns.
133
    @param table_is_esc If False, assumes any table name is not escaped or that
134
        re-escaping it will produce the same value.
135
    '''
136
    if isinstance(col, Col): return col # already in sql_gen form
137
138
    table = default_table
139
    if isinstance(col, tuple): table, col = col
140
    if table_is_esc: table = unescape_table(table)
141
    return Col(col, as_Table(table))
142
143 2227 aaronmk
def value2sql_gen(value, default_table=None, table_is_esc=False,
144
    assume_col=False):
145 2219 aaronmk
    '''Converts old-style (tuple-based) values to sql_gen-compatible values.
146
    @param table_is_esc If False, assumes any table name is not escaped or that
147
        re-escaping it will produce the same value.
148
    '''
149
    if isinstance(value, Code): return value # already in sql_gen form
150
151 2227 aaronmk
    is_tuple = isinstance(value, tuple)
152
    if is_tuple and len(value) == 1: return Literal(value[0])
153
    if is_tuple or (assume_col and util.is_str(value)):
154
        return col2sql_gen(value, default_table, table_is_esc)
155
    else: return Literal(value)
156 2225 aaronmk
157 2237 aaronmk
def cond2sql_gen(value, default_table=None, table_is_esc=False,
158
    assume_col=False):
159 2225 aaronmk
    '''Converts old-style (tuple-based) conditions to sql_gen-compatible values.
160
    @param table_is_esc If False, assumes any table name is not escaped or that
161
        re-escaping it will produce the same value.
162
    '''
163
    if isinstance(value, ValueCond): return value # already in sql_gen form
164
165 2237 aaronmk
    return as_ValueCond(value2sql_gen(value, default_table, table_is_esc,
166
        assume_col))