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 Literal(Code):
15
    def __init__(self, value): self.value = value
16
    
17
    def to_str(self, db): return db.esc_value(self.value)
18

    
19
def is_null(value): return isinstance(value, Literal) and value.value == None
20

    
21
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
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
class Col(Code):
39
    def __init__(self, name, table=None):
40
        '''
41
        @param table Table|None (for no table)
42
        '''
43
        if util.is_str(table): table = Table(table)
44
        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
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
class ValueCond:
66
    def __init__(self, value):
67
        if not isinstance(value, Code): value = Literal(value)
68
        
69
        self.value = value
70
    
71
    def to_str(self, db, left_value):
72
        '''
73
        @param left_value The Code object that the condition is being applied on
74
        '''
75
        raise NotImplemented()
76
    
77
    def __str__(self): return str(self.__dict__)
78

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

    
111
def as_ValueCond(value):
112
    if not isinstance(value, ValueCond): return CompareCond(value)
113
    else: return value
114

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

    
152
def cond2sql_gen(value, default_table=None, table_is_esc=False,
153
    assume_col=False):
154
    '''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
    return as_ValueCond(value2sql_gen(value, default_table, table_is_esc,
161
        assume_col))
(23-23/34)