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 Parser
9
import sql
10
import sql_gen
11
import strings
12
import util
13
import xml_dom
14
import xml_func
15
import xpath
16

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

    
19
ptr_suffix = '_id'
20

    
21
def is_ptr(node_name): return node_name.lower().endswith(ptr_suffix)
22

    
23
def ptr_type_guess(node_name):
24
    assert is_ptr(node_name)
25
    return node_name[:-len(ptr_suffix)]
26

    
27
def ptr_target(node):
28
    assert is_ptr(name_of(node))
29
    return xml_dom.value_node(node)
30

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

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

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

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

    
131
def into_table_name(out_table, row, is_func):
132
    into = None
133
    if not is_func:
134
        out_col = 'rank'
135
        try: in_col = row[out_col]
136
        except KeyError: pass
137
        else: # has a rank column, so hierarchical
138
            col_name = str(sql_gen.remove_col_rename(in_col))
139
            into = out_table+'['+out_col+'='+col_name+']'
140
    return into
141

    
142
input_col_prefix = '$'
143

    
144
put_table_special_funcs = set(['_simplifyPath'])
145

    
146
def put_table(db, node, in_table, commit=False, in_row_ct_ref=None,
147
    row_ins_ct_ref=None, limit=None, start=0, on_error=exc.raise_,
148
    parent_ids_loc=None, next=None):
149
    '''
150
    @param node The XML tree that transforms the input to the output. Similar to
151
        put()'s node param, but with the input column name prefixed by
152
        input_col_prefix in place of the column value.
153
    @param commit Whether to commit after each query
154
    @return (table, col) Where the pkeys (from INSERT RETURNING) are made
155
        available
156
    '''
157
    in_table = sql_gen.as_Table(in_table)
158
    in_table.set_srcs(sql_gen.src_self, overwrite=False)
159
    
160
    # Subset in_table
161
    if limit != None or start != 0:
162
        full_in_table = in_table
163
        in_table = copy.copy(in_table) # don't modify input!
164
        in_table.set_srcs([full_in_table])
165
        sql.run_query_into(db, sql.mk_select(db, in_table, limit=limit,
166
            start=start), into=in_table)
167
            # in_table will be shadowed (hidden) by the created temp table
168
        sql.add_pkey(db, in_table)
169
    
170
    def pkey(table): return sql.pkey(db, table, True)
171
    
172
    def put_table_(node):
173
        return put_table(db, node, in_table, commit, None, row_ins_ct_ref,
174
            on_error=on_error, parent_ids_loc=parent_ids_loc, next=next)
175
    
176
    is_func = xml_func.is_func(node)
177
    out_table = name_of(node)
178
    
179
    # Divide children into fields and children with fkeys to parent
180
    row = {}
181
    children = []
182
    for child in xml_dom.NodeElemIter(node):
183
        child_name = name_of(child)
184
        if xml_dom.is_empty(child): row[child_name] = None
185
        elif xml_dom.is_text(child):
186
            row[child_name] = strings.to_unicode(xml_dom.value(child))
187
        else:
188
            child_value = xml_dom.value_node(child)
189
            if is_func or is_ptr(child_name) or xml_func.is_func(child_value):
190
                row[child_name] = child_value
191
            else: children.append(child)
192
    
193
    # Special handling for structural XML functions
194
    if out_table == '_simplifyPath':
195
        # Parse args
196
        def wrap_e(e): raise xml_func.SyntaxError(e)
197
        try:
198
            next = row['next'] # modifies outer next var used by put_table_()
199
            require = row['require']
200
            path = row['path']
201
        except KeyError, e: wrap_e(e)
202
        try: next = xpath.parse(next)
203
        except Parser.SyntaxError, e: wrap_e(e)
204
        try: next = next[0].name
205
        except IndexError, e: wrap_e(e)
206
        
207
        return put_table_(path)
208
    
209
    # Remove any explicit pkey
210
    try: del row[pkey(out_table)]
211
    except KeyError: pass
212
    
213
    # Add fkey to parent
214
    if parent_ids_loc != None:
215
        parent_ptr = node.getAttribute('fkey')
216
        if parent_ptr == '': parent_ptr = pkey(name_of(node.parentNode))
217
        row[parent_ptr] = parent_ids_loc
218
    
219
    # Divide fields into input columns and literal values
220
    parent_ids_loc = None # applies to this section
221
    in_tables = [in_table]
222
    for out_col, value in row.iteritems():
223
        # Handle forward pointers
224
        if xml_dom.is_node(value): row[out_col] = value = put_table_(value)
225
        
226
        # Translate values
227
        if isinstance(value, sql_gen.Col): # value is temp table column
228
            in_tables.append(value.table)
229
        elif util.is_str(value) and value.startswith(input_col_prefix):
230
            # value is input column
231
            row[out_col] = sql_gen.Col(strings.remove_prefix(input_col_prefix,
232
                value), in_table)
233
        else: # value is literal value; should only be string or None
234
            assert util.is_str(value) or value == None
235
            row[out_col] = sql_gen.NamedCol(out_col, value)
236
    
237
    # Insert node
238
    pkeys_loc = sql.put_table(db, out_table, in_tables, row, row_ins_ct_ref,
239
        into_table_name(out_table, row, is_func), next, is_func, on_error)
240
    if commit: db.db.commit()
241
    
242
    # Insert children with fkeys to parent
243
    parent_ids_loc = pkeys_loc # applies to this section
244
    for child in children: put_table_(child)
245
    
246
    # Count # rows and update in_row_ct_ref once all columns have been processed
247
    if in_row_ct_ref != None:
248
        in_row_ct_ref[0] += sql.table_row_count(db, in_table)
249
    
250
    return pkeys_loc
(9-9/36)