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.raise_,
|
55
|
col_defaults={}, in_table=None, parent_ids_loc=None, next=None):
|
56
|
def put_(node, in_row_ct_ref=None):
|
57
|
return put(db, node, row_ins_ct_ref, on_error, col_defaults,
|
58
|
in_table, parent_ids_loc, next)
|
59
|
|
60
|
def on_error_(e):
|
61
|
exc.add_msg(e, 'node:\n'+str(node))
|
62
|
on_error(e)
|
63
|
|
64
|
is_func = xml_func.is_func(node)
|
65
|
out_table = name_of(node)
|
66
|
|
67
|
# Divide children into fields and children with fkeys to parent
|
68
|
row = {}
|
69
|
children = []
|
70
|
for child in xml_dom.NodeElemIter(node):
|
71
|
child_name = name_of(child)
|
72
|
if xml_dom.is_empty(child): row[child_name] = None
|
73
|
elif xml_dom.is_text(child):
|
74
|
row[child_name] = strings.to_unicode(xml_dom.value(child))
|
75
|
else:
|
76
|
child_value = xml_dom.value_node(child)
|
77
|
if is_func or is_ptr(child_name) or xml_func.is_func(child_value):
|
78
|
row[child_name] = child_value
|
79
|
else: children.append(child)
|
80
|
|
81
|
# Special handling for structural XML functions
|
82
|
if out_table == '_simplifyPath':
|
83
|
# Parse args
|
84
|
def wrap_e(e): raise xml_func.SyntaxError(e)
|
85
|
try:
|
86
|
next = row['next'] # modifies outer next var used by put_()
|
87
|
require = row['require']
|
88
|
path = row['path']
|
89
|
except KeyError, e: wrap_e(e)
|
90
|
try: next = xpath.parse(next)
|
91
|
except Parser.SyntaxError, e: wrap_e(e)
|
92
|
try: next = next[0].name
|
93
|
except IndexError, e: wrap_e(e)
|
94
|
|
95
|
return put_(path)
|
96
|
|
97
|
in_tables = []
|
98
|
no_empty = set()
|
99
|
if in_table != None:
|
100
|
in_tables.append(in_table)
|
101
|
no_empty.add(in_table)
|
102
|
|
103
|
def pkey(table): return sql.pkey(db, table, True)
|
104
|
|
105
|
# Add fkey to parent
|
106
|
if parent_ids_loc != None:
|
107
|
if sql_gen.is_table_col(parent_ids_loc):
|
108
|
no_empty.add(parent_ids_loc.table)
|
109
|
parent_ptr = node.getAttribute('fkey')
|
110
|
if parent_ptr == '': parent_ptr = pkey(name_of(node.parentNode))
|
111
|
row[parent_ptr] = parent_ids_loc
|
112
|
|
113
|
# Divide fields into input columns and literal values
|
114
|
parent_ids_loc = None # applies to this section
|
115
|
for out_col, value in row.iteritems():
|
116
|
# Handle forward pointers
|
117
|
if xml_dom.is_node(value): row[out_col] = value = put_(value)
|
118
|
|
119
|
# Translate values
|
120
|
if isinstance(value, sql_gen.Col): # value is temp table column
|
121
|
in_tables.append(value.table)
|
122
|
elif util.is_str(value) and value.startswith(input_col_prefix):
|
123
|
# value is input column
|
124
|
row[out_col] = sql_gen.Col(strings.remove_prefix(input_col_prefix,
|
125
|
value), in_table)
|
126
|
else: # value is literal value
|
127
|
row[out_col] = sql_gen.NamedCol(out_col, value)
|
128
|
|
129
|
# Insert node
|
130
|
pkeys_loc = sql_io.put_table(db, out_table, in_tables, row, row_ins_ct_ref,
|
131
|
next, col_defaults, on_error_)
|
132
|
|
133
|
sql.empty_temp(db, set(in_tables) - no_empty)
|
134
|
|
135
|
# Insert children with fkeys to parent
|
136
|
parent_ids_loc = pkeys_loc # applies to this section
|
137
|
for child in children: put_(child)
|
138
|
|
139
|
return pkeys_loc
|
140
|
|
141
|
def get(db, node, limit=None, start=None):
|
142
|
def pkey(table): return sql.pkey(db, table)
|
143
|
|
144
|
node = node.firstChild
|
145
|
table = name_of(node)
|
146
|
pkey_ = pkey(table)
|
147
|
|
148
|
fields = []
|
149
|
conds = {}
|
150
|
for child in xml_dom.NodeElemIter(node):
|
151
|
child_name = name_of(child)
|
152
|
if xml_dom.is_empty(child): fields.append(child_name)
|
153
|
elif xml_dom.is_text(child): conds[child_name] = xml_dom.value(child)
|
154
|
else: raise Exception('Joins not supported yet')
|
155
|
id_ = xml_dom.get_id(node)
|
156
|
if id_ != None: conds[pkey(table)] = id_ # replace any existing pkey value
|
157
|
if fields == []: fields.append(pkey_)
|
158
|
|
159
|
return sql.select(db, table, fields, conds, limit, start)
|
160
|
|
161
|
# Controls when and how put_table() will partition the input table
|
162
|
partition_size = 500000 # rows
|
163
|
|
164
|
input_col_prefix = '$'
|
165
|
|
166
|
def put_table(db, node, in_table, in_row_ct_ref=None, row_ins_ct_ref=None,
|
167
|
limit=None, start=0, on_error=exc.raise_, col_defaults={}):
|
168
|
'''
|
169
|
@param node The XML tree that transforms the input to the output. Similar to
|
170
|
put()'s node param, but with the input column name prefixed by
|
171
|
input_col_prefix in place of the column value.
|
172
|
@return sql_gen.Col Where the pkeys (from INSERT RETURNING) are made
|
173
|
available
|
174
|
'''
|
175
|
in_table = sql_gen.as_Table(in_table)
|
176
|
in_table.set_srcs([in_table], overwrite=False)
|
177
|
db.src = str(in_table)
|
178
|
|
179
|
db.autoanalyze = True # but don't do this in row-based import
|
180
|
db.autoexplain = True # but don't do this in row-based import
|
181
|
|
182
|
# Import col_defaults
|
183
|
for col, node_ in col_defaults.items():
|
184
|
col_defaults[col] = put(db, node_, row_ins_ct_ref, on_error)
|
185
|
|
186
|
# Subset and partition in_table
|
187
|
# OK to do even if table already the right size because it takes <1 sec.
|
188
|
full_in_table = in_table
|
189
|
total = 0
|
190
|
while limit == None or total < limit:
|
191
|
# Adjust partition size if last partition
|
192
|
this_limit = partition_size
|
193
|
if limit != None: this_limit = min(this_limit, limit - total)
|
194
|
|
195
|
# Row # is interally 0-based, but 1-based to the user
|
196
|
db.log_debug('********** Partition: rows '+str(start+1)+'-'
|
197
|
+str(start+this_limit)+' **********', level=1.2)
|
198
|
|
199
|
# Subset in_table
|
200
|
in_table = copy.copy(full_in_table) # don't modify input!
|
201
|
in_table.name = str(in_table) # prepend schema
|
202
|
cur = sql.run_query_into(db, sql.mk_select(db, full_in_table,
|
203
|
limit=this_limit, start=start), into=in_table, add_pkey_=True)
|
204
|
# full_in_table will be shadowed (hidden) by created temp table
|
205
|
|
206
|
this_ct = cur.rowcount
|
207
|
total += this_ct
|
208
|
start += this_ct # advance start to fetch next set
|
209
|
if this_ct == 0: break # in_table size is multiple of partition_size
|
210
|
|
211
|
# Recurse
|
212
|
pkeys_loc = put(db, node, row_ins_ct_ref, on_error,
|
213
|
col_defaults, in_table)
|
214
|
if in_row_ct_ref != None: in_row_ct_ref[0] += this_ct
|
215
|
|
216
|
sql.empty_temp(db, in_table)
|
217
|
|
218
|
if this_ct < partition_size: break # partial partition = last
|
219
|
|
220
|
# Work around PostgreSQL's temp table disk space leak
|
221
|
db.reconnect()
|
222
|
|
223
|
return pkeys_loc
|