Project

General

Profile

1
# XML-database conversion
2

    
3
import copy
4
import re
5
from xml.dom import Node
6

    
7
import dicts
8
import exc
9
import Parser
10
import sql
11
import sql_io
12
import sql_gen
13
import strings
14
import util
15
import xml_dom
16
import xml_func
17
import xpath
18

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

    
21
ptr_suffix = '_id'
22

    
23
def is_ptr(node_name): return node_name.lower().endswith(ptr_suffix)
24

    
25
def ptr_type_guess(node_name):
26
    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
    return xml_dom.value_node(node)
32

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

    
45
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
input_col_prefix = xml_func.var_name_prefix
54

    
55
put_special_funcs = set(['_setDefault', '_simplifyPath'])
56

    
57
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
    '''
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
    
66
    def put_(node):
67
        if util.is_str(node): return node
68
        return put(db, node, row_ins_ct_ref, on_error, col_defaults, in_table,
69
            parent_ids_loc, next)
70
    
71
    def augment_error(e): exc.add_msg(e, 'node:\n'+strings.ustr(node))
72
    def on_error_(e):
73
        augment_error(e)
74
        on_error(e)
75
    
76
    def wrap_e(e):
77
        augment_error(e)
78
        raise xml_func.SyntaxError(e)
79
    
80
    is_func = xml_func.is_func(node)
81
    out_table = name_of(node)
82
    
83
    # Divide children into fields and children with fkeys to parent
84
    row = dicts.OnceOnlyDict()
85
    children = []
86
    try:
87
        for child in xml_dom.NodeElemIter(node):
88
            child_name = name_of(child)
89
            if xml_dom.is_empty(child): row[child_name] = None
90
            elif xml_dom.is_text(child):
91
                row[child_name] = strings.to_unicode(xml_dom.value(child))
92
            else:
93
                child_value = xml_dom.value_node(child)
94
                if ((is_func or is_ptr(child_name)
95
                    or xml_func.is_func(child_value))
96
                    and not xml_func.is_func(child)):
97
                    row[child_name] = child_value
98
                else: children.append(child)
99
    except dicts.KeyExistsError, e: wrap_e(e)
100
    
101
    # Special handling for structural XML functions
102
    if out_table == '_setDefault':
103
        # Parse args
104
        try: path = row.pop('path')
105
        except KeyError, e: wrap_e(e)
106
        
107
        col_defaults.update([(k, put_(v)) for k, v in row.iteritems()])
108
        return put_(path)
109
    elif out_table == '_simplifyPath':
110
        # Parse args
111
        try:
112
            next = row['next'] # modifies outer next var used by put_()
113
            path = row['path']
114
        except KeyError, e: wrap_e(e)
115
        try: next = xpath.parse(next)
116
        except Parser.SyntaxError, e: wrap_e(e)
117
        try: next = next[0].name
118
        except IndexError, e: wrap_e(e)
119
        
120
        return put_(path)
121
    
122
    is_literals = in_table == None
123
    in_tables = []
124
    no_empty = set()
125
    if not is_literals:
126
        in_tables.append(in_table)
127
        no_empty.add(in_table)
128
    
129
    def pkey_name(table): return sql.pkey_name(db, table, True)
130
    
131
    # Add fkey to parent
132
    if parent_ids_loc is not no_parent_ids_loc:
133
        if sql_gen.is_table_col(parent_ids_loc):
134
            no_empty.add(parent_ids_loc.table)
135
        parent_ptr = node.getAttribute('fkey')
136
        if parent_ptr == '': parent_ptr = pkey_name(name_of(node.parentNode))
137
        row[parent_ptr] = parent_ids_loc
138
    
139
    # Parse input columns
140
    row = row.inner # now allow keys to be overwritten
141
    for out_col, value in row.iteritems():
142
        if (not is_literals and util.is_str(value)
143
            and value.startswith(input_col_prefix)): # value is input column
144
            row[out_col] = sql_gen.Col(strings.remove_prefix(input_col_prefix,
145
                value), in_table)
146
    
147
    # Optimizations for structural XML functions
148
    if out_table == '_alt': # return first arg if non-NULL
149
        args = row.items()
150
        args.sort()
151
        out_col, value = min(args) # first arg
152
        if xml_dom.is_node(value): row[out_col] = value = put_(value)
153
        if not sql_gen.is_nullable(db, value): return value
154
    
155
    # Process values
156
    parent_ids_loc = no_parent_ids_loc # applies to this section
157
    for out_col, value in row.iteritems():
158
        # Handle forward pointers
159
        if xml_dom.is_node(value): row[out_col] = value = put_(value)
160
        
161
        # Translate values
162
        if isinstance(value, sql_gen.Col): # value is table column
163
            assert sql_gen.is_table_col(value)
164
            if value.table is not in_table: in_tables.append(value.table)
165
        else: # value is literal value
166
            row[out_col] = sql_gen.NamedCol(out_col, value)
167
    
168
    # Insert node
169
    try: pkeys_loc = sql_io.put_table(db, out_table, in_tables, row,
170
        row_ins_ct_ref, next, col_defaults, on_error_)
171
    except Exception, e:
172
        augment_error(e)
173
        raise
174
    if sql_gen.is_table_col(pkeys_loc): no_empty.add(pkeys_loc.table)
175
    
176
    sql.empty_temp(db, set(in_tables) - no_empty)
177
    
178
    # Insert children with fkeys to parent
179
    parent_ids_loc = pkeys_loc # applies to this section
180
    for child in children: put_(child)
181
    
182
    return pkeys_loc
183

    
184
def get(db, node, limit=None, start=None):
185
    def pkey_name(table): return sql.pkey_name(db, table)
186
    
187
    node = node.firstChild
188
    table = name_of(node)
189
    pkey_ = pkey_name(table)
190
    
191
    fields = []
192
    conds = {}
193
    for child in xml_dom.NodeElemIter(node):
194
        child_name = name_of(child)
195
        if xml_dom.is_empty(child): fields.append(child_name)
196
        elif xml_dom.is_text(child): conds[child_name] = xml_dom.value(child)
197
        else: raise Exception('Joins not supported yet')
198
    id_ = xml_dom.get_id(node)
199
    if id_ != None: conds[pkey_name(table)] = id_ # replace any existing value
200
    if fields == []: fields.append(pkey_)
201
    
202
    return sql.select(db, table, fields, conds, limit, start)
203

    
204
# Controls when and how put_table() will partition the input table
205
partition_size = 1000000 # rows; must be >= NCBI.nodes size
206

    
207
def put_table(db, node, in_table, in_row_ct_ref=None, row_ins_ct_ref=None,
208
    limit=None, start=0, on_error=exc.reraise, col_defaults={},
209
    partition_size=partition_size):
210
    '''
211
    @param node The XML tree that transforms the input to the output. Similar to
212
        put()'s node param, but with the input column name prefixed by
213
        input_col_prefix in place of the column value.
214
    @return sql_gen.Col Where the pkeys (from INSERT RETURNING) are made
215
        available
216
    '''
217
    in_table = sql_gen.as_Table(in_table)
218
    sql_io.mk_errors_table(db, in_table)
219
    in_table.set_srcs([in_table], overwrite=False)
220
    db.src = strings.ustr(in_table)
221
    
222
    db.autoanalyze = True # but don't do this in row-based import
223
    db.autoexplain = True # but don't do this in row-based import
224
    
225
    # Subset and partition in_table
226
    # OK to do even if table already the right size because it takes <1 sec.
227
    full_in_table = in_table
228
    pkeys_loc = None # used if loop is never executed
229
    total = 0
230
    while limit == None or total < limit:
231
        # Adjust partition size if last partition
232
        this_limit = partition_size
233
        if limit != None: this_limit = min(this_limit, limit - total)
234
        
235
        # Row # is interally 0-based, but 1-based to the user
236
        db.log_debug('********** Partition: rows '+str(start+1)+'-'
237
            +str(start+this_limit)+' **********', level=1.2)
238
        
239
        # Subset in_table
240
        in_table = sql_gen.Table(strings.ustr(full_in_table),
241
            srcs=full_in_table.srcs, is_temp=True) # prepend schema to name
242
        sql.copy_table_struct(db, full_in_table, in_table)
243
        try: sql.add_row_num(db, in_table, 'row_num')
244
        except sql.DatabaseErrors: pass # already has pkey
245
        cur = sql.insert_select(db, in_table, None, sql.mk_select(db,
246
            full_in_table, limit=this_limit, start=start))
247
        
248
        this_ct = cur.rowcount
249
        total += this_ct
250
        start += this_ct # advance start to fetch next set
251
        if this_ct == 0: break # in_table size is multiple of partition_size
252
        
253
        # Import data
254
        pkeys_loc = put(db, node, row_ins_ct_ref, on_error, col_defaults,
255
            in_table)
256
        if in_row_ct_ref != None: in_row_ct_ref[0] += this_ct
257
        
258
        sql.empty_temp(db, in_table)
259
        
260
        if this_ct < partition_size: break # partial partition = last
261
        
262
        # Work around PostgreSQL's temp table disk space leak
263
        db.reconnect()
264
    
265
    return pkeys_loc
(12-12/44)