Project

General

Profile

1
# SQL code generation
2

    
3
import sql
4

    
5
class Code:
6
    def to_str(self, db): raise NotImplemented()
7

    
8
class Literal(Code):
9
    def __init__(self, value): self.value = value
10
    
11
    def to_str(self, db): return db.esc_value(self.value)
12

    
13
def is_null(value): return isinstance(value, Literal) and value.value == None
14

    
15
class Table(Code):
16
    def __init__(self, name, schema=None):
17
        '''
18
        @param schema str|None (for no schema)
19
        '''
20
        self.name = name
21
        self.schema = schema
22
    
23
    def to_str(self, db): return sql.qual_name(db, self.schema, self.name)
24

    
25
class Col(Code):
26
    def __init__(self, name, table=None):
27
        '''
28
        @param table Table|None (for no table)
29
        '''
30
        assert table == None or isinstance(table, Table)
31
        
32
        self.name = name
33
        self.table = table
34
    
35
    def to_str(self, db):
36
        str_ = ''
37
        if self.table != None: str_ += self.table.to_str(db)+'.'
38
        str_ += sql.esc_name(db, self.name)
39
        return str_
40

    
41
class ValueCond:
42
    def __init__(self, value):
43
        if not isinstance(value, Literal): value = Literal(value)
44
        
45
        self.value = value
46
    
47
    def to_str(self, db, left_value):
48
        '''
49
        @param left_value The Code object that the condition is being applied on
50
        '''
51
        raise NotImplemented()
52

    
53
class CompareCond(ValueCond):
54
    def __init__(self, value, operator='='):
55
        ValueCond.__init__(self, value)
56
        self.operator = operator
57
    
58
    def to_str(self, db, left_value):
59
        if not isinstance(left_value, Code): left_value = Col(left_value)
60
        
61
        operator = self.operator
62
        if is_null(self.value): operator = 'IS'
63
        return left_value.to_str(db)+' '+operator+' '+self.value.to_str(db)
64

    
65
def as_ValueCond(value):
66
    if not isinstance(value, ValueCond): return CompareCond(value)
67
    else: return value
(23-23/34)