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 299 aaronmk
import xml.dom.minidom as minidom
9 53 aaronmk
10 266 aaronmk
sys.path.append(os.path.dirname(__file__)+"/../lib")
11 53 aaronmk
12 344 aaronmk
import exc
13 64 aaronmk
import opts
14 281 aaronmk
import Parser
15 131 aaronmk
import sql
16 310 aaronmk
import util
17 133 aaronmk
import xml_dom
18 86 aaronmk
import xml_func
19 53 aaronmk
20 84 aaronmk
def metadata_value(name):
21 164 aaronmk
    if type(name) == str and name.startswith(':'): return name[1:]
22 84 aaronmk
    else: return None
23
24 53 aaronmk
def main():
25 434 aaronmk
    ex_tracker = exc.ExTracker()
26
27 131 aaronmk
    env_names = []
28
    def usage_err():
29 400 aaronmk
        raise SystemExit('Usage: '+opts.env_usage(env_names, True)+' [commit=1]'
30 510 aaronmk
            ' [test=1] '+sys.argv[0]+' [map_path...] [<input] [>output]')
31 146 aaronmk
    limit = opts.get_env_var('n', None, env_names)
32
    if limit != None: limit = int(limit)
33 400 aaronmk
    test = opts.env_flag('test')
34
    commit = not test and opts.env_flag('commit') # never commit in test mode
35 131 aaronmk
36 53 aaronmk
    # Get db config from env vars
37 131 aaronmk
    db_config_names = ['engine', 'host', 'user', 'password', 'database']
38 53 aaronmk
    def get_db_config(prefix):
39 64 aaronmk
        return opts.get_env_vars(db_config_names, prefix, env_names)
40 67 aaronmk
    in_db_config = get_db_config('in')
41
    out_db_config = get_db_config('out')
42 131 aaronmk
    in_is_db = 'engine' in in_db_config
43
    out_is_db = 'engine' in out_db_config
44 53 aaronmk
45
    # Parse args
46 510 aaronmk
    map_paths = sys.argv[1:]
47 512 aaronmk
    if map_paths == []:
48
        if in_is_db or not out_is_db: usage_err()
49
        else: map_paths = [None]
50 53 aaronmk
51 646 aaronmk
    def connect_db(db_config):
52 647 aaronmk
        sys.stderr.write('Connecting to '+sql.db_config_str(db_config)+'...')
53 646 aaronmk
        db = sql.connect(db_config)
54 647 aaronmk
        sys.stderr.write('Done\n')
55 646 aaronmk
        return db
56
57 512 aaronmk
    def process_input(root, process_row, map_path):
58
        '''Inputs datasource to XML tree, mapping if needed'''
59
        # Load map header
60
        in_is_xpaths = True
61
        out_label = None
62
        if map_path != None:
63
            import copy
64
            import csv
65
66
            import xpath
67
68
            metadata = []
69
            mappings = []
70
            stream = open(map_path, 'rb')
71
            reader = csv.reader(stream)
72
            in_label, out_label = reader.next()[:2]
73
            def split_col_name(name):
74
                name, sep, root = name.partition(':')
75
                return name, sep != '', root
76
            in_label, in_is_xpaths, in_root = split_col_name(in_label)
77
            out_label, out_is_xpaths, out_root = split_col_name(out_label)
78
            assert out_is_xpaths # CSV output not supported yet
79
            has_types = out_root.startswith('/*s/') # outer elements are types
80
            for row in reader:
81
                in_, out = row[:2]
82
                if out != '':
83
                    if out_is_xpaths: out = xpath.parse(out_root+out)
84
                    mappings.append((in_, out))
85
            stream.close()
86
87
            root.ownerDocument.documentElement.tagName = out_label
88
        in_is_xml = in_is_xpaths and not in_is_db
89 56 aaronmk
90 512 aaronmk
        if in_is_xml:
91
            doc0 = minidom.parse(sys.stdin)
92
            if out_label == None: out_label = doc0.documentElement.tagName
93 53 aaronmk
94 309 aaronmk
        def process_rows(get_value, rows):
95 297 aaronmk
            '''Processes input values
96
            @param get_value f(in_, row):str
97
            '''
98 314 aaronmk
            for i, row in enumerate(rows):
99 316 aaronmk
                if not (limit == None or i < limit): break
100
                row_id = str(i)
101
                for in_, out in mappings:
102
                    value = metadata_value(in_)
103
                    if value == None: value = get_value(in_, row)
104
                    if value != None:
105
                        xpath.put_obj(root, out, row_id, has_types, value)
106 452 aaronmk
                process_row(row)
107 460 aaronmk
            sys.stderr.write('Processed '+str(i+1)+' input rows\n')
108 297 aaronmk
109 310 aaronmk
        if map_path == None:
110
            iter_ = xml_dom.NodeElemIter(doc0.documentElement)
111
            util.skip(iter_, xml_dom.is_text) # skip metadata
112 317 aaronmk
            for child in iter_:
113
                root.appendChild(child)
114 452 aaronmk
                process_row(child)
115 309 aaronmk
        elif in_is_db:
116 130 aaronmk
            assert in_is_xpaths
117 126 aaronmk
118 117 aaronmk
            import db_xml
119
120 161 aaronmk
            in_root_xml = xpath.path2xml(in_root)
121 164 aaronmk
            for i, mapping in enumerate(mappings):
122
                in_, out = mapping
123
                if metadata_value(in_) == None:
124 168 aaronmk
                    mappings[i] = (xpath.path2xml(in_root+'/'+in_), out)
125 126 aaronmk
126 646 aaronmk
            in_db = connect_db(in_db_config)
127 133 aaronmk
            in_pkeys = {}
128 297 aaronmk
            def get_value(in_, row):
129 167 aaronmk
                pkey, = row
130 297 aaronmk
                in_ = in_.cloneNode(True) # don't modify orig value!
131
                xml_dom.set_id(xpath.get(in_, in_root), pkey)
132
                value = sql.value_or_none(db_xml.get(in_db, in_, in_pkeys))
133
                if value != None: return str(value)
134
                else: return None
135 309 aaronmk
            process_rows(get_value, sql.rows(db_xml.get(in_db, in_root_xml,
136
                in_pkeys, limit)))
137 117 aaronmk
            in_db.close()
138 161 aaronmk
        elif in_is_xml:
139 297 aaronmk
            def get_value(in_, row):
140
                node = xpath.get(row, in_)
141
                if node != None: return xml_dom.value(node)
142
                else: return None
143
            row0 = xpath.get(doc0.documentElement, in_root)
144 309 aaronmk
            process_rows(get_value, xml_dom.NodeElemIter(row0.parentNode))
145 56 aaronmk
        else: # input is CSV
146 133 aaronmk
            map_ = dict(mappings)
147 59 aaronmk
            reader = csv.reader(sys.stdin)
148 84 aaronmk
            cols = reader.next()
149 162 aaronmk
            col_idxs = dict([(value, idx) for idx, value in enumerate(cols)])
150 164 aaronmk
            for i, mapping in enumerate(mappings):
151
                in_, out = mapping
152
                if metadata_value(in_) == None:
153
                    try: mappings[i] = (col_idxs[in_], out)
154
                    except KeyError: pass
155 162 aaronmk
156 297 aaronmk
            def get_value(in_, row):
157
                value = row[in_]
158
                if value != '': return value
159
                else: return None
160 309 aaronmk
            process_rows(get_value, reader)
161 53 aaronmk
162 512 aaronmk
    def process_inputs(root, process_row):
163
        for map_path in map_paths: process_input(root, process_row, map_path)
164
165 53 aaronmk
    # Output XML tree
166 512 aaronmk
    doc = xml_dom.create_doc()
167 316 aaronmk
    root = doc.documentElement
168 130 aaronmk
    if out_is_db:
169 53 aaronmk
        import db_xml
170
171 646 aaronmk
        out_db = connect_db(out_db_config)
172 310 aaronmk
        out_pkeys = {}
173 53 aaronmk
        try:
174 400 aaronmk
            if test: sql.empty_db(out_db)
175 53 aaronmk
            row_ct_ref = [0]
176 449 aaronmk
177 452 aaronmk
            def process_row(input_row):
178
                def on_error(e):
179
                    exc.add_msg(e, 'output row:\n'+str(root))
180
                    exc.add_msg(e, 'input row:\n'+str(input_row))
181
                    ex_tracker.track(e)
182
183 449 aaronmk
                xml_func.process(root, on_error)
184 442 aaronmk
                if not xml_dom.is_empty(root):
185
                    assert xml_dom.has_one_child(root)
186
                    try:
187
                        sql.with_savepoint(out_db, lambda: db_xml.put(out_db,
188 462 aaronmk
                            root.firstChild, out_pkeys, row_ct_ref, on_error))
189 442 aaronmk
                        if commit: out_db.commit()
190 449 aaronmk
                    except sql.DatabaseErrors, e: on_error(e)
191 316 aaronmk
                root.clear()
192 449 aaronmk
193 512 aaronmk
            process_inputs(root, process_row)
194 460 aaronmk
            sys.stderr.write('Inserted '+str(row_ct_ref[0])+
195
                ' new rows into database\n')
196 53 aaronmk
        finally:
197 133 aaronmk
            out_db.rollback()
198
            out_db.close()
199 299 aaronmk
    else: # output is XML
200 452 aaronmk
        def process_row(input_row): pass
201 512 aaronmk
        process_inputs(root, process_row)
202 316 aaronmk
        xml_func.process(root)
203
        doc.writexml(sys.stdout, **xml_dom.prettyxml_config)
204 53 aaronmk
205 133 aaronmk
try: main()
206 294 aaronmk
except Parser.SyntaxException, e: raise SystemExit(str(e))