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 exc
15
import opts
16
import Parser
17
import profiling
18
import sql
19
import strings
20
import term
21
import util
22
import xpath
23
import xml_dom
24
import xml_func
25

    
26
def metadata_value(name): return None # this feature has been removed
27

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

    
273
def main():
274
    try: main_()
275
    except Parser.SyntaxException, e: raise SystemExit(str(e))
276

    
277
if __name__ == '__main__':
278
    profile_to = opts.get_env_var('profile_to', None)
279
    if profile_to != None:
280
        import cProfile
281
        cProfile.run(main.func_code, profile_to)
282
    else: main()
(14-14/27)