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.path
7
import sys
8
import xml.dom.minidom
9
10
sys.path.append(os.path.dirname(__file__)+"/lib")
11
12 64 aaronmk
import opts
13 133 aaronmk
from Parser import SyntaxException
14 131 aaronmk
import sql
15 133 aaronmk
import xml_dom
16 86 aaronmk
import xml_func
17 53 aaronmk
18 84 aaronmk
def metadata_value(name):
19
    if name.startswith(':'): return name[1:]
20
    else: return None
21
22 53 aaronmk
def main():
23 131 aaronmk
    env_names = []
24
    def usage_err():
25
        raise SystemExit('Usage: '+opts.env_usage(env_names, True)
26
            +' [commit=1] '+sys.argv[0]+' [map_path] [<input] [>output]')
27 146 aaronmk
    limit = opts.get_env_var('n', None, env_names)
28
    if limit != None: limit = int(limit)
29 135 aaronmk
    commit = opts.env_flag('commit')
30 131 aaronmk
31 53 aaronmk
    # Get db config from env vars
32 131 aaronmk
    db_config_names = ['engine', 'host', 'user', 'password', 'database']
33 53 aaronmk
    def get_db_config(prefix):
34 64 aaronmk
        return opts.get_env_vars(db_config_names, prefix, env_names)
35 67 aaronmk
    in_db_config = get_db_config('in')
36
    out_db_config = get_db_config('out')
37 131 aaronmk
    in_is_db = 'engine' in in_db_config
38
    out_is_db = 'engine' in out_db_config
39 53 aaronmk
40
    # Parse args
41 73 aaronmk
    map_path = None
42 67 aaronmk
    try: _prog_name, map_path = sys.argv
43 53 aaronmk
    except ValueError:
44 135 aaronmk
        if in_is_db: usage_err()
45 53 aaronmk
46 57 aaronmk
    # Load map header
47 130 aaronmk
    in_is_xpaths = True
48 73 aaronmk
    if map_path != None:
49 56 aaronmk
        import copy
50
        import csv
51
52 53 aaronmk
        import xpath
53
54 133 aaronmk
        metadata = []
55 73 aaronmk
        mappings = []
56
        stream = open(map_path, 'rb')
57
        reader = csv.reader(stream)
58 161 aaronmk
        in_label, out_label = reader.next()[:2]
59 61 aaronmk
        def split_col_name(name):
60 72 aaronmk
            name, sep, root = name.partition(':')
61
            return name, sep != '', root
62 161 aaronmk
        in_label, in_is_xpaths, in_root = split_col_name(in_label)
63
        out_label, out_is_xpaths, out_root = split_col_name(out_label)
64 133 aaronmk
        assert out_is_xpaths # CSV output not supported yet
65 161 aaronmk
        has_types = out_root.startswith('/*s/') # outer elements are types
66 73 aaronmk
        for row in reader:
67
            in_, out = row[:2]
68
            if out != '':
69 133 aaronmk
                value = metadata_value(in_)
70 161 aaronmk
                if out_is_xpaths: out = xpath.parse(out_root+out)
71
                if value != None: metadata.append((value, out))
72 133 aaronmk
                else: mappings.append((in_, out))
73 73 aaronmk
        stream.close()
74 130 aaronmk
    in_is_xml = in_is_xpaths and not in_is_db
75 56 aaronmk
76 57 aaronmk
    # Input datasource to XML tree, mapping if needed
77 161 aaronmk
    if in_is_xml:
78
        doc0 = xml.dom.minidom.parse(sys.stdin)
79 73 aaronmk
    if map_path != None:
80 161 aaronmk
        doc1 = xml_dom.create_doc(out_label)
81 141 aaronmk
        root = doc1.documentElement
82 126 aaronmk
        if in_is_db:
83 130 aaronmk
            assert in_is_xpaths
84 126 aaronmk
85 117 aaronmk
            import db_xml
86
87 161 aaronmk
            in_root_xml = xpath.path2xml(in_root)
88
            mappings = [(xpath.path2xml(in_root+in_), out) for in_, out in mappings]
89 126 aaronmk
90 131 aaronmk
            in_db = sql.connect(in_db_config)
91 133 aaronmk
            in_pkeys = {}
92 162 aaronmk
            for row in sql.rows(db_xml.get(in_db, in_root_xml, in_pkeys,
93
                limit)):
94 135 aaronmk
                row_id, = row
95
                row_id = str(row_id)
96
97 133 aaronmk
                def put_col(path, value):
98 141 aaronmk
                    xpath.put_obj(root, path, row_id, has_types, value)
99 133 aaronmk
                for value, out in metadata: put_col(out, value)
100
                for in_, out in mappings:
101 141 aaronmk
                    in_ = in_.cloneNode(True) # don't modify orig value!
102 161 aaronmk
                    xml_dom.set_id(xpath.get(in_, in_root), row_id)
103 140 aaronmk
                    value = sql.value_or_none(db_xml.get(in_db, in_, in_pkeys))
104
                    if value != None: put_col(out, str(value))
105 117 aaronmk
            in_db.close()
106 161 aaronmk
        elif in_is_xml:
107
            row = xpath.get(doc0.documentElement, in_root)
108
            for row_idx, row in enumerate(xml_dom.NodeElemIter(row.parentNode)):
109
                if not (limit == None or row_idx < limit): break
110
                row_id = str(row_idx)
111
112
                def put_col(path, value):
113
                    xpath.put_obj(root, path, row_id, has_types, value)
114
                for value, out in metadata: put_col(out, value)
115
                for in_, out in mappings:
116
                    node = xpath.get(row, in_)
117
                    if node != None: put_col(out, xml_dom.value(node))
118 56 aaronmk
        else: # input is CSV
119 133 aaronmk
            map_ = dict(mappings)
120 59 aaronmk
            reader = csv.reader(sys.stdin)
121 84 aaronmk
            cols = reader.next()
122 162 aaronmk
            col_idxs = dict([(value, idx) for idx, value in enumerate(cols)])
123
            mappings = [(col_idxs.get(in_, None), out) for in_, out in mappings]
124
            mappings = filter(lambda item: item[0] != None, mappings)
125
126 83 aaronmk
            for row_idx, row in enumerate(reader):
127 146 aaronmk
                if not (limit == None or row_idx < limit): break
128 56 aaronmk
                row_id = str(row_idx)
129 135 aaronmk
130 84 aaronmk
                def put_col(path, value):
131 141 aaronmk
                    xpath.put_obj(root, path, row_id, has_types, value)
132 84 aaronmk
                for value, out in metadata: put_col(out, value)
133 162 aaronmk
                for in_, out in mappings:
134
                    if row[in_] != '': put_col(out, row[in_])
135 142 aaronmk
        xml_func.process(root)
136 116 aaronmk
    else: doc1 = doc0
137 53 aaronmk
138
    # Output XML tree
139 130 aaronmk
    if out_is_db:
140 53 aaronmk
        from psycopg2.extensions import ISOLATION_LEVEL_SERIALIZABLE
141
        import db_xml
142
143 133 aaronmk
        out_db = sql.connect(out_db_config)
144
        out_db.set_isolation_level(ISOLATION_LEVEL_SERIALIZABLE)
145 53 aaronmk
        try:
146
            row_ct_ref = [0]
147 133 aaronmk
            db_xml.xml2db(out_db, doc1.documentElement, row_ct_ref)
148 53 aaronmk
            print 'Inserted '+str(row_ct_ref[0])+' rows'
149 133 aaronmk
            if commit: out_db.commit()
150 53 aaronmk
        finally:
151 133 aaronmk
            out_db.rollback()
152
            out_db.close()
153 135 aaronmk
    else: xml_dom.writexml(sys.stdout, doc1) # output is XML
154 53 aaronmk
155 133 aaronmk
try: main()
156
except SyntaxException, ex: raise SystemExit(str(ex))