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