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