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