Project

General

Profile

1 13 aaronmk
# XML-database conversion
2
3 2418 aaronmk
import copy
4 16 aaronmk
import re
5 13 aaronmk
from xml.dom import Node
6
7 446 aaronmk
import exc
8 2436 aaronmk
import Parser
9 46 aaronmk
import sql
10 2268 aaronmk
import sql_gen
11 84 aaronmk
import strings
12 133 aaronmk
import util
13 46 aaronmk
import xml_dom
14 2113 aaronmk
import xml_func
15 2436 aaronmk
import xpath
16 13 aaronmk
17 139 aaronmk
def name_of(node): return re.sub(r'^.*\.', r'', node.tagName)
18 16 aaronmk
19 13 aaronmk
ptr_suffix = '_id'
20
21 138 aaronmk
def is_ptr(node_name): return node_name.lower().endswith(ptr_suffix)
22 13 aaronmk
23 172 aaronmk
def ptr_type_guess(node_name):
24 13 aaronmk
    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 2113 aaronmk
    return xml_dom.value_node(node)
30 13 aaronmk
31
def find_by_name(node, name):
32 46 aaronmk
    for parent in xml_dom.NodeParentIter(node):
33 13 aaronmk
        if name_of(parent) == name: return parent
34
        else:
35 46 aaronmk
            for child in xml_dom.NodeElemIter(parent):
36 16 aaronmk
                child_name = name_of(child)
37 13 aaronmk
                if is_ptr(child_name):
38 172 aaronmk
                    target = ptr_target(child)
39
                    if target.tagName == name: return target
40 13 aaronmk
                elif child_name == name: return child
41
    return None
42
43 1850 aaronmk
def get(db, node, limit=None, start=None):
44
    def pkey(table): return sql.pkey(db, table)
45 126 aaronmk
46 141 aaronmk
    node = node.firstChild
47 135 aaronmk
    table = name_of(node)
48
    pkey_ = pkey(table)
49
50
    fields = []
51
    conds = {}
52 133 aaronmk
    for child in xml_dom.NodeElemIter(node):
53 135 aaronmk
        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 1836 aaronmk
    if id_ != None: conds[pkey(table)] = id_ # replace any existing pkey value
59 135 aaronmk
    if fields == []: fields.append(pkey_)
60 133 aaronmk
61 864 aaronmk
    return sql.select(db, table, fields, conds, limit, start)
62 126 aaronmk
63 1864 aaronmk
def put(db, node, row_ct_ref=None, on_error=exc.raise_, pool=None,
64
    store_ids=False, parent_id=None):
65 138 aaronmk
    '''store_ids enables searching the tree for missing fields'''
66 1850 aaronmk
    def pkey(table): return sql.pkey(db, table, True)
67 15 aaronmk
68 461 aaronmk
    def put_(node, parent_id=None):
69 1874 aaronmk
        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 461 aaronmk
73
    def on_error_(e):
74 446 aaronmk
        exc.add_msg(e, 'node:\n'+str(node))
75 461 aaronmk
        on_error(e)
76 446 aaronmk
77 48 aaronmk
    table = name_of(node)
78 446 aaronmk
    try: pkey_ = pkey(table)
79 461 aaronmk
    except sql.DatabaseErrors, e: on_error_(e); return None
80 48 aaronmk
    row = {}
81
    children = []
82 13 aaronmk
83 48 aaronmk
    # 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 463 aaronmk
        if xml_dom.is_empty(child): row[child_name] = None
87 454 aaronmk
        elif xml_dom.is_text(child):
88 84 aaronmk
            row[child_name] = strings.to_unicode(xml_dom.value(child))
89 461 aaronmk
        elif is_ptr(child_name): row[child_name] = put_(ptr_target(child))
90 48 aaronmk
        else: children.append(child)
91
    try: del row[pkey_]
92
    except KeyError: pass
93
94
    # Add fkey to parent
95 59 aaronmk
    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 48 aaronmk
100
    # Insert node
101 446 aaronmk
    try:
102
        for try_num in xrange(2):
103
            try:
104 472 aaronmk
                id_ = sql.put(db, table, row, pkey_, row_ct_ref)
105 446 aaronmk
                if store_ids: xml_dom.set_id(node, id_)
106
                break
107
            except sql.NullValueException, e:
108 468 aaronmk
                col = e.cols[0]
109 446 aaronmk
                if try_num > 0: raise # exception still raised after retry
110 468 aaronmk
                if store_ids and is_ptr(col):
111 446 aaronmk
                    # Search for required column in ancestors and their children
112 468 aaronmk
                    target = find_by_name(node, ptr_type_guess(col))
113 446 aaronmk
                    if target == None: raise
114 468 aaronmk
                    row[col] = xml_dom.get_id(target)
115 446 aaronmk
                else: raise
116 461 aaronmk
    except sql.DatabaseErrors, e: on_error_(e); return None
117 48 aaronmk
118
    # Insert children with fkeys to parent
119 1874 aaronmk
    for child in children: put_(child, id_)
120 48 aaronmk
121
    return id_
122 1996 aaronmk
123 2039 aaronmk
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 2491 aaronmk
def into_table_name(out_table, row):
132
    into = None
133 2512 aaronmk
    try: in_col = row['value']
134
    except KeyError:
135
        out_col = 'rank'
136
        try: in_col = row[out_col]
137
        except KeyError: pass
138
        else: # has a rank column, so hierarchical
139 2515 aaronmk
            col_name = str(sql_gen.remove_col_rename(in_col))
140 2512 aaronmk
            into = out_table+'['+out_col+'='+col_name+']'
141
    else: # has a value column, so function-like
142 2515 aaronmk
        col_name = str(sql_gen.remove_col_rename(in_col))
143 2494 aaronmk
        into = out_table+'('+col_name+')'
144 2491 aaronmk
    return into
145
146 2177 aaronmk
input_col_prefix = '$'
147
148 2549 aaronmk
put_table_special_funcs = set(['_simplifyPath'])
149
150 2422 aaronmk
def put_table(db, node, in_table, commit=False, in_row_ct_ref=None,
151 2506 aaronmk
    row_ins_ct_ref=None, limit=None, start=0, parent_ids_loc=None, next=None):
152 1996 aaronmk
    '''
153 1998 aaronmk
    @param node The XML tree that transforms the input to the output. Similar to
154 2177 aaronmk
        put()'s node param, but with the input column name prefixed by
155
        input_col_prefix in place of the column value.
156 1998 aaronmk
    @param commit Whether to commit after each query
157 2133 aaronmk
    @return (table, col) Where the pkeys (from INSERT RETURNING) are made
158 2067 aaronmk
        available
159 1998 aaronmk
    '''
160 2418 aaronmk
    in_table = sql_gen.as_Table(in_table)
161
162 2423 aaronmk
    # Subset in_table
163 2418 aaronmk
    if limit != None or start != 0:
164
        in_table = copy.copy(in_table) # don't modify input!
165
        sql.run_query_into(db, *sql.mk_select(db, in_table, limit=limit,
166
            start=start, order_by=None), into=in_table)
167 2469 aaronmk
            # in_table will be shadowed (hidden) by the created temp table
168 2418 aaronmk
169 2005 aaronmk
    def pkey(table): return sql.pkey(db, table, True)
170
171 2506 aaronmk
    def put_table_(node):
172
        return put_table(db, node, in_table, commit, None, row_ins_ct_ref,
173
            parent_ids_loc=parent_ids_loc, next=next)
174 2088 aaronmk
175 2551 aaronmk
    is_func = xml_func.is_func(node)
176 2005 aaronmk
    out_table = name_of(node)
177 2432 aaronmk
178
    # Divide children into fields and children with fkeys to parent
179 2005 aaronmk
    row = {}
180
    children = []
181
    for child in xml_dom.NodeElemIter(node):
182
        child_name = name_of(child)
183
        if xml_dom.is_empty(child): row[child_name] = None
184
        elif xml_dom.is_text(child):
185
            row[child_name] = strings.to_unicode(xml_dom.value(child))
186 2113 aaronmk
        else:
187
            child_value = xml_dom.value_node(child)
188 2434 aaronmk
            if is_func or is_ptr(child_name) or xml_func.is_func(child_value):
189 2432 aaronmk
                row[child_name] = child_value
190 2113 aaronmk
            else: children.append(child)
191 2434 aaronmk
192
    # Special handling for structural XML functions
193
    if out_table == '_simplifyPath':
194 2436 aaronmk
        # Parse args
195
        def wrap_e(e): raise xml_func.SyntaxError(e)
196 2434 aaronmk
        try:
197 2506 aaronmk
            next = row['next'] # modifies outer next var used by put_table_()
198 2434 aaronmk
            require = row['require']
199
            path = row['path']
200 2436 aaronmk
        except KeyError, e: wrap_e(e)
201
        try: next = xpath.parse(next)
202
        except Parser.SyntaxError, e: wrap_e(e)
203
        try: next = next[0].name
204
        except IndexError, e: wrap_e(e)
205 2434 aaronmk
206
        # For now, just skip XML func
207 2506 aaronmk
        return put_table_(path)
208 2434 aaronmk
209
    # Remove any explicit pkey
210 2133 aaronmk
    try: del row[pkey(out_table)]
211 2005 aaronmk
    except KeyError: pass
212
213 2177 aaronmk
    # 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 2060 aaronmk
    # Divide fields into input columns and literal values
220 2506 aaronmk
    parent_ids_loc = None # applies to this section
221 2313 aaronmk
    in_tables = [in_table]
222 2060 aaronmk
    for out_col, value in row.iteritems():
223 2432 aaronmk
        # Handle forward pointers
224
        if xml_dom.is_node(value): row[out_col] = value = put_table_(value)
225
226
        # Translate values
227 2268 aaronmk
        if isinstance(value, sql_gen.Col): # value is temp table column
228
            in_tables.append(value.table)
229 2177 aaronmk
        elif util.is_str(value) and value.startswith(input_col_prefix):
230
            # value is input column
231 2272 aaronmk
            row[out_col] = sql_gen.Col(strings.remove_prefix(input_col_prefix,
232 2313 aaronmk
                value), in_table)
233 2177 aaronmk
        else: # value is literal value; should only be string or None
234
            assert util.is_str(value) or value == None
235 2323 aaronmk
            row[out_col] = sql_gen.NamedCol(out_col, value)
236 2060 aaronmk
237
    # Insert node
238 2488 aaronmk
    pkeys_loc = sql.put_table(db, out_table, in_tables, row, row_ins_ct_ref,
239 2553 aaronmk
        into_table_name(out_table, row), next, is_func)
240 2182 aaronmk
    if commit: db.db.commit()
241 2060 aaronmk
242 2177 aaronmk
    # Insert children with fkeys to parent
243 2506 aaronmk
    parent_ids_loc = pkeys_loc # applies to this section
244
    for child in children: put_table_(child)
245 2177 aaronmk
246 2423 aaronmk
    # Count # rows and update in_row_ct_ref once all columns have been processed
247
    if in_row_ct_ref != None:
248 2427 aaronmk
        in_row_ct_ref[0] += sql.table_row_count(db, in_table)
249 2423 aaronmk
250 2133 aaronmk
    return pkeys_loc