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 3077 aaronmk
import sql_io
11 2268 aaronmk
import sql_gen
12 84 aaronmk
import strings
13 133 aaronmk
import util
14 46 aaronmk
import xml_dom
15 2113 aaronmk
import xml_func
16 2436 aaronmk
import xpath
17 13 aaronmk
18 139 aaronmk
def name_of(node): return re.sub(r'^.*\.', r'', node.tagName)
19 16 aaronmk
20 13 aaronmk
ptr_suffix = '_id'
21
22 138 aaronmk
def is_ptr(node_name): return node_name.lower().endswith(ptr_suffix)
23 13 aaronmk
24 172 aaronmk
def ptr_type_guess(node_name):
25 13 aaronmk
    assert is_ptr(node_name)
26
    return node_name[:-len(ptr_suffix)]
27
28
def ptr_target(node):
29
    assert is_ptr(name_of(node))
30 2113 aaronmk
    return xml_dom.value_node(node)
31 13 aaronmk
32
def find_by_name(node, name):
33 46 aaronmk
    for parent in xml_dom.NodeParentIter(node):
34 13 aaronmk
        if name_of(parent) == name: return parent
35
        else:
36 46 aaronmk
            for child in xml_dom.NodeElemIter(parent):
37 16 aaronmk
                child_name = name_of(child)
38 13 aaronmk
                if is_ptr(child_name):
39 172 aaronmk
                    target = ptr_target(child)
40
                    if target.tagName == name: return target
41 13 aaronmk
                elif child_name == name: return child
42
    return None
43
44 2039 aaronmk
class ColRef:
45
    '''A reference to a table column'''
46
    def __init__(self, name, idx):
47
        self.name = name
48
        self.idx = idx
49
50
    def __str__(self): return self.name
51
52 3652 aaronmk
put_special_funcs = set(['_simplifyPath'])
53 2549 aaronmk
54 3660 aaronmk
def put(db, node, row_ins_ct_ref=None, on_error=exc.reraise,
55 3649 aaronmk
    col_defaults={}, in_table=None, parent_ids_loc=None, next=None):
56 3676 aaronmk
    '''
57
    @param node To use an entire XML document, pass root.firstChild.
58
    '''
59
    if node == None: return None # when no rows, root.firstChild == None
60
61 3685 aaronmk
    def put_(node):
62
        return put(db, node, row_ins_ct_ref, on_error, col_defaults, in_table,
63
            parent_ids_loc, next)
64 3621 aaronmk
65 3677 aaronmk
    def augment_error(e): exc.add_msg(e, 'node:\n'+str(node))
66 3646 aaronmk
    def on_error_(e):
67 3677 aaronmk
        augment_error(e)
68 3646 aaronmk
        on_error(e)
69
70 2551 aaronmk
    is_func = xml_func.is_func(node)
71 2005 aaronmk
    out_table = name_of(node)
72 2432 aaronmk
73
    # Divide children into fields and children with fkeys to parent
74 2005 aaronmk
    row = {}
75
    children = []
76
    for child in xml_dom.NodeElemIter(node):
77
        child_name = name_of(child)
78
        if xml_dom.is_empty(child): row[child_name] = None
79
        elif xml_dom.is_text(child):
80
            row[child_name] = strings.to_unicode(xml_dom.value(child))
81 2113 aaronmk
        else:
82
            child_value = xml_dom.value_node(child)
83 2434 aaronmk
            if is_func or is_ptr(child_name) or xml_func.is_func(child_value):
84 2432 aaronmk
                row[child_name] = child_value
85 2113 aaronmk
            else: children.append(child)
86 2434 aaronmk
87
    # Special handling for structural XML functions
88
    if out_table == '_simplifyPath':
89 2436 aaronmk
        # Parse args
90
        def wrap_e(e): raise xml_func.SyntaxError(e)
91 2434 aaronmk
        try:
92 3650 aaronmk
            next = row['next'] # modifies outer next var used by put_()
93 2434 aaronmk
            require = row['require']
94
            path = row['path']
95 2436 aaronmk
        except KeyError, e: wrap_e(e)
96
        try: next = xpath.parse(next)
97
        except Parser.SyntaxError, e: wrap_e(e)
98
        try: next = next[0].name
99
        except IndexError, e: wrap_e(e)
100 2434 aaronmk
101 3650 aaronmk
        return put_(path)
102 2434 aaronmk
103 3687 aaronmk
    is_literals = in_table == None
104 3624 aaronmk
    in_tables = []
105
    no_empty = set()
106 3687 aaronmk
    if not is_literals:
107 3624 aaronmk
        in_tables.append(in_table)
108
        no_empty.add(in_table)
109 2966 aaronmk
110 3107 aaronmk
    def pkey(table): return sql.pkey(db, table, True)
111
112 2177 aaronmk
    # Add fkey to parent
113
    if parent_ids_loc != None:
114 3601 aaronmk
        if sql_gen.is_table_col(parent_ids_loc):
115
            no_empty.add(parent_ids_loc.table)
116 2177 aaronmk
        parent_ptr = node.getAttribute('fkey')
117
        if parent_ptr == '': parent_ptr = pkey(name_of(node.parentNode))
118
        row[parent_ptr] = parent_ids_loc
119
120 2060 aaronmk
    # Divide fields into input columns and literal values
121 2506 aaronmk
    parent_ids_loc = None # applies to this section
122 2060 aaronmk
    for out_col, value in row.iteritems():
123 2432 aaronmk
        # Handle forward pointers
124 3650 aaronmk
        if xml_dom.is_node(value): row[out_col] = value = put_(value)
125 2432 aaronmk
126
        # Translate values
127 2268 aaronmk
        if isinstance(value, sql_gen.Col): # value is temp table column
128 3687 aaronmk
            assert sql_gen.is_table_col(value)
129 2268 aaronmk
            in_tables.append(value.table)
130 3687 aaronmk
        elif (not is_literals and util.is_str(value)
131
            and value.startswith(input_col_prefix)): # value is input column
132 2272 aaronmk
            row[out_col] = sql_gen.Col(strings.remove_prefix(input_col_prefix,
133 2313 aaronmk
                value), in_table)
134 3428 aaronmk
        else: # value is literal value
135 2323 aaronmk
            row[out_col] = sql_gen.NamedCol(out_col, value)
136 2060 aaronmk
137
    # Insert node
138 3657 aaronmk
    try: pkeys_loc = sql_io.put_table(db, out_table, in_tables, row,
139
        row_ins_ct_ref, next, col_defaults, on_error_)
140
    except Exception, e:
141 3677 aaronmk
        augment_error(e)
142
        raise
143 2060 aaronmk
144 2975 aaronmk
    sql.empty_temp(db, set(in_tables) - no_empty)
145 2966 aaronmk
146 2177 aaronmk
    # Insert children with fkeys to parent
147 2506 aaronmk
    parent_ids_loc = pkeys_loc # applies to this section
148 3650 aaronmk
    for child in children: put_(child)
149 2177 aaronmk
150 2133 aaronmk
    return pkeys_loc
151 3651 aaronmk
152
def get(db, node, limit=None, start=None):
153
    def pkey(table): return sql.pkey(db, table)
154
155
    node = node.firstChild
156
    table = name_of(node)
157
    pkey_ = pkey(table)
158
159
    fields = []
160
    conds = {}
161
    for child in xml_dom.NodeElemIter(node):
162
        child_name = name_of(child)
163
        if xml_dom.is_empty(child): fields.append(child_name)
164
        elif xml_dom.is_text(child): conds[child_name] = xml_dom.value(child)
165
        else: raise Exception('Joins not supported yet')
166
    id_ = xml_dom.get_id(node)
167
    if id_ != None: conds[pkey(table)] = id_ # replace any existing pkey value
168
    if fields == []: fields.append(pkey_)
169
170
    return sql.select(db, table, fields, conds, limit, start)
171
172
# Controls when and how put_table() will partition the input table
173
partition_size = 500000 # rows
174
175
input_col_prefix = '$'
176
177
def put_table(db, node, in_table, in_row_ct_ref=None, row_ins_ct_ref=None,
178 3660 aaronmk
    limit=None, start=0, on_error=exc.reraise, col_defaults={}):
179 3651 aaronmk
    '''
180
    @param node The XML tree that transforms the input to the output. Similar to
181
        put()'s node param, but with the input column name prefixed by
182
        input_col_prefix in place of the column value.
183
    @return sql_gen.Col Where the pkeys (from INSERT RETURNING) are made
184
        available
185
    '''
186
    in_table = sql_gen.as_Table(in_table)
187
    in_table.set_srcs([in_table], overwrite=False)
188
    db.src = str(in_table)
189
190
    db.autoanalyze = True # but don't do this in row-based import
191
    db.autoexplain = True # but don't do this in row-based import
192
193
    # Subset and partition in_table
194
    # OK to do even if table already the right size because it takes <1 sec.
195
    full_in_table = in_table
196
    total = 0
197
    while limit == None or total < limit:
198
        # Adjust partition size if last partition
199
        this_limit = partition_size
200
        if limit != None: this_limit = min(this_limit, limit - total)
201
202
        # Row # is interally 0-based, but 1-based to the user
203
        db.log_debug('********** Partition: rows '+str(start+1)+'-'
204
            +str(start+this_limit)+' **********', level=1.2)
205
206
        # Subset in_table
207
        in_table = copy.copy(full_in_table) # don't modify input!
208
        in_table.name = str(in_table) # prepend schema
209
        cur = sql.run_query_into(db, sql.mk_select(db, full_in_table,
210
            limit=this_limit, start=start), into=in_table, add_pkey_=True)
211
            # full_in_table will be shadowed (hidden) by created temp table
212
213
        this_ct = cur.rowcount
214
        total += this_ct
215
        start += this_ct # advance start to fetch next set
216
        if this_ct == 0: break # in_table size is multiple of partition_size
217
218
        # Recurse
219
        pkeys_loc = put(db, node, row_ins_ct_ref, on_error,
220
            col_defaults, in_table)
221
        if in_row_ct_ref != None: in_row_ct_ref[0] += this_ct
222
223
        sql.empty_temp(db, in_table)
224
225
        if this_ct < partition_size: break # partial partition = last
226
227
        # Work around PostgreSQL's temp table disk space leak
228
        db.reconnect()
229
230
    return pkeys_loc