Project

General

Profile

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