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