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