Project

General

Profile

1
# SQL code generation
2

    
3
import sql
4
import strings
5
import util
6

    
7
##### SQL code objects
8

    
9
class Code:
10
    def to_str(self, db): raise NotImplemented()
11
    
12
    def __str__(self): return str(self.__dict__)
13

    
14
class CustomCode:
15
    def __init__(self, str_): self.str_ = str_
16
    
17
    def to_str(self, db): return self.str_
18

    
19
class Literal(Code):
20
    def __init__(self, value): self.value = value
21
    
22
    def to_str(self, db): return db.esc_value(self.value)
23

    
24
def is_null(value): return isinstance(value, Literal) and value.value == None
25

    
26
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
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
class Col(Code):
44
    def __init__(self, name, table=None):
45
        '''
46
        @param table Table|None (for no table)
47
        '''
48
        if util.is_str(table): table = Table(table)
49
        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
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
class ValueCond:
71
    def __init__(self, value):
72
        if not isinstance(value, Code): value = Literal(value)
73
        
74
        self.value = value
75
    
76
    def to_str(self, db, left_value):
77
        '''
78
        @param left_value The Code object that the condition is being applied on
79
        '''
80
        raise NotImplemented()
81
    
82
    def __str__(self): return str(self.__dict__)
83

    
84
class CompareCond(ValueCond):
85
    def __init__(self, value, operator='='):
86
        '''
87
        @param operator By default, compares NULL values literally. Use '~=' or
88
            '~!=' to pass NULLs through.
89
        '''
90
        ValueCond.__init__(self, value)
91
        self.operator = operator
92
    
93
    def to_str(self, db, left_value):
94
        if not isinstance(left_value, Code): left_value = Col(left_value)
95
        
96
        right_value = self.value
97
        left = left_value.to_str(db)
98
        right = right_value.to_str(db)
99
        
100
        # Parse operator
101
        operator = self.operator
102
        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

    
116
def as_ValueCond(value):
117
    if not isinstance(value, ValueCond): return CompareCond(value)
118
    else: return value
119

    
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
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
def value2sql_gen(value, default_table=None, table_is_esc=False,
144
    assume_col=False):
145
    '''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
    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

    
157
def cond2sql_gen(value, default_table=None, table_is_esc=False,
158
    assume_col=False):
159
    '''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
    return as_ValueCond(value2sql_gen(value, default_table, table_is_esc,
166
        assume_col))
(23-23/34)