1
|
# XML-database conversion
|
2
|
|
3
|
import re
|
4
|
from xml.dom import Node
|
5
|
|
6
|
import sql
|
7
|
import strings
|
8
|
import xml_dom
|
9
|
|
10
|
def name_of(node): return re.sub(r'^.*\.', r'', xml_dom.name_of(node))
|
11
|
|
12
|
ptr_suffix = '_id'
|
13
|
|
14
|
def is_ptr(node_name): return node_name.endswith(ptr_suffix)
|
15
|
|
16
|
def ptr_type(node_name):
|
17
|
assert is_ptr(node_name)
|
18
|
return node_name[:-len(ptr_suffix)]
|
19
|
|
20
|
def ptr_target(node):
|
21
|
assert is_ptr(name_of(node))
|
22
|
return xml_dom.first_elem(node)
|
23
|
|
24
|
def find_by_name(node, name):
|
25
|
for parent in xml_dom.NodeParentIter(node):
|
26
|
if name_of(parent) == name: return parent
|
27
|
else:
|
28
|
for child in xml_dom.NodeElemIter(parent):
|
29
|
child_name = name_of(child)
|
30
|
if is_ptr(child_name):
|
31
|
if ptr_type(child_name) == name: return ptr_target(child)
|
32
|
elif child_name == name: return child
|
33
|
return None
|
34
|
|
35
|
def put(db, node, store_ids=False, row_ct_ref=None, pkeys=None, parent_id=None):
|
36
|
# store_ids enables searching the tree for missing fields
|
37
|
if pkeys == None: pkeys = {}
|
38
|
def pkey(table):
|
39
|
if table not in pkeys: pkeys[table] = sql.pkey(db, table)
|
40
|
return pkeys[table]
|
41
|
|
42
|
table = name_of(node)
|
43
|
pkey_ = pkey(table)
|
44
|
row = {}
|
45
|
children = []
|
46
|
|
47
|
# Divide children into fields and children with fkeys to parent
|
48
|
for child in xml_dom.NodeElemIter(node):
|
49
|
child_name = name_of(child)
|
50
|
if xml_dom.is_text(child):
|
51
|
row[child_name] = strings.to_unicode(xml_dom.value(child))
|
52
|
elif is_ptr(child_name): row[child_name] = put(db, ptr_target(child),
|
53
|
store_ids, row_ct_ref, pkeys)
|
54
|
else: children.append(child)
|
55
|
try: del row[pkey_]
|
56
|
except KeyError: pass
|
57
|
|
58
|
# Add fkey to parent
|
59
|
if parent_id != None:
|
60
|
parent_ptr = node.getAttribute('fkey')
|
61
|
if parent_ptr == '': parent_ptr = pkey(name_of(node.parentNode))
|
62
|
row[parent_ptr] = parent_id
|
63
|
|
64
|
# Insert node
|
65
|
for try_num in xrange(2):
|
66
|
try:
|
67
|
id_ = sql.get(db, table, row, pkey_, True, row_ct_ref)
|
68
|
if store_ids: xml_dom.set_id(node, id_)
|
69
|
break
|
70
|
except sql.NullValueException, ex:
|
71
|
if try_num > 0: raise # exception still raised after retry
|
72
|
if is_ptr(ex.col):
|
73
|
# Search for required column in ancestors and their children
|
74
|
target = find_by_name(node, ptr_type(ex.col))
|
75
|
if target == None: raise
|
76
|
row[ex.col] = xml_dom.get_id(target)
|
77
|
else: raise
|
78
|
|
79
|
# Insert children with fkeys to parent
|
80
|
for child in children: put(db, child, store_ids, row_ct_ref, pkeys, id_)
|
81
|
|
82
|
return id_
|
83
|
|
84
|
def xml2db(db, node, row_ct_ref=None):
|
85
|
iter_ = xml_dom.NodeElemIter(node)
|
86
|
while xml_dom.is_text(iter_.curr()): iter_.next() # skip metadata
|
87
|
for child in iter_: put(db, child, True, row_ct_ref)
|