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
    '''Gets all entries for the given key with any of the given prefixes'''
29
    values = []
30
    for prefix in ['']+prefixes: # also lookup with no prefix
31
        try: value = map_[prefix+key]
32
        except KeyError, e: continue # keep going
33
        values.append(value)
34
    
35
    if values != []: return values
36
    else: raise e # re-raise last KeyError
37

    
38
def metadata_value(name): return None # this feature has been removed
39

    
40
def cleanup(val):
41
    if val == None: return val
42
    return util.none_if(strings.cleanup(strings.ustr(val)), u'', u'\\N')
43

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

    
286
def main():
287
    try: main_()
288
    except Parser.SyntaxException, e: raise SystemExit(str(e))
289

    
290
if __name__ == '__main__':
291
    profile_to = opts.get_env_var('profile_to', None)
292
    if profile_to != None:
293
        import cProfile
294
        cProfile.run(main.func_code, profile_to)
295
    else: main()
(16-16/32)