Project

General

Profile

1 53 aaronmk
#!/usr/bin/env python
2
# Maps one datasource to another, using a map spreadsheet if needed
3 986 aaronmk
# Exit status is the # of errors in the import, up to the maximum exit status
4 53 aaronmk
# For outputting an XML file to a PostgreSQL database, use the general format of
5
# http://vegbank.org/vegdocs/xml/vegbank_example_ver1.0.2.xml
6
7 1014 aaronmk
import csv
8 53 aaronmk
import os.path
9
import sys
10 299 aaronmk
import xml.dom.minidom as minidom
11 53 aaronmk
12 266 aaronmk
sys.path.append(os.path.dirname(__file__)+"/../lib")
13 53 aaronmk
14 344 aaronmk
import exc
15 64 aaronmk
import opts
16 281 aaronmk
import Parser
17 982 aaronmk
import profiling
18 131 aaronmk
import sql
19 715 aaronmk
import strings
20 828 aaronmk
import term
21 310 aaronmk
import util
22 1014 aaronmk
import xpath
23 133 aaronmk
import xml_dom
24 86 aaronmk
import xml_func
25 53 aaronmk
26 1018 aaronmk
def metadata_value(name): return None # this feature has been removed
27 84 aaronmk
28 1360 aaronmk
def cleanup(val):
29
    if val == None: return val
30 1374 aaronmk
    return util.none_if(strings.cleanup(strings.ustr(val)), u'', u'\\N')
31 1360 aaronmk
32 847 aaronmk
def main_():
33 131 aaronmk
    env_names = []
34
    def usage_err():
35 944 aaronmk
        raise SystemExit('Usage: '+opts.env_usage(env_names, True)+' '
36 847 aaronmk
            +sys.argv[0]+' [map_path...] [<input] [>output]')
37 838 aaronmk
38
    # Get db config from env vars
39
    db_config_names = ['engine', 'host', 'user', 'password', 'database']
40
    def get_db_config(prefix):
41
        return opts.get_env_vars(db_config_names, prefix, env_names)
42
    in_db_config = get_db_config('in')
43
    out_db_config = get_db_config('out')
44
    in_is_db = 'engine' in in_db_config
45
    out_is_db = 'engine' in out_db_config
46
47
    # Get other config from env vars
48
    end = util.cast(int, opts.get_env_var('n', None, env_names))
49
    start = util.cast(int, opts.get_env_var('start', '0', env_names))
50
    if end != None: end += start
51 946 aaronmk
    test = opts.env_flag('test', False, env_names)
52 947 aaronmk
    commit = opts.env_flag('commit', False, env_names) and not test
53 944 aaronmk
        # never commit in test mode
54 947 aaronmk
    redo = opts.env_flag('redo', test, env_names) and not commit
55
        # never redo in commit mode (manually run `make empty_db` instead)
56 946 aaronmk
    debug = opts.env_flag('debug', False, env_names)
57 859 aaronmk
    sql.run_raw_query.debug = debug
58 946 aaronmk
    verbose = debug or opts.env_flag('verbose', False, env_names)
59 944 aaronmk
    opts.get_env_var('profile_to', None, env_names) # add to env_names
60 131 aaronmk
61 838 aaronmk
    # Logging
62 662 aaronmk
    def log(msg, on=verbose):
63
        if on: sys.stderr.write(msg)
64 859 aaronmk
    def log_start(action, on=verbose): log(action+'...\n', on)
65 662 aaronmk
66 53 aaronmk
    # Parse args
67 510 aaronmk
    map_paths = sys.argv[1:]
68 512 aaronmk
    if map_paths == []:
69
        if in_is_db or not out_is_db: usage_err()
70
        else: map_paths = [None]
71 53 aaronmk
72 646 aaronmk
    def connect_db(db_config):
73 662 aaronmk
        log_start('Connecting to '+sql.db_config_str(db_config))
74 1014 aaronmk
        return sql.connect(db_config)
75 646 aaronmk
76 1014 aaronmk
    ex_tracker = exc.ExPercentTracker(iter_text='row')
77
    profiler = profiling.ItersProfiler(start_now=True, iter_text='row')
78
79
    doc = xml_dom.create_doc()
80
    root = doc.documentElement
81 751 aaronmk
    out_is_xml_ref = [False]
82 1014 aaronmk
    in_label_ref = [None]
83
    def update_in_label():
84
        if in_label_ref[0] != None:
85
            xpath.get(root, '/_ignore/inLabel="'+in_label_ref[0]+'"', True)
86
    def prep_root():
87
        root.clear()
88
        update_in_label()
89
    prep_root()
90 751 aaronmk
91 838 aaronmk
    def process_input(root, row_ready, map_path):
92 512 aaronmk
        '''Inputs datasource to XML tree, mapping if needed'''
93
        # Load map header
94
        in_is_xpaths = True
95 751 aaronmk
        out_is_xpaths = True
96 512 aaronmk
        out_label = None
97
        if map_path != None:
98
            metadata = []
99
            mappings = []
100
            stream = open(map_path, 'rb')
101
            reader = csv.reader(stream)
102
            in_label, out_label = reader.next()[:2]
103
            def split_col_name(name):
104
                name, sep, root = name.partition(':')
105 1198 aaronmk
                return name.partition('[')[0], sep != '', root
106
                    # extract datasrc from "datasrc[data_format]"
107 512 aaronmk
            in_label, in_is_xpaths, in_root = split_col_name(in_label)
108 1014 aaronmk
            in_label_ref[0] = in_label
109
            update_in_label()
110 512 aaronmk
            out_label, out_is_xpaths, out_root = split_col_name(out_label)
111
            has_types = out_root.startswith('/*s/') # outer elements are types
112
            for row in reader:
113
                in_, out = row[:2]
114
                if out != '':
115
                    if out_is_xpaths: out = xpath.parse(out_root+out)
116
                    mappings.append((in_, out))
117
            stream.close()
118
119
            root.ownerDocument.documentElement.tagName = out_label
120
        in_is_xml = in_is_xpaths and not in_is_db
121 751 aaronmk
        out_is_xml_ref[0] = out_is_xpaths and not out_is_db
122 56 aaronmk
123 512 aaronmk
        if in_is_xml:
124
            doc0 = minidom.parse(sys.stdin)
125 1006 aaronmk
            doc0_root = doc0.documentElement
126
            if out_label == None: out_label = doc0_root.tagName
127 53 aaronmk
128 1148 aaronmk
        def process_rows(process_row, rows):
129 838 aaronmk
            '''Processes input rows
130
            @param process_row(in_row, i)
131 297 aaronmk
            '''
132 838 aaronmk
            i = -1 # in case for loop does not execute
133 314 aaronmk
            for i, row in enumerate(rows):
134 838 aaronmk
                if i < start: continue
135
                if end != None and i >= end: break
136
                process_row(row, i)
137
                row_ready(i, row)
138 978 aaronmk
            row_ct = i-start+1
139 982 aaronmk
            return row_ct
140 838 aaronmk
141
        def map_rows(get_value, rows):
142
            '''Maps input rows
143
            @param get_value(in_, row):str
144
            '''
145
            def process_row(row, i):
146 316 aaronmk
                row_id = str(i)
147
                for in_, out in mappings:
148
                    value = metadata_value(in_)
149 662 aaronmk
                    if value == None:
150 857 aaronmk
                        log_start('Getting '+str(in_), debug)
151 1360 aaronmk
                        value = cleanup(get_value(in_, row))
152 1348 aaronmk
                    if value != None:
153
                        log_start('Putting '+str(out), debug)
154 1360 aaronmk
                        xpath.put_obj(root, out, row_id, has_types, value)
155 982 aaronmk
            return process_rows(process_row, rows)
156 297 aaronmk
157 310 aaronmk
        if map_path == None:
158 1006 aaronmk
            iter_ = xml_dom.NodeElemIter(doc0_root)
159 310 aaronmk
            util.skip(iter_, xml_dom.is_text) # skip metadata
160 982 aaronmk
            row_ct = process_rows(lambda row, i: root.appendChild(row), iter_)
161 309 aaronmk
        elif in_is_db:
162 130 aaronmk
            assert in_is_xpaths
163 126 aaronmk
164 1136 aaronmk
            in_db = connect_db(in_db_config)
165
            in_pkeys = {}
166
            cur = sql.select(in_db, table=in_root, fields=None, conds=None,
167
                limit=end, start=0)
168 1179 aaronmk
            col_names = list(sql.col_names(cur))
169
            col_idxs = util.list_flip(col_names)
170 1136 aaronmk
171 1179 aaronmk
            mappings_new = []
172
            for i, mapping in enumerate(mappings):
173
                in_, out = mapping
174
                if metadata_value(in_) == None:
175
                    try: mapping = (col_idxs[in_], out)
176
                    except KeyError: continue
177
                mappings_new.append(mapping)
178
            mappings = mappings_new
179
180 1148 aaronmk
            def get_value(in_, row):
181 1360 aaronmk
                try: return row.list[in_]
182 1179 aaronmk
                except IndexError: return None
183 1148 aaronmk
            def wrap_row(row): return util.ListDict(row, col_names, col_idxs)
184
            row_ct = map_rows(get_value, util.WrapIter(wrap_row, sql.rows(cur)))
185 1136 aaronmk
186 117 aaronmk
            in_db.close()
187 161 aaronmk
        elif in_is_xml:
188 297 aaronmk
            def get_value(in_, row):
189 1005 aaronmk
                nodes = xpath.get(row, in_, allow_rooted=False)
190 886 aaronmk
                if nodes != []: return xml_dom.value(nodes[0])
191 297 aaronmk
                else: return None
192 1006 aaronmk
            rows = xpath.get(doc0_root, in_root, limit=end)
193 886 aaronmk
            if rows == []: raise SystemExit('Map error: Root "'+in_root
194 883 aaronmk
                +'" not found in input')
195 982 aaronmk
            row_ct = map_rows(get_value, rows)
196 56 aaronmk
        else: # input is CSV
197 133 aaronmk
            map_ = dict(mappings)
198 59 aaronmk
            reader = csv.reader(sys.stdin)
199 1179 aaronmk
            col_names = reader.next()
200
            col_idxs = util.list_flip(col_names)
201 1134 aaronmk
202 1179 aaronmk
            mappings_new = []
203
            for i, mapping in enumerate(mappings):
204
                in_, out = mapping
205
                if metadata_value(in_) == None:
206
                    try: mapping = (col_idxs[in_], out)
207
                    except KeyError: continue
208
                mappings_new.append(mapping)
209
            mappings = mappings_new
210
211 1148 aaronmk
            def get_value(in_, row):
212 1360 aaronmk
                try: return row.list[in_]
213 1179 aaronmk
                except IndexError: return None
214 1148 aaronmk
            def wrap_row(row): return util.ListDict(row, col_names, col_idxs)
215
            row_ct = map_rows(get_value, util.WrapIter(wrap_row, reader))
216 982 aaronmk
217
        return row_ct
218 53 aaronmk
219 838 aaronmk
    def process_inputs(root, row_ready):
220 982 aaronmk
        row_ct = 0
221
        for map_path in map_paths:
222
            row_ct += process_input(root, row_ready, map_path)
223
        return row_ct
224 512 aaronmk
225 130 aaronmk
    if out_is_db:
226 53 aaronmk
        import db_xml
227
228 646 aaronmk
        out_db = connect_db(out_db_config)
229 310 aaronmk
        out_pkeys = {}
230 53 aaronmk
        try:
231 947 aaronmk
            if redo: sql.empty_db(out_db)
232 982 aaronmk
            row_ins_ct_ref = [0]
233 449 aaronmk
234 838 aaronmk
            def row_ready(row_num, input_row):
235 452 aaronmk
                def on_error(e):
236 835 aaronmk
                    exc.add_msg(e, term.emph('row #:')+' '+str(row_num))
237 828 aaronmk
                    exc.add_msg(e, term.emph('input row:')+'\n'+str(input_row))
238
                    exc.add_msg(e, term.emph('output row:')+'\n'+str(root))
239 452 aaronmk
                    ex_tracker.track(e)
240
241 449 aaronmk
                xml_func.process(root, on_error)
242 442 aaronmk
                if not xml_dom.is_empty(root):
243
                    assert xml_dom.has_one_child(root)
244
                    try:
245 982 aaronmk
                        sql.with_savepoint(out_db,
246
                            lambda: db_xml.put(out_db, root.firstChild,
247
                                out_pkeys, row_ins_ct_ref, on_error))
248 442 aaronmk
                        if commit: out_db.commit()
249 449 aaronmk
                    except sql.DatabaseErrors, e: on_error(e)
250 1010 aaronmk
                prep_root()
251 449 aaronmk
252 982 aaronmk
            row_ct = process_inputs(root, row_ready)
253
            sys.stdout.write('Inserted '+str(row_ins_ct_ref[0])+
254 460 aaronmk
                ' new rows into database\n')
255 53 aaronmk
        finally:
256 133 aaronmk
            out_db.rollback()
257
            out_db.close()
258 751 aaronmk
    else:
259 759 aaronmk
        def on_error(e): ex_tracker.track(e)
260 838 aaronmk
        def row_ready(row_num, input_row): pass
261 982 aaronmk
        row_ct = process_inputs(root, row_ready)
262 759 aaronmk
        xml_func.process(root, on_error)
263 751 aaronmk
        if out_is_xml_ref[0]:
264
            doc.writexml(sys.stdout, **xml_dom.prettyxml_config)
265
        else: # output is CSV
266
            raise NotImplementedError('CSV output not supported yet')
267 985 aaronmk
268 982 aaronmk
    profiler.stop(row_ct)
269
    ex_tracker.add_iters(row_ct)
270 990 aaronmk
    if verbose:
271
        sys.stderr.write('Processed '+str(row_ct)+' input rows\n')
272
        sys.stderr.write(profiler.msg()+'\n')
273
        sys.stderr.write(ex_tracker.msg()+'\n')
274 985 aaronmk
    ex_tracker.exit()
275 53 aaronmk
276 847 aaronmk
def main():
277
    try: main_()
278
    except Parser.SyntaxException, e: raise SystemExit(str(e))
279
280 846 aaronmk
if __name__ == '__main__':
281 847 aaronmk
    profile_to = opts.get_env_var('profile_to', None)
282
    if profile_to != None:
283
        import cProfile
284
        cProfile.run(main.func_code, profile_to)
285
    else: main()