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_idxs = util.list_flip(col_names)
173
            
174
            i = 0
175
            while i < len(mappings): # mappings len changes in loop
176
                in_, out = mappings[i]
177
                if metadata_value(in_) == None:
178
                    try: mappings[i] = (
179
                        get_with_prefix(col_idxs, prefixes, in_), out)
180
                    except KeyError:
181
                        del mappings[i]
182
                        continue # keep i the same
183
                i += 1
184
            
185
            def get_value(in_, row):
186
                try: return row.list[in_]
187
                except IndexError: return None
188
            def wrap_row(row): return util.ListDict(row, col_names, col_idxs)
189
            
190
            return map_rows(get_value, util.WrapIter(wrap_row, rows))
191
        
192
        if map_path == None:
193
            iter_ = xml_dom.NodeElemIter(doc0_root)
194
            util.skip(iter_, xml_dom.is_text) # skip metadata
195
            row_ct = process_rows(lambda row, i: root.appendChild(row), iter_)
196
        elif in_is_db:
197
            assert in_is_xpaths
198
            
199
            in_db = connect_db(in_db_config)
200
            in_pkeys = {}
201
            cur = sql.select(in_db, table=in_root, fields=None, conds=None,
202
                limit=end, start=0)
203
            row_ct = map_table(list(sql.col_names(cur)), sql.rows(cur))
204
            
205
            in_db.close()
206
        elif in_is_xml:
207
            def get_value(in_, row):
208
                nodes = xpath.get(row, in_, allow_rooted=False)
209
                if nodes != []: return xml_dom.value(nodes[0])
210
                else: return None
211
            rows = xpath.get(doc0_root, in_root, limit=end)
212
            if rows == []: raise SystemExit('Map error: Root "'+in_root
213
                +'" not found in input')
214
            row_ct = map_rows(get_value, rows)
215
        else: # input is CSV
216
            map_ = dict(mappings)
217
            reader, col_names = csvs.reader_and_header(sys.stdin)
218
            row_ct = map_table(col_names, reader)
219
        
220
        return row_ct
221
    
222
    def process_inputs(root, row_ready):
223
        row_ct = 0
224
        for map_path in map_paths:
225
            row_ct += process_input(root, row_ready, map_path)
226
        return row_ct
227
    
228
    if out_is_db:
229
        import db_xml
230
        
231
        out_db = connect_db(out_db_config)
232
        out_pkeys = {}
233
        try:
234
            if redo: sql.empty_db(out_db)
235
            row_ins_ct_ref = [0]
236
            
237
            def row_ready(row_num, input_row):
238
                def on_error(e):
239
                    exc.add_msg(e, term.emph('row #:')+' '+str(row_num))
240
                    exc.add_msg(e, term.emph('input row:')+'\n'+str(input_row))
241
                    exc.add_msg(e, term.emph('output row:')+'\n'+str(root))
242
                    ex_tracker.track(e)
243
                
244
                xml_func.process(root, on_error)
245
                if not xml_dom.is_empty(root):
246
                    assert xml_dom.has_one_child(root)
247
                    try:
248
                        sql.with_savepoint(out_db,
249
                            lambda: db_xml.put(out_db, root.firstChild,
250
                                out_pkeys, row_ins_ct_ref, on_error))
251
                        if commit: out_db.commit()
252
                    except sql.DatabaseErrors, e: on_error(e)
253
                prep_root()
254
            
255
            row_ct = process_inputs(root, row_ready)
256
            sys.stdout.write('Inserted '+str(row_ins_ct_ref[0])+
257
                ' new rows into database\n')
258
        finally:
259
            out_db.rollback()
260
            out_db.close()
261
    else:
262
        def on_error(e): ex_tracker.track(e)
263
        def row_ready(row_num, input_row): pass
264
        row_ct = process_inputs(root, row_ready)
265
        xml_func.process(root, on_error)
266
        if out_is_xml_ref[0]:
267
            doc.writexml(sys.stdout, **xml_dom.prettyxml_config)
268
        else: # output is CSV
269
            raise NotImplementedError('CSV output not supported yet')
270
    
271
    profiler.stop(row_ct)
272
    ex_tracker.add_iters(row_ct)
273
    if verbose:
274
        sys.stderr.write('Processed '+str(row_ct)+' input rows\n')
275
        sys.stderr.write(profiler.msg()+'\n')
276
        sys.stderr.write(ex_tracker.msg()+'\n')
277
    ex_tracker.exit()
278

    
279
def main():
280
    try: main_()
281
    except Parser.SyntaxException, e: raise SystemExit(str(e))
282

    
283
if __name__ == '__main__':
284
    profile_to = opts.get_env_var('profile_to', None)
285
    if profile_to != None:
286
        import cProfile
287
        cProfile.run(main.func_code, profile_to)
288
    else: main()
(14-14/28)