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
|
7
|
import os.path
|
8
|
import sys
|
9
|
import xml.dom.minidom
|
10
|
|
11
|
sys.path.append(os.path.dirname(__file__)+"/lib")
|
12
|
|
13
|
import opts
|
14
|
|
15
|
def main():
|
16
|
# Get db config from env vars
|
17
|
db_config_names = ['host', 'user', 'password', 'database']
|
18
|
env_names = []
|
19
|
def get_db_config(prefix):
|
20
|
return opts.get_env_vars(db_config_names, prefix, env_names)
|
21
|
in_db_config = get_db_config('in')
|
22
|
out_db_config = get_db_config('out')
|
23
|
in_is_db = in_db_config != None
|
24
|
out_is_db = out_db_config != None
|
25
|
|
26
|
# Parse args
|
27
|
map_path = None
|
28
|
try: _prog_name, map_path = sys.argv
|
29
|
except ValueError:
|
30
|
if in_is_db or not out_is_db: raise SystemExit('Usage: '
|
31
|
+opts.env_usage(env_names, True)+' [commit=1] '+sys.argv[0]
|
32
|
+' [map_path] [<input] [>output]')
|
33
|
commit = opts.env_flag('commit')
|
34
|
|
35
|
# Load map header
|
36
|
in_is_xml = True
|
37
|
if map_path != None:
|
38
|
import copy
|
39
|
import csv
|
40
|
|
41
|
import xpath
|
42
|
|
43
|
mappings = []
|
44
|
stream = open(map_path, 'rb')
|
45
|
reader = csv.reader(stream)
|
46
|
src, dest = reader.next()[:2]
|
47
|
def split_col_name(name):
|
48
|
name, sep, root = name.partition(':')
|
49
|
return name, sep != '', root
|
50
|
src, in_is_xml, src_root = split_col_name(src)
|
51
|
dest, out_is_xml, dest_root = split_col_name(dest)
|
52
|
assert out_is_xml
|
53
|
has_types = dest_root.startswith('/*s/') # outer elements are types
|
54
|
for row in reader:
|
55
|
in_, out = row[:2]
|
56
|
if out != '':
|
57
|
try: out = xpath.parse(dest_root+out)
|
58
|
except SyntaxException, ex: raise SystemExit(str(ex))
|
59
|
mappings.append((in_, out))
|
60
|
stream.close()
|
61
|
|
62
|
# Input datasource to XML tree, mapping if needed
|
63
|
if in_is_xml: doc = xml.dom.minidom.parse(sys.stdin)
|
64
|
if map_path != None:
|
65
|
from Parser import SyntaxException
|
66
|
import xml_xpath
|
67
|
|
68
|
out_doc = xml.dom.minidom.getDOMImplementation().createDocument(None,
|
69
|
dest, None)
|
70
|
if in_is_xml: raise Exception('XML-XML mapping not supported yet')
|
71
|
elif in_is_db: raise Exception('DB-XML mapping not supported yet')
|
72
|
else: # input is CSV
|
73
|
map_ = dict(mappings)
|
74
|
reader = csv.reader(sys.stdin)
|
75
|
fieldnames = reader.next()
|
76
|
row_idx = 0
|
77
|
for row in reader:
|
78
|
row_id = str(row_idx)
|
79
|
for idx, name in enumerate(fieldnames):
|
80
|
value = row[idx]
|
81
|
if value != '' and name in map_:
|
82
|
path = copy.deepcopy(map_[name]) # don't modify value!
|
83
|
xpath.set_id(path, row_id, has_types)
|
84
|
xpath.set_value(path, value)
|
85
|
xml_xpath.get(out_doc, path, True)
|
86
|
row_idx += 1
|
87
|
doc = out_doc
|
88
|
|
89
|
# Output XML tree
|
90
|
if out_db_config != None: # output is database
|
91
|
import psycopg2
|
92
|
from psycopg2.extensions import ISOLATION_LEVEL_SERIALIZABLE
|
93
|
|
94
|
import db_xml
|
95
|
|
96
|
db = psycopg2.connect(**out_db_config)
|
97
|
db.set_isolation_level(ISOLATION_LEVEL_SERIALIZABLE)
|
98
|
try:
|
99
|
row_ct_ref = [0]
|
100
|
db_xml.xml2db(db, doc.documentElement, row_ct_ref)
|
101
|
print 'Inserted '+str(row_ct_ref[0])+' rows'
|
102
|
if commit: db.commit()
|
103
|
finally:
|
104
|
db.rollback()
|
105
|
db.close()
|
106
|
else: doc.writexml(sys.stdout, addindent=' ', newl='\n') # output is XML
|
107
|
|
108
|
main()
|