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 strings
10
import util
11
import xml_dom
12
import xml_func
13

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

    
16
ptr_suffix = '_id'
17

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

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

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

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

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

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

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

    
128
input_col_prefix = '$'
129

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