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_io
11
import sql_gen
12
import strings
13
import util
14
import xml_dom
15
import xml_func
16
import xpath
17

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

    
20
ptr_suffix = '_id'
21

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

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

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

    
44
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
put_special_funcs = set(['_simplifyPath'])
53

    
54
def put(db, node, row_ins_ct_ref=None, on_error=exc.reraise,
55
    col_defaults={}, in_table=None, parent_ids_loc=None, next=None):
56
    '''
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
    def put_(node, in_row_ct_ref=None):
62
        return put(db, node, row_ins_ct_ref, on_error, col_defaults,
63
            in_table, parent_ids_loc, next)
64
    
65
    def on_error_(e):
66
        exc.add_msg(e, 'node:\n'+str(node))
67
        on_error(e)
68
    
69
    is_func = xml_func.is_func(node)
70
    out_table = name_of(node)
71
    
72
    # Divide children into fields and children with fkeys to parent
73
    row = {}
74
    children = []
75
    for child in xml_dom.NodeElemIter(node):
76
        child_name = name_of(child)
77
        if xml_dom.is_empty(child): row[child_name] = None
78
        elif xml_dom.is_text(child):
79
            row[child_name] = strings.to_unicode(xml_dom.value(child))
80
        else:
81
            child_value = xml_dom.value_node(child)
82
            if is_func or is_ptr(child_name) or xml_func.is_func(child_value):
83
                row[child_name] = child_value
84
            else: children.append(child)
85
    
86
    # Special handling for structural XML functions
87
    if out_table == '_simplifyPath':
88
        # Parse args
89
        def wrap_e(e): raise xml_func.SyntaxError(e)
90
        try:
91
            next = row['next'] # modifies outer next var used by put_()
92
            require = row['require']
93
            path = row['path']
94
        except KeyError, e: wrap_e(e)
95
        try: next = xpath.parse(next)
96
        except Parser.SyntaxError, e: wrap_e(e)
97
        try: next = next[0].name
98
        except IndexError, e: wrap_e(e)
99
        
100
        return put_(path)
101
    
102
    in_tables = []
103
    no_empty = set()
104
    if in_table != None:
105
        in_tables.append(in_table)
106
        no_empty.add(in_table)
107
    
108
    def pkey(table): return sql.pkey(db, table, True)
109
    
110
    # Add fkey to parent
111
    if parent_ids_loc != None:
112
        if sql_gen.is_table_col(parent_ids_loc):
113
            no_empty.add(parent_ids_loc.table)
114
        parent_ptr = node.getAttribute('fkey')
115
        if parent_ptr == '': parent_ptr = pkey(name_of(node.parentNode))
116
        row[parent_ptr] = parent_ids_loc
117
    
118
    # Divide fields into input columns and literal values
119
    parent_ids_loc = None # applies to this section
120
    for out_col, value in row.iteritems():
121
        # Handle forward pointers
122
        if xml_dom.is_node(value): row[out_col] = value = put_(value)
123
        
124
        # Translate values
125
        if isinstance(value, sql_gen.Col): # value is temp table column
126
            in_tables.append(value.table)
127
        elif util.is_str(value) and value.startswith(input_col_prefix):
128
            # value is input column
129
            row[out_col] = sql_gen.Col(strings.remove_prefix(input_col_prefix,
130
                value), in_table)
131
        else: # value is literal value
132
            row[out_col] = sql_gen.NamedCol(out_col, value)
133
    
134
    # Insert node
135
    try: pkeys_loc = sql_io.put_table(db, out_table, in_tables, row,
136
        row_ins_ct_ref, next, col_defaults, on_error_)
137
    except Exception, e:
138
        on_error_(e)
139
        return None
140
    
141
    sql.empty_temp(db, set(in_tables) - no_empty)
142
    
143
    # Insert children with fkeys to parent
144
    parent_ids_loc = pkeys_loc # applies to this section
145
    for child in children: put_(child)
146
    
147
    return pkeys_loc
148

    
149
def get(db, node, limit=None, start=None):
150
    def pkey(table): return sql.pkey(db, table)
151
    
152
    node = node.firstChild
153
    table = name_of(node)
154
    pkey_ = pkey(table)
155
    
156
    fields = []
157
    conds = {}
158
    for child in xml_dom.NodeElemIter(node):
159
        child_name = name_of(child)
160
        if xml_dom.is_empty(child): fields.append(child_name)
161
        elif xml_dom.is_text(child): conds[child_name] = xml_dom.value(child)
162
        else: raise Exception('Joins not supported yet')
163
    id_ = xml_dom.get_id(node)
164
    if id_ != None: conds[pkey(table)] = id_ # replace any existing pkey value
165
    if fields == []: fields.append(pkey_)
166
    
167
    return sql.select(db, table, fields, conds, limit, start)
168

    
169
# Controls when and how put_table() will partition the input table
170
partition_size = 500000 # rows
171

    
172
input_col_prefix = '$'
173

    
174
def put_table(db, node, in_table, in_row_ct_ref=None, row_ins_ct_ref=None,
175
    limit=None, start=0, on_error=exc.reraise, col_defaults={}):
176
    '''
177
    @param node The XML tree that transforms the input to the output. Similar to
178
        put()'s node param, but with the input column name prefixed by
179
        input_col_prefix in place of the column value.
180
    @return sql_gen.Col Where the pkeys (from INSERT RETURNING) are made
181
        available
182
    '''
183
    in_table = sql_gen.as_Table(in_table)
184
    in_table.set_srcs([in_table], overwrite=False)
185
    db.src = str(in_table)
186
    
187
    db.autoanalyze = True # but don't do this in row-based import
188
    db.autoexplain = True # but don't do this in row-based import
189
    
190
    # Subset and partition in_table
191
    # OK to do even if table already the right size because it takes <1 sec.
192
    full_in_table = in_table
193
    total = 0
194
    while limit == None or total < limit:
195
        # Adjust partition size if last partition
196
        this_limit = partition_size
197
        if limit != None: this_limit = min(this_limit, limit - total)
198
        
199
        # Row # is interally 0-based, but 1-based to the user
200
        db.log_debug('********** Partition: rows '+str(start+1)+'-'
201
            +str(start+this_limit)+' **********', level=1.2)
202
        
203
        # Subset in_table
204
        in_table = copy.copy(full_in_table) # don't modify input!
205
        in_table.name = str(in_table) # prepend schema
206
        cur = sql.run_query_into(db, sql.mk_select(db, full_in_table,
207
            limit=this_limit, start=start), into=in_table, add_pkey_=True)
208
            # full_in_table will be shadowed (hidden) by created temp table
209
        
210
        this_ct = cur.rowcount
211
        total += this_ct
212
        start += this_ct # advance start to fetch next set
213
        if this_ct == 0: break # in_table size is multiple of partition_size
214
        
215
        # Recurse
216
        pkeys_loc = put(db, node, row_ins_ct_ref, on_error,
217
            col_defaults, in_table)
218
        if in_row_ct_ref != None: in_row_ct_ref[0] += this_ct
219
        
220
        sql.empty_temp(db, in_table)
221
        
222
        if this_ct < partition_size: break # partial partition = last
223
        
224
        # Work around PostgreSQL's temp table disk space leak
225
        db.reconnect()
226
    
227
    return pkeys_loc
(9-9/37)