1
|
#!/usr/bin/env python
|
2
|
# Maps one datasource to another, using a map spreadsheet if needed
|
3
|
# For outputting an XML file to a PostgreSQL database, use the general format of
|
4
|
# http://vegbank.org/vegdocs/xml/vegbank_example_ver1.0.2.xml
|
5
|
|
6
|
import os.path
|
7
|
import sys
|
8
|
import xml.dom.minidom as minidom
|
9
|
|
10
|
sys.path.append(os.path.dirname(__file__)+"/../lib")
|
11
|
|
12
|
import exc
|
13
|
import opts
|
14
|
import Parser
|
15
|
import sql
|
16
|
import strings
|
17
|
import util
|
18
|
import xml_dom
|
19
|
import xml_func
|
20
|
|
21
|
def metadata_value(name):
|
22
|
if type(name) == str and name.startswith(':'): return name[1:]
|
23
|
else: return None
|
24
|
|
25
|
def main():
|
26
|
ex_tracker = exc.ExTracker()
|
27
|
|
28
|
env_names = []
|
29
|
def usage_err():
|
30
|
raise SystemExit('Usage: ' + opts.env_usage(env_names, True)
|
31
|
+' [commit=1] [test=1] [verbose=1] [debug=1] '+sys.argv[0]
|
32
|
+' [map_path...] [<input] [>output]')
|
33
|
limit = opts.get_env_var('n', None, env_names)
|
34
|
if limit != None: limit = int(limit)
|
35
|
test = opts.env_flag('test')
|
36
|
commit = not test and opts.env_flag('commit') # never commit in test mode
|
37
|
debug = opts.env_flag('debug')
|
38
|
verbose = debug or opts.env_flag('verbose')
|
39
|
|
40
|
def log(msg, on=verbose):
|
41
|
if on: sys.stderr.write(msg)
|
42
|
def log_start(action, on=verbose): log(action+'...', on)
|
43
|
def log_done(on=verbose): log('Done\n', on)
|
44
|
|
45
|
# Get db config from env vars
|
46
|
db_config_names = ['engine', 'host', 'user', 'password', 'database']
|
47
|
def get_db_config(prefix):
|
48
|
return opts.get_env_vars(db_config_names, prefix, env_names)
|
49
|
in_db_config = get_db_config('in')
|
50
|
out_db_config = get_db_config('out')
|
51
|
in_is_db = 'engine' in in_db_config
|
52
|
out_is_db = 'engine' in out_db_config
|
53
|
|
54
|
# Parse args
|
55
|
map_paths = sys.argv[1:]
|
56
|
if map_paths == []:
|
57
|
if in_is_db or not out_is_db: usage_err()
|
58
|
else: map_paths = [None]
|
59
|
|
60
|
def connect_db(db_config):
|
61
|
log_start('Connecting to '+sql.db_config_str(db_config))
|
62
|
db = sql.connect(db_config)
|
63
|
log_done()
|
64
|
return db
|
65
|
|
66
|
def process_input(root, process_row, map_path):
|
67
|
'''Inputs datasource to XML tree, mapping if needed'''
|
68
|
# Load map header
|
69
|
in_is_xpaths = True
|
70
|
out_label = None
|
71
|
if map_path != None:
|
72
|
import copy
|
73
|
import csv
|
74
|
|
75
|
import xpath
|
76
|
|
77
|
metadata = []
|
78
|
mappings = []
|
79
|
stream = open(map_path, 'rb')
|
80
|
reader = csv.reader(stream)
|
81
|
in_label, out_label = reader.next()[:2]
|
82
|
def split_col_name(name):
|
83
|
name, sep, root = name.partition(':')
|
84
|
return name, sep != '', root
|
85
|
in_label, in_is_xpaths, in_root = split_col_name(in_label)
|
86
|
out_label, out_is_xpaths, out_root = split_col_name(out_label)
|
87
|
assert out_is_xpaths # CSV output not supported yet
|
88
|
has_types = out_root.startswith('/*s/') # outer elements are types
|
89
|
for row in reader:
|
90
|
in_, out = row[:2]
|
91
|
if out != '':
|
92
|
if out_is_xpaths: out = xpath.parse(out_root+out)
|
93
|
mappings.append((in_, out))
|
94
|
stream.close()
|
95
|
|
96
|
root.ownerDocument.documentElement.tagName = out_label
|
97
|
in_is_xml = in_is_xpaths and not in_is_db
|
98
|
|
99
|
if in_is_xml:
|
100
|
doc0 = minidom.parse(sys.stdin)
|
101
|
if out_label == None: out_label = doc0.documentElement.tagName
|
102
|
|
103
|
def process_rows(get_value, rows):
|
104
|
'''Processes input values
|
105
|
@param get_value f(in_, row):str
|
106
|
'''
|
107
|
for i, row in enumerate(rows):
|
108
|
if not (limit == None or i < limit): break
|
109
|
row_id = str(i)
|
110
|
for in_, out in mappings:
|
111
|
value = metadata_value(in_)
|
112
|
if value == None:
|
113
|
log_start('Getting '+str(in_), debug)
|
114
|
value = get_value(in_, row)
|
115
|
log_done(debug)
|
116
|
if value != None: xpath.put_obj(root, out, row_id,
|
117
|
has_types, strings.cleanup(value))
|
118
|
process_row(row)
|
119
|
sys.stderr.write('Processed '+str(i+1)+' input rows\n')
|
120
|
|
121
|
if map_path == None:
|
122
|
iter_ = xml_dom.NodeElemIter(doc0.documentElement)
|
123
|
util.skip(iter_, xml_dom.is_text) # skip metadata
|
124
|
for child in iter_:
|
125
|
root.appendChild(child)
|
126
|
process_row(child)
|
127
|
elif in_is_db:
|
128
|
assert in_is_xpaths
|
129
|
|
130
|
import db_xml
|
131
|
|
132
|
in_root_xml = xpath.path2xml(in_root)
|
133
|
for i, mapping in enumerate(mappings):
|
134
|
in_, out = mapping
|
135
|
if metadata_value(in_) == None:
|
136
|
mappings[i] = (xpath.path2xml(in_root+'/'+in_), out)
|
137
|
|
138
|
in_db = connect_db(in_db_config)
|
139
|
in_pkeys = {}
|
140
|
def get_value(in_, row):
|
141
|
pkey, = row
|
142
|
in_ = in_.cloneNode(True) # don't modify orig value!
|
143
|
xml_dom.set_id(xpath.get(in_, in_root), pkey)
|
144
|
value = sql.value_or_none(db_xml.get(in_db, in_, in_pkeys))
|
145
|
if value != None: return str(value)
|
146
|
else: return None
|
147
|
process_rows(get_value, sql.rows(db_xml.get(in_db, in_root_xml,
|
148
|
in_pkeys, limit)))
|
149
|
in_db.close()
|
150
|
elif in_is_xml:
|
151
|
def get_value(in_, row):
|
152
|
node = xpath.get(row, in_)
|
153
|
if node != None: return xml_dom.value(node)
|
154
|
else: return None
|
155
|
row0 = xpath.get(doc0.documentElement, in_root)
|
156
|
process_rows(get_value, xml_dom.NodeElemIter(row0.parentNode))
|
157
|
else: # input is CSV
|
158
|
map_ = dict(mappings)
|
159
|
reader = csv.reader(sys.stdin)
|
160
|
cols = reader.next()
|
161
|
col_idxs = dict([(value, idx) for idx, value in enumerate(cols)])
|
162
|
for i, mapping in enumerate(mappings):
|
163
|
in_, out = mapping
|
164
|
if metadata_value(in_) == None:
|
165
|
try: mappings[i] = (col_idxs[in_], out)
|
166
|
except KeyError: pass
|
167
|
|
168
|
def get_value(in_, row):
|
169
|
value = row[in_]
|
170
|
if value != '': return value
|
171
|
else: return None
|
172
|
process_rows(get_value, reader)
|
173
|
|
174
|
def process_inputs(root, process_row):
|
175
|
for map_path in map_paths: process_input(root, process_row, map_path)
|
176
|
|
177
|
# Output XML tree
|
178
|
doc = xml_dom.create_doc()
|
179
|
root = doc.documentElement
|
180
|
if out_is_db:
|
181
|
import db_xml
|
182
|
|
183
|
out_db = connect_db(out_db_config)
|
184
|
out_pkeys = {}
|
185
|
try:
|
186
|
if test: sql.empty_db(out_db)
|
187
|
row_ct_ref = [0]
|
188
|
|
189
|
def process_row(input_row):
|
190
|
def on_error(e):
|
191
|
exc.add_msg(e, 'output row:\n'+str(root))
|
192
|
exc.add_msg(e, 'input row:\n'+str(input_row))
|
193
|
ex_tracker.track(e)
|
194
|
|
195
|
xml_func.process(root, on_error)
|
196
|
if not xml_dom.is_empty(root):
|
197
|
assert xml_dom.has_one_child(root)
|
198
|
try:
|
199
|
sql.with_savepoint(out_db, lambda: db_xml.put(out_db,
|
200
|
root.firstChild, out_pkeys, row_ct_ref, on_error))
|
201
|
if commit: out_db.commit()
|
202
|
except sql.DatabaseErrors, e: on_error(e)
|
203
|
root.clear()
|
204
|
|
205
|
process_inputs(root, process_row)
|
206
|
sys.stdout.write('Inserted '+str(row_ct_ref[0])+
|
207
|
' new rows into database\n')
|
208
|
finally:
|
209
|
out_db.rollback()
|
210
|
out_db.close()
|
211
|
else: # output is XML
|
212
|
def process_row(input_row): pass
|
213
|
process_inputs(root, process_row)
|
214
|
xml_func.process(root)
|
215
|
doc.writexml(sys.stdout, **xml_dom.prettyxml_config)
|
216
|
|
217
|
try: main()
|
218
|
except Parser.SyntaxException, e: raise SystemExit(str(e))
|