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 1714 aaronmk
import itertools
9 53 aaronmk
import os.path
10
import sys
11 299 aaronmk
import xml.dom.minidom as minidom
12 53 aaronmk
13 266 aaronmk
sys.path.append(os.path.dirname(__file__)+"/../lib")
14 53 aaronmk
15 1389 aaronmk
import csvs
16 344 aaronmk
import exc
17 1714 aaronmk
import iters
18 1705 aaronmk
import maps
19 64 aaronmk
import opts
20 1859 aaronmk
import parallel
21 281 aaronmk
import Parser
22 982 aaronmk
import profiling
23 131 aaronmk
import sql
24 1758 aaronmk
import streams
25 715 aaronmk
import strings
26 828 aaronmk
import term
27 310 aaronmk
import util
28 1014 aaronmk
import xpath
29 133 aaronmk
import xml_dom
30 86 aaronmk
import xml_func
31 1713 aaronmk
import xml_parse
32 53 aaronmk
33 1404 aaronmk
def get_with_prefix(map_, prefixes, key):
34 1484 aaronmk
    '''Gets all entries for the given key with any of the given prefixes'''
35
    values = []
36 1681 aaronmk
    for key_ in strings.with_prefixes(['']+prefixes, key): # also with no prefix
37
        try: value = map_[key_]
38 1484 aaronmk
        except KeyError, e: continue # keep going
39
        values.append(value)
40
41
    if values != []: return values
42
    else: raise e # re-raise last KeyError
43 1404 aaronmk
44 1018 aaronmk
def metadata_value(name): return None # this feature has been removed
45 84 aaronmk
46 1360 aaronmk
def cleanup(val):
47
    if val == None: return val
48 1374 aaronmk
    return util.none_if(strings.cleanup(strings.ustr(val)), u'', u'\\N')
49 1360 aaronmk
50 847 aaronmk
def main_():
51 131 aaronmk
    env_names = []
52
    def usage_err():
53 944 aaronmk
        raise SystemExit('Usage: '+opts.env_usage(env_names, True)+' '
54 1945 aaronmk
            +sys.argv[0]+' [map_path...] [<input] [>output]\n'
55 1946 aaronmk
            'Note: Row #s start with 1')
56 838 aaronmk
57 1570 aaronmk
    ## Get config from env vars
58 838 aaronmk
59 1570 aaronmk
    # Modes
60 946 aaronmk
    test = opts.env_flag('test', False, env_names)
61 947 aaronmk
    commit = opts.env_flag('commit', False, env_names) and not test
62 944 aaronmk
        # never commit in test mode
63 947 aaronmk
    redo = opts.env_flag('redo', test, env_names) and not commit
64
        # never redo in commit mode (manually run `make empty_db` instead)
65 1570 aaronmk
66
    # Ranges
67 1946 aaronmk
    start = util.cast(int, opts.get_env_var('start', 1, env_names)) # 1-based
68
    # Make start interally 0-based.
69
    # It's 1-based to the user to match up with the staging table row #s.
70
    start -= 1
71 1945 aaronmk
    if test: n_default = 1
72
    else: n_default = None
73
    n = util.cast(int, util.none_if(opts.get_env_var('n', n_default, env_names),
74
        u''))
75
    end = n
76 1570 aaronmk
    if end != None: end += start
77
78
    # Debugging
79 946 aaronmk
    debug = opts.env_flag('debug', False, env_names)
80 859 aaronmk
    sql.run_raw_query.debug = debug
81 1574 aaronmk
    verbose = debug or opts.env_flag('verbose', not test, env_names)
82 944 aaronmk
    opts.get_env_var('profile_to', None, env_names) # add to env_names
83 131 aaronmk
84 1570 aaronmk
    # DB
85
    def get_db_config(prefix):
86 1926 aaronmk
        return opts.get_env_vars(sql.db_config_names, prefix, env_names)
87 1570 aaronmk
    in_db_config = get_db_config('in')
88
    out_db_config = get_db_config('out')
89
    in_is_db = 'engine' in in_db_config
90
    out_is_db = 'engine' in out_db_config
91 1982 aaronmk
    in_schema = opts.get_env_var('in_schema', None, env_names)
92
    in_table = opts.get_env_var('in_table', None, env_names)
93 1570 aaronmk
94 1989 aaronmk
    # Optimization
95
    by_col = in_db_config == out_db_config and opts.env_flag('by_col', False,
96
        env_names) # by-column optimization only applies if mapping to same DB
97
    if test: cpus_default = 0
98
    else: cpus_default = None
99
    cpus = util.cast(int, util.none_if(opts.get_env_var('cpus', cpus_default,
100
        env_names), u''))
101
102 1570 aaronmk
    ##
103
104 838 aaronmk
    # Logging
105 662 aaronmk
    def log(msg, on=verbose):
106 1901 aaronmk
        if on: sys.stderr.write(msg+'\n')
107
    if debug: log_debug = lambda msg: log(msg, debug)
108
    else: log_debug = sql.log_debug_none
109 662 aaronmk
110 53 aaronmk
    # Parse args
111 510 aaronmk
    map_paths = sys.argv[1:]
112 512 aaronmk
    if map_paths == []:
113
        if in_is_db or not out_is_db: usage_err()
114
        else: map_paths = [None]
115 53 aaronmk
116 646 aaronmk
    def connect_db(db_config):
117 1901 aaronmk
        log('Connecting to '+sql.db_config_str(db_config))
118
        return sql.connect(db_config, log_debug=log_debug)
119 646 aaronmk
120 1945 aaronmk
    if end != None: end_str = str(end-1) # end is one past the last #
121 1573 aaronmk
    else: end_str = 'end'
122 1901 aaronmk
    log('Processing input rows '+str(start)+'-'+end_str)
123 1573 aaronmk
124 1014 aaronmk
    ex_tracker = exc.ExPercentTracker(iter_text='row')
125
    profiler = profiling.ItersProfiler(start_now=True, iter_text='row')
126
127 1856 aaronmk
    # Parallel processing
128 1862 aaronmk
    pool = parallel.MultiProducerPool(cpus)
129 1901 aaronmk
    log('Using '+str(pool.process_ct)+' parallel CPUs')
130 1846 aaronmk
131 1014 aaronmk
    doc = xml_dom.create_doc()
132
    root = doc.documentElement
133 751 aaronmk
    out_is_xml_ref = [False]
134 1014 aaronmk
    in_label_ref = [None]
135
    def update_in_label():
136
        if in_label_ref[0] != None:
137
            xpath.get(root, '/_ignore/inLabel="'+in_label_ref[0]+'"', True)
138
    def prep_root():
139
        root.clear()
140
        update_in_label()
141
    prep_root()
142 751 aaronmk
143 1991 aaronmk
    # Define before the out_is_db section because it's used by by_col
144
    row_ins_ct_ref = [0]
145
146 838 aaronmk
    def process_input(root, row_ready, map_path):
147 512 aaronmk
        '''Inputs datasource to XML tree, mapping if needed'''
148
        # Load map header
149
        in_is_xpaths = True
150 751 aaronmk
        out_is_xpaths = True
151 512 aaronmk
        out_label = None
152
        if map_path != None:
153
            metadata = []
154
            mappings = []
155
            stream = open(map_path, 'rb')
156
            reader = csv.reader(stream)
157
            in_label, out_label = reader.next()[:2]
158 1402 aaronmk
159 512 aaronmk
            def split_col_name(name):
160 1402 aaronmk
                label, sep, root = name.partition(':')
161
                label, sep2, prefixes_str = label.partition('[')
162
                prefixes_str = strings.remove_suffix(']', prefixes_str)
163
                prefixes = strings.split(',', prefixes_str)
164
                return label, sep != '', root, prefixes
165 1198 aaronmk
                    # extract datasrc from "datasrc[data_format]"
166 1402 aaronmk
167 1705 aaronmk
            in_label, in_root, prefixes = maps.col_info(in_label)
168
            in_is_xpaths = in_root != None
169 1014 aaronmk
            in_label_ref[0] = in_label
170
            update_in_label()
171 1705 aaronmk
            out_label, out_root = maps.col_info(out_label)[:2]
172
            out_is_xpaths = out_root != None
173 1841 aaronmk
            if out_is_xpaths: has_types = out_root.find('/*s/') >= 0
174 1705 aaronmk
                # outer elements are types
175 1402 aaronmk
176 512 aaronmk
            for row in reader:
177
                in_, out = row[:2]
178 2029 aaronmk
                if out != '': mappings.append([in_, out_root+out])
179 1402 aaronmk
180 512 aaronmk
            stream.close()
181
182
            root.ownerDocument.documentElement.tagName = out_label
183
        in_is_xml = in_is_xpaths and not in_is_db
184 751 aaronmk
        out_is_xml_ref[0] = out_is_xpaths and not out_is_db
185 56 aaronmk
186 1897 aaronmk
        def process_rows(process_row, rows, rows_start=0):
187
            '''Processes input rows
188 838 aaronmk
            @param process_row(in_row, i)
189 1945 aaronmk
            @rows_start The (0-based) row # of the first row in rows. Set this
190
                only if the pre-start rows have already been skipped.
191 297 aaronmk
            '''
192 1897 aaronmk
            rows = iter(rows)
193
194
            if end != None: row_nums = xrange(rows_start, end)
195
            else: row_nums = itertools.count(rows_start)
196 2033 aaronmk
            i = 0
197 1897 aaronmk
            for i in row_nums:
198 1718 aaronmk
                try: row = rows.next()
199
                except StopIteration: break # no more rows
200
                if i < start: continue # not at start row yet
201
202 838 aaronmk
                process_row(row, i)
203
                row_ready(i, row)
204 2033 aaronmk
            row_ct = i-start+1
205 982 aaronmk
            return row_ct
206 838 aaronmk
207 1898 aaronmk
        def map_rows(get_value, rows, **kw_args):
208 838 aaronmk
            '''Maps input rows
209
            @param get_value(in_, row):str
210
            '''
211 2030 aaronmk
            # Prevent collisions if multiple inputs mapping to same output
212
            outputs_idxs = dict()
213
            for i, mapping in enumerate(mappings):
214
                in_, out = mapping
215
                default = util.NamedTuple(count=1, first=i)
216
                idxs = outputs_idxs.setdefault(out, default)
217
                if idxs is not default: # key existed, so there was a collision
218
                    if idxs.count == 1: # first key does not yet have /_alt/#
219
                        mappings[idxs.first][1] += '/_alt/0'
220
                    mappings[i][1] += '/_alt/'+str(idxs.count)
221
                    idxs.count += 1
222
223 2026 aaronmk
            id_node = None
224
            if out_is_db:
225
                for i, mapping in enumerate(mappings):
226
                    in_, out = mapping
227
                    # All put_obj()s should return the same id_node
228
                    nodes, id_node = xpath.put_obj(root, out, '-1', has_types,
229
                        '$'+str(in_)) # value is placeholder that documents name
230 2032 aaronmk
                    mappings[i] = [in_, nodes]
231
                assert id_node != None
232 2026 aaronmk
233
                if debug: # only str() if debug
234
                    log_debug('Put template:\n'+str(root))
235
236 838 aaronmk
            def process_row(row, i):
237 316 aaronmk
                row_id = str(i)
238 2032 aaronmk
                if id_node != None: xml_dom.set_value(id_node, row_id)
239 316 aaronmk
                for in_, out in mappings:
240 2027 aaronmk
                    log_debug('Getting '+str(in_))
241 316 aaronmk
                    value = metadata_value(in_)
242 2027 aaronmk
                    if value == None: value = cleanup(get_value(in_, row))
243
                    log_debug('Putting '+repr(value)+' to '+str(out))
244 2032 aaronmk
                    if out_is_db: # out is list of XML nodes
245
                        for node in out: xml_dom.set_value(node, value)
246
                    elif value != None: # out is XPath
247 1360 aaronmk
                        xpath.put_obj(root, out, row_id, has_types, value)
248 2027 aaronmk
                if debug: log_debug('Putting:\n'+str(root))# only str() if debug
249 1898 aaronmk
            return process_rows(process_row, rows, **kw_args)
250 297 aaronmk
251 1898 aaronmk
        def map_table(col_names, rows, **kw_args):
252 1416 aaronmk
            col_names_ct = len(col_names)
253 1403 aaronmk
            col_idxs = util.list_flip(col_names)
254
255 2029 aaronmk
            # Resolve prefixes
256 2025 aaronmk
            mappings_orig = mappings[:] # save a copy
257
            mappings[:] = [] # empty existing elements
258
            for in_, out in mappings_orig:
259 1403 aaronmk
                if metadata_value(in_) == None:
260 2025 aaronmk
                    try: names = get_with_prefix(col_idxs, prefixes, in_)
261
                    except KeyError: pass
262 2031 aaronmk
                    else: mappings[len(mappings):] = [[v, out] for v in names]
263
                        # can't use += because that uses assignment
264 1403 aaronmk
265 2031 aaronmk
            def get_value(in_, row): return row.list[in_]
266 1416 aaronmk
            def wrap_row(row):
267
                return util.ListDict(util.list_as_length(row, col_names_ct),
268
                    col_names, col_idxs) # handle CSV rows of different lengths
269 1403 aaronmk
270 1898 aaronmk
            return map_rows(get_value, util.WrapIter(wrap_row, rows), **kw_args)
271 1403 aaronmk
272 1758 aaronmk
        stdin = streams.LineCountStream(sys.stdin)
273
        def on_error(e):
274
            exc.add_msg(e, term.emph('input line #:')+' '+str(stdin.line_num))
275
            ex_tracker.track(e)
276
277 1700 aaronmk
        if in_is_db:
278 1982 aaronmk
            in_db = connect_db(in_db_config)
279 126 aaronmk
280 1982 aaronmk
            # Get table and schema name
281
            schema = in_schema # modified, so can't have same name as outer var
282
            table = in_table # modified, so can't have same name as outer var
283
            if table == None:
284
                assert in_is_xpaths
285
                schema, sep, table = in_root.partition('.')
286
                if sep == '': # only the table name was specified
287
                    table = schema
288
                    schema = None
289
            table_is_esc = False
290
            if schema != None:
291
                table = sql.qual_name(in_db, schema, table)
292
                table_is_esc = True
293
294 1991 aaronmk
            # Fetch rows
295
            if by_col: limit = 0 # only fetch column names
296
            else: limit = n
297
            cur = sql.select(in_db, table, limit=limit, start=start,
298
                table_is_esc=table_is_esc)
299
            col_names = list(sql.col_names(cur))
300
301 1989 aaronmk
            if by_col:
302 1991 aaronmk
                row_ready = lambda row_num, input_row: None# disable row_ready()
303 1994 aaronmk
                row = ['$'+v for v in col_names] # values are the column names
304
                map_table(col_names, [row]) # map just the sample row
305 1993 aaronmk
                xml_func.strip(root)
306 1998 aaronmk
                db_xml.put_table(in_db, root.firstChild, table, commit,
307
                    row_ins_ct_ref, table_is_esc)
308 1984 aaronmk
            else:
309
                # Use normal by-row method
310 1991 aaronmk
                row_ct = map_table(col_names, sql.rows(cur), rows_start=start)
311
                    # rows_start: pre-start rows have been skipped
312 1136 aaronmk
313 1849 aaronmk
            in_db.db.close()
314 161 aaronmk
        elif in_is_xml:
315 1715 aaronmk
            def get_rows(doc2rows):
316 1758 aaronmk
                return iters.flatten(itertools.imap(doc2rows,
317
                    xml_parse.docs_iter(stdin, on_error)))
318 1715 aaronmk
319 1714 aaronmk
            if map_path == None:
320 1715 aaronmk
                def doc2rows(in_xml_root):
321 1701 aaronmk
                    iter_ = xml_dom.NodeElemIter(in_xml_root)
322
                    util.skip(iter_, xml_dom.is_text) # skip metadata
323 1715 aaronmk
                    return iter_
324
325
                row_ct = process_rows(lambda row, i: root.appendChild(row),
326
                    get_rows(doc2rows))
327 1714 aaronmk
            else:
328 1715 aaronmk
                def doc2rows(in_xml_root):
329 1701 aaronmk
                    rows = xpath.get(in_xml_root, in_root, limit=end)
330 1714 aaronmk
                    if rows == []: raise SystemExit('Map error: Root "'
331
                        +in_root+'" not found in input')
332
                    return rows
333
334
                def get_value(in_, row):
335
                    in_ = './{'+(','.join(strings.with_prefixes(
336
                        ['']+prefixes, in_)))+'}' # also with no prefix
337
                    nodes = xpath.get(row, in_, allow_rooted=False)
338
                    if nodes != []: return xml_dom.value(nodes[0])
339
                    else: return None
340
341 1715 aaronmk
                row_ct = map_rows(get_value, get_rows(doc2rows))
342 56 aaronmk
        else: # input is CSV
343 133 aaronmk
            map_ = dict(mappings)
344 1389 aaronmk
            reader, col_names = csvs.reader_and_header(sys.stdin)
345 1403 aaronmk
            row_ct = map_table(col_names, reader)
346 982 aaronmk
347
        return row_ct
348 53 aaronmk
349 838 aaronmk
    def process_inputs(root, row_ready):
350 982 aaronmk
        row_ct = 0
351
        for map_path in map_paths:
352
            row_ct += process_input(root, row_ready, map_path)
353
        return row_ct
354 512 aaronmk
355 1886 aaronmk
    pool.share_vars(locals())
356 130 aaronmk
    if out_is_db:
357 53 aaronmk
        import db_xml
358
359 646 aaronmk
        out_db = connect_db(out_db_config)
360 53 aaronmk
        try:
361 947 aaronmk
            if redo: sql.empty_db(out_db)
362 1886 aaronmk
            pool.share_vars(locals())
363 449 aaronmk
364 838 aaronmk
            def row_ready(row_num, input_row):
365 452 aaronmk
                def on_error(e):
366 1946 aaronmk
                    exc.add_msg(e, term.emph('row #:')+' '+str(row_num+1))
367
                        # row # is interally 0-based, but 1-based to the user
368 828 aaronmk
                    exc.add_msg(e, term.emph('input row:')+'\n'+str(input_row))
369
                    exc.add_msg(e, term.emph('output row:')+'\n'+str(root))
370 1617 aaronmk
                    ex_tracker.track(e, row_num)
371 1886 aaronmk
                pool.share_vars(locals())
372 452 aaronmk
373 2032 aaronmk
                row_root = root.cloneNode(True) # deep copy so don't modify root
374
                xml_func.process(row_root, on_error)
375
                if not xml_dom.is_empty(row_root):
376
                    assert xml_dom.has_one_child(row_root)
377 442 aaronmk
                    try:
378 982 aaronmk
                        sql.with_savepoint(out_db,
379 2032 aaronmk
                            lambda: db_xml.put(out_db, row_root.firstChild,
380 1850 aaronmk
                                row_ins_ct_ref, on_error))
381 1849 aaronmk
                        if commit: out_db.db.commit()
382 449 aaronmk
                    except sql.DatabaseErrors, e: on_error(e)
383
384 982 aaronmk
            row_ct = process_inputs(root, row_ready)
385
            sys.stdout.write('Inserted '+str(row_ins_ct_ref[0])+
386 460 aaronmk
                ' new rows into database\n')
387 1868 aaronmk
388
            # Consume asynchronous tasks
389
            pool.main_loop()
390 53 aaronmk
        finally:
391 1849 aaronmk
            out_db.db.rollback()
392
            out_db.db.close()
393 751 aaronmk
    else:
394 759 aaronmk
        def on_error(e): ex_tracker.track(e)
395 838 aaronmk
        def row_ready(row_num, input_row): pass
396 982 aaronmk
        row_ct = process_inputs(root, row_ready)
397 759 aaronmk
        xml_func.process(root, on_error)
398 751 aaronmk
        if out_is_xml_ref[0]:
399
            doc.writexml(sys.stdout, **xml_dom.prettyxml_config)
400
        else: # output is CSV
401
            raise NotImplementedError('CSV output not supported yet')
402 985 aaronmk
403 1868 aaronmk
    # Consume any asynchronous tasks not already consumed above
404 1862 aaronmk
    pool.main_loop()
405
406 982 aaronmk
    profiler.stop(row_ct)
407
    ex_tracker.add_iters(row_ct)
408 990 aaronmk
    if verbose:
409
        sys.stderr.write('Processed '+str(row_ct)+' input rows\n')
410
        sys.stderr.write(profiler.msg()+'\n')
411
        sys.stderr.write(ex_tracker.msg()+'\n')
412 985 aaronmk
    ex_tracker.exit()
413 53 aaronmk
414 847 aaronmk
def main():
415
    try: main_()
416 1719 aaronmk
    except Parser.SyntaxError, e: raise SystemExit(str(e))
417 847 aaronmk
418 846 aaronmk
if __name__ == '__main__':
419 847 aaronmk
    profile_to = opts.get_env_var('profile_to', None)
420
    if profile_to != None:
421
        import cProfile
422 1584 aaronmk
        sys.stderr.write('Profiling to '+profile_to+'\n')
423 847 aaronmk
        cProfile.run(main.func_code, profile_to)
424
    else: main()