Project

General

Profile

1 2211 aaronmk
# SQL code generation
2
3
import sql
4
5
class Code:
6
    def to_str(self, db): raise NotImplemented()
7
8 2216 aaronmk
class Literal(Code):
9 2211 aaronmk
    def __init__(self, value): self.value = value
10 2213 aaronmk
11
    def to_str(self, db): return db.esc_value(self.value)
12 2211 aaronmk
13 2216 aaronmk
def is_null(value): return isinstance(value, Literal) and value.value == None
14
15 2211 aaronmk
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 2214 aaronmk
class ValueCond:
42 2213 aaronmk
    def __init__(self, value):
43
        if not isinstance(value, Literal): value = Literal(value)
44
45
        self.value = value
46 2214 aaronmk
47 2216 aaronmk
    def to_str(self, db, left_value):
48 2214 aaronmk
        '''
49 2216 aaronmk
        @param left_value The Code object that the condition is being applied on
50 2214 aaronmk
        '''
51
        raise NotImplemented()
52 2211 aaronmk
53
class CompareCond(ValueCond):
54
    def __init__(self, value, operator='='):
55
        ValueCond.__init__(self, value)
56
        self.operator = operator
57
58 2216 aaronmk
    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