Project

General

Profile

1
#!/usr/bin/env python
2
# Maps one datasource to another, using a map spreadsheet if needed
3
# Exit status is the # of errors in the import, up to the maximum exit status
4
# 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
import csv
8
import os.path
9
import sys
10
import xml.dom.minidom as minidom
11

    
12
sys.path.append(os.path.dirname(__file__)+"/../lib")
13

    
14
import csvs
15
import exc
16
import opts
17
import Parser
18
import profiling
19
import sql
20
import strings
21
import term
22
import util
23
import xpath
24
import xml_dom
25
import xml_func
26

    
27
def get_with_prefix(map_, prefixes, key):
28
    for prefix in ['']+prefixes: # also lookup with no prefix
29
        try: return map_[prefix+key]
30
        except KeyError, e: pass # keep going
31
    raise e # re-raise last KeyError
32

    
33
def metadata_value(name): return None # this feature has been removed
34

    
35
def cleanup(val):
36
    if val == None: return val
37
    return util.none_if(strings.cleanup(strings.ustr(val)), u'', u'\\N')
38

    
39
def main_():
40
    env_names = []
41
    def usage_err():
42
        raise SystemExit('Usage: '+opts.env_usage(env_names, True)+' '
43
            +sys.argv[0]+' [map_path...] [<input] [>output]')
44
    
45
    # Get db config from env vars
46
    db_config_names = ['engine', 'host', 'user', 'password', 'database']
47
    def get_db_config(prefix):
48
        return opts.get_env_vars(db_config_names, prefix, env_names)
49
    in_db_config = get_db_config('in')
50
    out_db_config = get_db_config('out')
51
    in_is_db = 'engine' in in_db_config
52
    out_is_db = 'engine' in out_db_config
53
    
54
    # Get other config from env vars
55
    end = util.cast(int, opts.get_env_var('n', None, env_names))
56
    start = util.cast(int, opts.get_env_var('start', '0', env_names))
57
    if end != None: end += start
58
    test = opts.env_flag('test', False, env_names)
59
    commit = opts.env_flag('commit', False, env_names) and not test
60
        # never commit in test mode
61
    redo = opts.env_flag('redo', test, env_names) and not commit
62
        # never redo in commit mode (manually run `make empty_db` instead)
63
    debug = opts.env_flag('debug', False, env_names)
64
    sql.run_raw_query.debug = debug
65
    verbose = debug or opts.env_flag('verbose', False, env_names)
66
    opts.get_env_var('profile_to', None, env_names) # add to env_names
67
    
68
    # Logging
69
    def log(msg, on=verbose):
70
        if on: sys.stderr.write(msg)
71
    def log_start(action, on=verbose): log(action+'...\n', on)
72
    
73
    # Parse args
74
    map_paths = sys.argv[1:]
75
    if map_paths == []:
76
        if in_is_db or not out_is_db: usage_err()
77
        else: map_paths = [None]
78
    
79
    def connect_db(db_config):
80
        log_start('Connecting to '+sql.db_config_str(db_config))
81
        return sql.connect(db_config)
82
    
83
    ex_tracker = exc.ExPercentTracker(iter_text='row')
84
    profiler = profiling.ItersProfiler(start_now=True, iter_text='row')
85
    
86
    doc = xml_dom.create_doc()
87
    root = doc.documentElement
88
    out_is_xml_ref = [False]
89
    in_label_ref = [None]
90
    def update_in_label():
91
        if in_label_ref[0] != None:
92
            xpath.get(root, '/_ignore/inLabel="'+in_label_ref[0]+'"', True)
93
    def prep_root():
94
        root.clear()
95
        update_in_label()
96
    prep_root()
97
    
98
    def process_input(root, row_ready, map_path):
99
        '''Inputs datasource to XML tree, mapping if needed'''
100
        # Load map header
101
        in_is_xpaths = True
102
        out_is_xpaths = True
103
        out_label = None
104
        if map_path != None:
105
            metadata = []
106
            mappings = []
107
            stream = open(map_path, 'rb')
108
            reader = csv.reader(stream)
109
            in_label, out_label = reader.next()[:2]
110
            
111
            def split_col_name(name):
112
                label, sep, root = name.partition(':')
113
                label, sep2, prefixes_str = label.partition('[')
114
                prefixes_str = strings.remove_suffix(']', prefixes_str)
115
                prefixes = strings.split(',', prefixes_str)
116
                return label, sep != '', root, prefixes
117
                    # extract datasrc from "datasrc[data_format]"
118
            
119
            in_label, in_is_xpaths, in_root, prefixes = split_col_name(in_label)
120
            in_label_ref[0] = in_label
121
            update_in_label()
122
            out_label, out_is_xpaths, out_root = split_col_name(out_label)[:3]
123
            has_types = out_root.startswith('/*s/') # outer elements are types
124
            
125
            for row in reader:
126
                in_, out = row[:2]
127
                if out != '':
128
                    if out_is_xpaths: out = xpath.parse(out_root+out)
129
                    mappings.append((in_, out))
130
            
131
            stream.close()
132
            
133
            root.ownerDocument.documentElement.tagName = out_label
134
        in_is_xml = in_is_xpaths and not in_is_db
135
        out_is_xml_ref[0] = out_is_xpaths and not out_is_db
136
        
137
        if in_is_xml:
138
            doc0 = minidom.parse(sys.stdin)
139
            doc0_root = doc0.documentElement
140
            if out_label == None: out_label = doc0_root.tagName
141
        
142
        def process_rows(process_row, rows):
143
            '''Processes input rows
144
            @param process_row(in_row, i)
145
            '''
146
            i = -1 # in case for loop does not execute
147
            for i, row in enumerate(rows):
148
                if i < start: continue
149
                if end != None and i >= end: break
150
                process_row(row, i)
151
                row_ready(i, row)
152
            row_ct = i-start+1
153
            return row_ct
154
        
155
        def map_rows(get_value, rows):
156
            '''Maps input rows
157
            @param get_value(in_, row):str
158
            '''
159
            def process_row(row, i):
160
                row_id = str(i)
161
                for in_, out in mappings:
162
                    value = metadata_value(in_)
163
                    if value == None:
164
                        log_start('Getting '+str(in_), debug)
165
                        value = cleanup(get_value(in_, row))
166
                    if value != None:
167
                        log_start('Putting '+str(out), debug)
168
                        xpath.put_obj(root, out, row_id, has_types, value)
169
            return process_rows(process_row, rows)
170
        
171
        def map_table(col_names, rows):
172
            col_names_ct = len(col_names)
173
            col_idxs = util.list_flip(col_names)
174
            
175
            i = 0
176
            while i < len(mappings): # mappings len changes in loop
177
                in_, out = mappings[i]
178
                if metadata_value(in_) == None:
179
                    try: mappings[i] = (
180
                        get_with_prefix(col_idxs, prefixes, in_), out)
181
                    except KeyError:
182
                        del mappings[i]
183
                        continue # keep i the same
184
                i += 1
185
            
186
            def get_value(in_, row):
187
                try: return row.list[in_]
188
                except IndexError: return None
189
            def wrap_row(row):
190
                return util.ListDict(util.list_as_length(row, col_names_ct),
191
                    col_names, col_idxs) # handle CSV rows of different lengths
192
            
193
            return map_rows(get_value, util.WrapIter(wrap_row, rows))
194
        
195
        if map_path == None:
196
            iter_ = xml_dom.NodeElemIter(doc0_root)
197
            util.skip(iter_, xml_dom.is_text) # skip metadata
198
            row_ct = process_rows(lambda row, i: root.appendChild(row), iter_)
199
        elif in_is_db:
200
            assert in_is_xpaths
201
            
202
            in_db = connect_db(in_db_config)
203
            in_pkeys = {}
204
            cur = sql.select(in_db, table=in_root, fields=None, conds=None,
205
                limit=end, start=0)
206
            row_ct = map_table(list(sql.col_names(cur)), sql.rows(cur))
207
            
208
            in_db.close()
209
        elif in_is_xml:
210
            def get_value(in_, row):
211
                nodes = xpath.get(row, in_, allow_rooted=False)
212
                if nodes != []: return xml_dom.value(nodes[0])
213
                else: return None
214
            rows = xpath.get(doc0_root, in_root, limit=end)
215
            if rows == []: raise SystemExit('Map error: Root "'+in_root
216
                +'" not found in input')
217
            row_ct = map_rows(get_value, rows)
218
        else: # input is CSV
219
            map_ = dict(mappings)
220
            reader, col_names = csvs.reader_and_header(sys.stdin)
221
            row_ct = map_table(col_names, reader)
222
        
223
        return row_ct
224
    
225
    def process_inputs(root, row_ready):
226
        row_ct = 0
227
        for map_path in map_paths:
228
            row_ct += process_input(root, row_ready, map_path)
229
        return row_ct
230
    
231
    if out_is_db:
232
        import db_xml
233
        
234
        out_db = connect_db(out_db_config)
235
        out_pkeys = {}
236
        try:
237
            if redo: sql.empty_db(out_db)
238
            row_ins_ct_ref = [0]
239
            
240
            def row_ready(row_num, input_row):
241
                def on_error(e):
242
                    exc.add_msg(e, term.emph('row #:')+' '+str(row_num))
243
                    exc.add_msg(e, term.emph('input row:')+'\n'+str(input_row))
244
                    exc.add_msg(e, term.emph('output row:')+'\n'+str(root))
245
                    ex_tracker.track(e)
246
                
247
                xml_func.process(root, on_error)
248
                if not xml_dom.is_empty(root):
249
                    assert xml_dom.has_one_child(root)
250
                    try:
251
                        sql.with_savepoint(out_db,
252
                            lambda: db_xml.put(out_db, root.firstChild,
253
                                out_pkeys, row_ins_ct_ref, on_error))
254
                        if commit: out_db.commit()
255
                    except sql.DatabaseErrors, e: on_error(e)
256
                prep_root()
257
            
258
            row_ct = process_inputs(root, row_ready)
259
            sys.stdout.write('Inserted '+str(row_ins_ct_ref[0])+
260
                ' new rows into database\n')
261
        finally:
262
            out_db.rollback()
263
            out_db.close()
264
    else:
265
        def on_error(e): ex_tracker.track(e)
266
        def row_ready(row_num, input_row): pass
267
        row_ct = process_inputs(root, row_ready)
268
        xml_func.process(root, on_error)
269
        if out_is_xml_ref[0]:
270
            doc.writexml(sys.stdout, **xml_dom.prettyxml_config)
271
        else: # output is CSV
272
            raise NotImplementedError('CSV output not supported yet')
273
    
274
    profiler.stop(row_ct)
275
    ex_tracker.add_iters(row_ct)
276
    if verbose:
277
        sys.stderr.write('Processed '+str(row_ct)+' input rows\n')
278
        sys.stderr.write(profiler.msg()+'\n')
279
        sys.stderr.write(ex_tracker.msg()+'\n')
280
    ex_tracker.exit()
281

    
282
def main():
283
    try: main_()
284
    except Parser.SyntaxException, e: raise SystemExit(str(e))
285

    
286
if __name__ == '__main__':
287
    profile_to = opts.get_env_var('profile_to', None)
288
    if profile_to != None:
289
        import cProfile
290
        cProfile.run(main.func_code, profile_to)
291
    else: main()
(16-16/32)