Project

General

Profile

1
# XML-database conversion
2

    
3
import copy
4
import re
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, commit=False, in_row_ct_ref=None,
132
    row_ins_ct_ref=None, limit=None, start=0, 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
    in_table = sql_gen.as_Table(in_table)
142
    
143
    # Subset in_table
144
    if limit != None or start != 0:
145
        in_table = copy.copy(in_table) # don't modify input!
146
        sql.run_query_into(db, *sql.mk_select(db, in_table, limit=limit,
147
            start=start, order_by=None), into=in_table)
148
            # in_table won't be overwritten because of automatic versioning
149
    
150
    def pkey(table): return sql.pkey(db, table, True)
151
    
152
    def put_table_(node, parent_ids_loc=None):
153
        return put_table(db, node, in_table, commit, row_ins_ct_ref,
154
            parent_ids_loc=parent_ids_loc)
155
    
156
    out_table = name_of(node)
157
    row = {}
158
    children = []
159
    
160
    # Divide children into fields and children with fkeys to parent
161
    for child in xml_dom.NodeElemIter(node):
162
        child_name = name_of(child)
163
        if xml_dom.is_empty(child): row[child_name] = None
164
        elif xml_dom.is_text(child):
165
            row[child_name] = strings.to_unicode(xml_dom.value(child))
166
        else:
167
            child_value = xml_dom.value_node(child)
168
            if is_ptr(child_name) or xml_func.is_func(child_value):
169
                row[child_name] = put_table_(child_value)
170
            else: children.append(child)
171
    try: del row[pkey(out_table)]
172
    except KeyError: pass
173
    
174
    # Add fkey to parent
175
    if parent_ids_loc != None:
176
        parent_ptr = node.getAttribute('fkey')
177
        if parent_ptr == '': parent_ptr = pkey(name_of(node.parentNode))
178
        row[parent_ptr] = parent_ids_loc
179
    
180
    # Divide fields into input columns and literal values
181
    in_tables = [in_table]
182
    for out_col, value in row.iteritems():
183
        if isinstance(value, sql_gen.Col): # value is temp table column
184
            in_tables.append(value.table)
185
        elif util.is_str(value) and value.startswith(input_col_prefix):
186
            # value is input column
187
            row[out_col] = sql_gen.Col(strings.remove_prefix(input_col_prefix,
188
                value), in_table)
189
        else: # value is literal value; should only be string or None
190
            assert util.is_str(value) or value == None
191
            row[out_col] = sql_gen.NamedCol(out_col, value)
192
    
193
    # Insert node
194
    db.log_debug('Putting columns: '+str(row))
195
    pkeys_loc = sql.put_table(db, out_table, in_tables, row, row_ins_ct_ref)
196
    if commit: db.db.commit()
197
    
198
    # Insert children with fkeys to parent
199
    for child in children: put_table_(child, pkeys_loc)
200
    
201
    # Count # rows and update in_row_ct_ref once all columns have been processed
202
    if in_row_ct_ref != None:
203
        in_row_ct_ref[0] += sql.table_row_count(db, in_table)
204
    
205
    return pkeys_loc
(9-9/35)