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
|
def env_flag(name): return name in os.environ and os.environ[name] != ''
|
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
|
has_all = True
|
21
|
db_config = {}
|
22
|
for name in db_config_names:
|
23
|
env_name = prefix+'_'+name
|
24
|
env_names.append(env_name)
|
25
|
if env_name in os.environ: db_config[name] = os.environ[env_name]
|
26
|
else: has_all = False
|
27
|
if has_all: return db_config
|
28
|
else: return None
|
29
|
from_db_config = get_db_config('from')
|
30
|
to_db_config = get_db_config('to')
|
31
|
uses_map = not (from_db_config == None and to_db_config != None)
|
32
|
|
33
|
# Parse args
|
34
|
prog_name = sys.argv[0]
|
35
|
try: prog_name, map_path = sys.argv
|
36
|
except ValueError:
|
37
|
if uses_map: raise SystemExit('Usage: env'+''.join(map(lambda name:
|
38
|
' ['+name+'=...]', env_names))+' [commit=1] '+prog_name
|
39
|
+' [map_path] [<input] [>output]')
|
40
|
commit = env_flag('commit')
|
41
|
|
42
|
csv_config = dict(delimiter=',', quotechar='"')
|
43
|
|
44
|
# Load map
|
45
|
is_xml = True
|
46
|
if uses_map:
|
47
|
import copy
|
48
|
import csv
|
49
|
|
50
|
import xpath
|
51
|
|
52
|
map_ = {}
|
53
|
has_types = False # whether outer elements are type containiners
|
54
|
stream = open(map_path, 'rb')
|
55
|
reader = csv.reader(stream, **csv_config)
|
56
|
src, dest = reader.next()[:2]
|
57
|
src, sep, src_base = src.partition('/')
|
58
|
is_xml = sep != ''
|
59
|
for row in reader:
|
60
|
name, path = row[:2]
|
61
|
if name != '' and path != '':
|
62
|
if path.startswith('/*s/'): has_types = True # *s for type elem
|
63
|
path = path.replace('<name>', name)
|
64
|
map_[name] = xpath.XpathParser(path).parse()
|
65
|
stream.close()
|
66
|
|
67
|
# Input datasource to XML tree
|
68
|
if is_xml: doc = xml.dom.minidom.parse(sys.stdin)
|
69
|
if uses_map:
|
70
|
import xml_xpath
|
71
|
|
72
|
out_doc = xml.dom.minidom.getDOMImplementation().createDocument(None,
|
73
|
dest, None)
|
74
|
if is_xml: raise Exception('XML-XML mapping not supported yet')
|
75
|
else: # input is CSV
|
76
|
reader = csv.reader(sys.stdin, **csv_config)
|
77
|
fieldnames = reader.next()
|
78
|
row_idx = 0
|
79
|
for row in reader:
|
80
|
row_id = str(row_idx)
|
81
|
for idx, name in enumerate(fieldnames):
|
82
|
value = row[idx]
|
83
|
if value != '' and name in map_:
|
84
|
path = copy.deepcopy(map_[name]) # don't modify value!
|
85
|
xpath.set_id(path, row_id, has_types)
|
86
|
xpath.set_value(path, value)
|
87
|
xml_xpath.get(out_doc, path, True)
|
88
|
row_idx += 1
|
89
|
doc = out_doc
|
90
|
|
91
|
# Output XML tree
|
92
|
if to_db_config != None: # output is database
|
93
|
import psycopg2
|
94
|
from psycopg2.extensions import ISOLATION_LEVEL_SERIALIZABLE
|
95
|
|
96
|
import db_xml
|
97
|
|
98
|
db = psycopg2.connect(**to_db_config)
|
99
|
db.set_isolation_level(ISOLATION_LEVEL_SERIALIZABLE)
|
100
|
try:
|
101
|
row_ct_ref = [0]
|
102
|
db_xml.xml2db(db, doc.documentElement, row_ct_ref)
|
103
|
print 'Inserted '+str(row_ct_ref[0])+' rows'
|
104
|
if commit: db.commit()
|
105
|
finally:
|
106
|
db.rollback()
|
107
|
db.close()
|
108
|
else: doc.writexml(sys.stdout, addindent=' ', newl='\n') # output is XML
|
109
|
|
110
|
main()
|