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