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