Project

General

Profile

« Previous | Next » 

Revision 2219

sql_gen.py: Added as_Table(), unescape_table(), value2sql_gen()

View differences:

lib/sql_gen.py
2 2

  
3 3
import sql
4 4

  
5
##### SQL code objects
6

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

  
......
22 24
    
23 25
    def to_str(self, db): return sql.qual_name(db, self.schema, self.name)
24 26

  
27
def as_Table(table):
28
    if table == None or isinstance(table, Table): return table
29
    elif isinstance(table, tuple):
30
        schema, table = table
31
        return Table(table, schema)
32
    else: return Table(table)
33

  
25 34
class Col(Code):
26 35
    def __init__(self, name, table=None):
27 36
        '''
......
65 74
def as_ValueCond(value):
66 75
    if not isinstance(value, ValueCond): return CompareCond(value)
67 76
    else: return value
77

  
78
##### Old-style format support
79

  
80
def unescape_table(table):
81
    '''Currently only works with PostgreSQL.'''
82
    if table == None: return table
83
    
84
    assert table.count('.') <= 1
85
    parts = tuple((v.replace('"', '') for v in table.split('"."', 2)))
86
    if len(parts) == 1: parts, = parts
87
    return parts
88

  
89
def value2sql_gen(value, default_table=None, table_is_esc=False):
90
    '''Converts old-style (tuple-based) values to sql_gen-compatible values.
91
    @param table_is_esc If False, assumes any table name is not escaped or that
92
        re-escaping it will produce the same value.
93
    '''
94
    if isinstance(value, Code): return value # already in sql_gen form
95
    
96
    if table_is_esc: default_table = unescape_table(default_table)
97
    is_tuple = isinstance(value, tuple)
98
    if is_tuple and len(value) == 1: return Literal(value[0]) # value is literal
99
    elif is_tuple and len(value) == 2: # value is col with table
100
        table, col = value
101
        if table_is_esc: table = unescape_table(table)
102
        return Col(col, as_Table(table))
103
    else: return Col(value, as_Table(default_table)) # value is col name

Also available in: Unified diff