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

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

    
15
ptr_suffix = '_id'
16

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

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

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

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

    
39
def get(db, node, limit=None, start=None):
40
    def pkey(table): return sql.pkey(db, 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_ != None: 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, start)
58

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

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

    
127
def put_table(db, node, in_table, in_schema=None, commit=False,
128
    row_ct_ref=None):
129
    '''
130
    @param node The XML tree that transforms the input to the output. Similar to
131
        put()'s node param, but with the input column name prefixed by "$" in
132
        place of the column value.
133
    @param commit Whether to commit after each query
134
    '''
135
    def qual_name(table): return sql.qual_name(db, in_schema, table)
136
    def pkey(table): return sql.pkey(db, table, True)
137
    
138
    out_table = name_of(node)
139
    pkey_ = pkey(out_table)
140
    row = {}
141
    children = []
142
    
143
    # Divide children into fields and children with fkeys to parent
144
    for child in xml_dom.NodeElemIter(node):
145
        child_name = name_of(child)
146
        if xml_dom.is_empty(child): row[child_name] = None
147
        elif xml_dom.is_text(child):
148
            row[child_name] = strings.to_unicode(xml_dom.value(child))
149
        elif is_ptr(child_name): pass#row[child_name] = put_(ptr_target(child))
150
        else: children.append(child)
151
    try: del row[pkey_]
152
    except KeyError: pass
153
    
154
    # Divide fields into input columns and literal values
155
    for out_col, value in row.iteritems():
156
        in_col = strings.remove_prefix('$', value)
157
        if in_col != value: row[out_col] = in_col # value is input column
158
        else: row[out_col] = (value, out_col) # value is literal value
159
    
160
    # Insert node
161
    out_cols = row.keys()
162
    map(sql.check_name, out_cols)
163
    select_query, params = sql.mk_select(db, qual_name(in_table), row.values(),
164
        table_is_esc=True)
165
    sql.run_query(db, 'INSERT INTO '+out_table+' ('+', '.join(out_cols)+') '
166
        +select_query, params)
167
    
168
    import sys; sys.stderr.write(str(node))
169
    if commit: db.db.commit()
170
    raise NotImplementedError('By-column optimization not available yet')
(9-9/33)