Project

General

Profile

1
# XML-database conversion
2

    
3
import re
4
import traceback
5
from xml.dom import Node
6

    
7
import exc
8
import sql
9
import sql_gen
10
import strings
11
import util
12
import xml_dom
13
import xml_func
14

    
15
def name_of(node): return re.sub(r'^.*\.', r'', node.tagName)
16

    
17
ptr_suffix = '_id'
18

    
19
def is_ptr(node_name): return node_name.lower().endswith(ptr_suffix)
20

    
21
def ptr_type_guess(node_name):
22
    assert is_ptr(node_name)
23
    return node_name[:-len(ptr_suffix)]
24

    
25
def ptr_target(node):
26
    assert is_ptr(name_of(node))
27
    return xml_dom.value_node(node)
28

    
29
def find_by_name(node, name):
30
    for parent in xml_dom.NodeParentIter(node):
31
        if name_of(parent) == name: return parent
32
        else:
33
            for child in xml_dom.NodeElemIter(parent):
34
                child_name = name_of(child)
35
                if is_ptr(child_name):
36
                    target = ptr_target(child)
37
                    if target.tagName == name: return target
38
                elif child_name == name: return child
39
    return None
40

    
41
def get(db, node, limit=None, start=None):
42
    def pkey(table): return sql.pkey(db, table)
43
    
44
    node = node.firstChild
45
    table = name_of(node)
46
    pkey_ = pkey(table)
47
    
48
    fields = []
49
    conds = {}
50
    for child in xml_dom.NodeElemIter(node):
51
        child_name = name_of(child)
52
        if xml_dom.is_empty(child): fields.append(child_name)
53
        elif xml_dom.is_text(child): conds[child_name] = xml_dom.value(child)
54
        else: raise Exception('Joins not supported yet')
55
    id_ = xml_dom.get_id(node)
56
    if id_ != None: conds[pkey(table)] = id_ # replace any existing pkey value
57
    if fields == []: fields.append(pkey_)
58
    
59
    return sql.select(db, table, fields, conds, limit, start)
60

    
61
def put(db, node, row_ct_ref=None, on_error=exc.raise_, pool=None,
62
    store_ids=False, parent_id=None):
63
    '''store_ids enables searching the tree for missing fields'''
64
    def pkey(table): return sql.pkey(db, table, True)
65
    
66
    def put_(node, parent_id=None):
67
        args = (db, node, row_ct_ref, on_error, pool, store_ids, parent_id)
68
        if parent_id != None and pool != None: pool.apply_async(put, args)
69
        else: return put(*args)
70
    
71
    def on_error_(e):
72
        exc.add_msg(e, 'node:\n'+str(node))
73
        on_error(e)
74
    
75
    table = name_of(node)
76
    try: pkey_ = pkey(table)
77
    except sql.DatabaseErrors, e: on_error_(e); return None
78
    row = {}
79
    children = []
80
    
81
    # Divide children into fields and children with fkeys to parent
82
    for child in xml_dom.NodeElemIter(node):
83
        child_name = name_of(child)
84
        if xml_dom.is_empty(child): row[child_name] = None
85
        elif xml_dom.is_text(child):
86
            row[child_name] = strings.to_unicode(xml_dom.value(child))
87
        elif is_ptr(child_name): row[child_name] = put_(ptr_target(child))
88
        else: children.append(child)
89
    try: del row[pkey_]
90
    except KeyError: pass
91
    
92
    # Add fkey to parent
93
    if parent_id != None:
94
        parent_ptr = node.getAttribute('fkey')
95
        if parent_ptr == '': parent_ptr = pkey(name_of(node.parentNode))
96
        row[parent_ptr] = parent_id
97
    
98
    # Insert node
99
    try:
100
        for try_num in xrange(2):
101
            try:
102
                id_ = sql.put(db, table, row, pkey_, row_ct_ref)
103
                if store_ids: xml_dom.set_id(node, id_)
104
                break
105
            except sql.NullValueException, e:
106
                col = e.cols[0]
107
                if try_num > 0: raise # exception still raised after retry
108
                if store_ids and is_ptr(col):
109
                    # Search for required column in ancestors and their children
110
                    target = find_by_name(node, ptr_type_guess(col))
111
                    if target == None: raise
112
                    row[col] = xml_dom.get_id(target)
113
                else: raise
114
    except sql.DatabaseErrors, e: on_error_(e); return None
115
    
116
    # Insert children with fkeys to parent
117
    for child in children: put_(child, id_)
118
    
119
    return id_
120

    
121
class ColRef:
122
    '''A reference to a table column'''
123
    def __init__(self, name, idx):
124
        self.name = name
125
        self.idx = idx
126
    
127
    def __str__(self): return self.name
128

    
129
input_col_prefix = '$'
130

    
131
def put_table(db, node, in_table, limit=None, start=0,
132
    commit=False, row_ct_ref=None, parent_ids_loc=None):
133
    '''
134
    @param node The XML tree that transforms the input to the output. Similar to
135
        put()'s node param, but with the input column name prefixed by
136
        input_col_prefix in place of the column value.
137
    @param commit Whether to commit after each query
138
    @return (table, col) Where the pkeys (from INSERT RETURNING) are made
139
        available
140
    '''
141
    def pkey(table): return sql.pkey(db, table, True)
142
    
143
    in_table = sql_gen.as_Table(in_table)
144
    
145
    def put_table_(node, parent_ids_loc=None):
146
        return put_table(db, node, in_table, limit, start, commit, row_ct_ref,
147
            parent_ids_loc)
148
    
149
    out_table = name_of(node)
150
    row = {}
151
    children = []
152
    
153
    # Divide children into fields and children with fkeys to parent
154
    for child in xml_dom.NodeElemIter(node):
155
        child_name = name_of(child)
156
        if xml_dom.is_empty(child): row[child_name] = None
157
        elif xml_dom.is_text(child):
158
            row[child_name] = strings.to_unicode(xml_dom.value(child))
159
        else:
160
            child_value = xml_dom.value_node(child)
161
            if is_ptr(child_name) or xml_func.is_func(child_value):
162
                row[child_name] = put_table_(child_value)
163
            else: children.append(child)
164
    try: del row[pkey(out_table)]
165
    except KeyError: pass
166
    
167
    # Add fkey to parent
168
    if parent_ids_loc != None:
169
        parent_ptr = node.getAttribute('fkey')
170
        if parent_ptr == '': parent_ptr = pkey(name_of(node.parentNode))
171
        row[parent_ptr] = parent_ids_loc
172
    
173
    # Divide fields into input columns and literal values
174
    in_tables = [in_table]
175
    for out_col, value in row.iteritems():
176
        if isinstance(value, sql_gen.Col): # value is temp table column
177
            in_tables.append(value.table)
178
        elif util.is_str(value) and value.startswith(input_col_prefix):
179
            # value is input column
180
            row[out_col] = sql_gen.Col(strings.remove_prefix(input_col_prefix,
181
                value), in_table)
182
        else: # value is literal value; should only be string or None
183
            assert util.is_str(value) or value == None
184
            row[out_col] = sql_gen.NamedCol(out_col, value)
185
    
186
    # Insert node
187
    pkeys_loc = sql.put_table(db, out_table, in_tables, row, limit, start,
188
        row_ct_ref=row_ct_ref)
189
    if commit: db.db.commit()
190
    
191
    # Insert children with fkeys to parent
192
    for child in children: put_table_(child, pkeys_loc)
193
    
194
    return pkeys_loc
(9-9/34)