Project

General

Profile

1
# XML-database conversion
2

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

    
7
import sql
8
import strings
9
import util
10
import xml_dom
11

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

    
14
ptr_suffix = '_id'
15

    
16
def is_ptr(node_name): return node_name.lower().endswith(ptr_suffix)
17

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

    
22
def ptr_target(node):
23
    assert is_ptr(name_of(node))
24
    return xml_dom.first_elem(node)
25

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

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

    
59
def put(db, node, store_ids=False, row_ct_ref=None, pkeys=None, parent_id=None):
60
    '''store_ids enables searching the tree for missing fields'''
61
    if pkeys == None: pkeys = {}
62
    def pkey(table): return sql.pkey(db, pkeys, table)
63
    
64
    table = name_of(node)
65
    pkey_ = pkey(table)
66
    row = {}
67
    children = []
68
    
69
    # Divide children into fields and children with fkeys to parent
70
    for child in xml_dom.NodeElemIter(node):
71
        child_name = name_of(child)
72
        if xml_dom.is_text(child):
73
            row[child_name] = strings.to_unicode(xml_dom.value(child))
74
        elif is_ptr(child_name): row[child_name] = put(db, ptr_target(child),
75
            store_ids, row_ct_ref, pkeys)
76
        else: children.append(child)
77
    try: del row[pkey_]
78
    except KeyError: pass
79
    
80
    # Add fkey to parent
81
    if parent_id != None:
82
        parent_ptr = node.getAttribute('fkey')
83
        if parent_ptr == '': parent_ptr = pkey(name_of(node.parentNode))
84
        row[parent_ptr] = parent_id
85
    
86
    # Insert node
87
    for try_num in xrange(2):
88
        try:
89
            id_ = sql.get(db, table, row, pkey_, True, row_ct_ref)
90
            if store_ids: xml_dom.set_id(node, id_)
91
            break
92
        except sql.NullValueException, ex:
93
            if try_num > 0: raise # exception still raised after retry
94
            if store_ids and is_ptr(ex.col):
95
                # Search for required column in ancestors and their children
96
                target = find_by_name(node, ptr_type_guess(ex.col))
97
                if target == None: raise
98
                row[ex.col] = xml_dom.get_id(target)
99
            else: raise
100
    
101
    # Insert children with fkeys to parent
102
    for child in children: put(db, child, store_ids, row_ct_ref, pkeys, id_)
103
    
104
    return id_
105

    
106
def xml2db(db, node, commit=False, row_ct_ref=None):
107
    iter_ = xml_dom.NodeElemIter(node)
108
    util.skip(iter_, xml_dom.is_text) # skip metadata
109
    for child in iter_:
110
        try:
111
            put(db, child, False, row_ct_ref)
112
            if commit: db.commit()
113
        except Exception:
114
            db.rollback()
115
            traceback.print_exc()
(2-2/11)