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
|
def get(db, node, limit=None, start=None):
|
45
|
def pkey(table): return sql.pkey(db, table)
|
46
|
|
47
|
node = node.firstChild
|
48
|
table = name_of(node)
|
49
|
pkey_ = pkey(table)
|
50
|
|
51
|
fields = []
|
52
|
conds = {}
|
53
|
for child in xml_dom.NodeElemIter(node):
|
54
|
child_name = name_of(child)
|
55
|
if xml_dom.is_empty(child): fields.append(child_name)
|
56
|
elif xml_dom.is_text(child): conds[child_name] = xml_dom.value(child)
|
57
|
else: raise Exception('Joins not supported yet')
|
58
|
id_ = xml_dom.get_id(node)
|
59
|
if id_ != None: conds[pkey(table)] = id_ # replace any existing pkey value
|
60
|
if fields == []: fields.append(pkey_)
|
61
|
|
62
|
return sql.select(db, table, fields, conds, limit, start)
|
63
|
|
64
|
def put(db, node, row_ct_ref=None, on_error=exc.raise_, pool=None,
|
65
|
store_ids=False, parent_id=None):
|
66
|
'''store_ids enables searching the tree for missing fields'''
|
67
|
def pkey(table): return sql.pkey(db, table, True)
|
68
|
|
69
|
def put_(node, parent_id=None):
|
70
|
args = (db, node, row_ct_ref, on_error, pool, store_ids, parent_id)
|
71
|
if parent_id != None and pool != None: pool.apply_async(put, args)
|
72
|
else: return put(*args)
|
73
|
|
74
|
def on_error_(e):
|
75
|
exc.add_msg(e, 'node:\n'+str(node))
|
76
|
on_error(e)
|
77
|
|
78
|
table = name_of(node)
|
79
|
try: pkey_ = pkey(table)
|
80
|
except sql.DatabaseErrors, e: on_error_(e); return None
|
81
|
row = {}
|
82
|
children = []
|
83
|
|
84
|
# Divide children into fields and children with fkeys to parent
|
85
|
for child in xml_dom.NodeElemIter(node):
|
86
|
child_name = name_of(child)
|
87
|
if xml_dom.is_empty(child): row[child_name] = None
|
88
|
elif xml_dom.is_text(child):
|
89
|
row[child_name] = strings.to_unicode(xml_dom.value(child))
|
90
|
elif is_ptr(child_name): row[child_name] = put_(ptr_target(child))
|
91
|
else: children.append(child)
|
92
|
|
93
|
# Add fkey to parent
|
94
|
if parent_id != None:
|
95
|
parent_ptr = node.getAttribute('fkey')
|
96
|
if parent_ptr == '': parent_ptr = pkey(name_of(node.parentNode))
|
97
|
row[parent_ptr] = parent_id
|
98
|
|
99
|
# Insert node
|
100
|
try:
|
101
|
for try_num in xrange(2):
|
102
|
try:
|
103
|
id_ = sql_io.put(db, table, row, pkey_, row_ct_ref)
|
104
|
if store_ids: xml_dom.set_id(node, id_)
|
105
|
break
|
106
|
except sql.NullValueException, e:
|
107
|
col = e.cols[0]
|
108
|
if try_num > 0: raise # exception still raised after retry
|
109
|
if store_ids and is_ptr(col):
|
110
|
# Search for required column in ancestors and their children
|
111
|
target = find_by_name(node, ptr_type_guess(col))
|
112
|
if target == None: raise
|
113
|
row[col] = xml_dom.get_id(target)
|
114
|
else: raise
|
115
|
except sql.DatabaseErrors, e: on_error_(e); return None
|
116
|
|
117
|
# Insert children with fkeys to parent
|
118
|
for child in children: put_(child, id_)
|
119
|
|
120
|
return id_
|
121
|
|
122
|
class ColRef:
|
123
|
'''A reference to a table column'''
|
124
|
def __init__(self, name, idx):
|
125
|
self.name = name
|
126
|
self.idx = idx
|
127
|
|
128
|
def __str__(self): return self.name
|
129
|
|
130
|
# Controls when and how put_table() will partition the input table
|
131
|
partition_size = 500000 # rows
|
132
|
|
133
|
input_col_prefix = '$'
|
134
|
|
135
|
put_table_special_funcs = set(['_simplifyPath'])
|
136
|
|
137
|
def put_table(db, node, in_table, in_row_ct_ref=None, row_ins_ct_ref=None,
|
138
|
limit=None, start=0, on_error=exc.raise_, col_defaults={}):
|
139
|
'''
|
140
|
@param node The XML tree that transforms the input to the output. Similar to
|
141
|
put()'s node param, but with the input column name prefixed by
|
142
|
input_col_prefix in place of the column value.
|
143
|
@return sql_gen.Col Where the pkeys (from INSERT RETURNING) are made
|
144
|
available
|
145
|
'''
|
146
|
in_table = sql_gen.as_Table(in_table)
|
147
|
in_table.set_srcs([in_table], overwrite=False)
|
148
|
db.src = str(in_table)
|
149
|
|
150
|
db.autoanalyze = True # but don't do this in row-based import
|
151
|
db.autoexplain = True # but don't do this in row-based import
|
152
|
|
153
|
# Import col_defaults
|
154
|
for col, node_ in col_defaults.items():
|
155
|
col_defaults[col] = _put_table_part(db, node_, None, row_ins_ct_ref,
|
156
|
on_error)
|
157
|
|
158
|
# Subset and partition in_table
|
159
|
# OK to do even if table already the right size because it takes <1 sec.
|
160
|
full_in_table = in_table
|
161
|
total = 0
|
162
|
while limit == None or total < limit:
|
163
|
# Adjust partition size if last partition
|
164
|
this_limit = partition_size
|
165
|
if limit != None: this_limit = min(this_limit, limit - total)
|
166
|
|
167
|
# Row # is interally 0-based, but 1-based to the user
|
168
|
db.log_debug('********** Partition: rows '+str(start+1)+'-'
|
169
|
+str(start+this_limit)+' **********', level=1.2)
|
170
|
|
171
|
# Subset in_table
|
172
|
in_table = copy.copy(full_in_table) # don't modify input!
|
173
|
in_table.name = str(in_table) # prepend schema
|
174
|
cur = sql.run_query_into(db, sql.mk_select(db, full_in_table,
|
175
|
limit=this_limit, start=start), into=in_table, add_pkey_=True)
|
176
|
# full_in_table will be shadowed (hidden) by created temp table
|
177
|
|
178
|
this_ct = cur.rowcount
|
179
|
total += this_ct
|
180
|
start += this_ct # advance start to fetch next set
|
181
|
if this_ct == 0: break # in_table size is multiple of partition_size
|
182
|
|
183
|
# Recurse
|
184
|
pkeys_loc = _put_table_part(db, node, in_table, row_ins_ct_ref,
|
185
|
on_error, col_defaults)
|
186
|
if in_row_ct_ref != None: in_row_ct_ref[0] += this_ct
|
187
|
|
188
|
sql.empty_temp(db, in_table)
|
189
|
|
190
|
if this_ct < partition_size: break # partial partition = last
|
191
|
|
192
|
# Work around PostgreSQL's temp table disk space leak
|
193
|
db.reconnect()
|
194
|
|
195
|
return pkeys_loc
|
196
|
|
197
|
def _put_table_part(db, node, in_table, row_ins_ct_ref, on_error,
|
198
|
col_defaults={}, parent_ids_loc=None, next=None):
|
199
|
'''Helper function for put_table() only; should not be called directly'''
|
200
|
def put_table_(node, in_row_ct_ref=None):
|
201
|
return _put_table_part(db, node, in_table, row_ins_ct_ref, on_error,
|
202
|
col_defaults, parent_ids_loc, next)
|
203
|
|
204
|
is_func = xml_func.is_func(node)
|
205
|
out_table = name_of(node)
|
206
|
|
207
|
# Divide children into fields and children with fkeys to parent
|
208
|
row = {}
|
209
|
children = []
|
210
|
for child in xml_dom.NodeElemIter(node):
|
211
|
child_name = name_of(child)
|
212
|
if xml_dom.is_empty(child): row[child_name] = None
|
213
|
elif xml_dom.is_text(child):
|
214
|
row[child_name] = strings.to_unicode(xml_dom.value(child))
|
215
|
else:
|
216
|
child_value = xml_dom.value_node(child)
|
217
|
if is_func or is_ptr(child_name) or xml_func.is_func(child_value):
|
218
|
row[child_name] = child_value
|
219
|
else: children.append(child)
|
220
|
|
221
|
# Special handling for structural XML functions
|
222
|
if out_table == '_simplifyPath':
|
223
|
# Parse args
|
224
|
def wrap_e(e): raise xml_func.SyntaxError(e)
|
225
|
try:
|
226
|
next = row['next'] # modifies outer next var used by put_table_()
|
227
|
require = row['require']
|
228
|
path = row['path']
|
229
|
except KeyError, e: wrap_e(e)
|
230
|
try: next = xpath.parse(next)
|
231
|
except Parser.SyntaxError, e: wrap_e(e)
|
232
|
try: next = next[0].name
|
233
|
except IndexError, e: wrap_e(e)
|
234
|
|
235
|
return put_table_(path)
|
236
|
|
237
|
in_tables = []
|
238
|
no_empty = set()
|
239
|
if in_table != None:
|
240
|
in_tables.append(in_table)
|
241
|
no_empty.add(in_table)
|
242
|
|
243
|
def pkey(table): return sql.pkey(db, table, True)
|
244
|
|
245
|
# Add fkey to parent
|
246
|
if parent_ids_loc != None:
|
247
|
if sql_gen.is_table_col(parent_ids_loc):
|
248
|
no_empty.add(parent_ids_loc.table)
|
249
|
parent_ptr = node.getAttribute('fkey')
|
250
|
if parent_ptr == '': parent_ptr = pkey(name_of(node.parentNode))
|
251
|
row[parent_ptr] = parent_ids_loc
|
252
|
|
253
|
# Divide fields into input columns and literal values
|
254
|
parent_ids_loc = None # applies to this section
|
255
|
for out_col, value in row.iteritems():
|
256
|
# Handle forward pointers
|
257
|
if xml_dom.is_node(value): row[out_col] = value = put_table_(value)
|
258
|
|
259
|
# Translate values
|
260
|
if isinstance(value, sql_gen.Col): # value is temp table column
|
261
|
in_tables.append(value.table)
|
262
|
elif util.is_str(value) and value.startswith(input_col_prefix):
|
263
|
# value is input column
|
264
|
row[out_col] = sql_gen.Col(strings.remove_prefix(input_col_prefix,
|
265
|
value), in_table)
|
266
|
else: # value is literal value
|
267
|
row[out_col] = sql_gen.NamedCol(out_col, value)
|
268
|
|
269
|
# Insert node
|
270
|
pkeys_loc = sql_io.put_table(db, out_table, in_tables, row, row_ins_ct_ref,
|
271
|
next, col_defaults, on_error)
|
272
|
|
273
|
sql.empty_temp(db, set(in_tables) - no_empty)
|
274
|
|
275
|
# Insert children with fkeys to parent
|
276
|
parent_ids_loc = pkeys_loc # applies to this section
|
277
|
for child in children: put_table_(child)
|
278
|
|
279
|
return pkeys_loc
|