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):
27
    if util.is_str(name) and name.startswith(':'): return name[1:]
28
    else: return None
29

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

    
265
def main():
266
    try: main_()
267
    except Parser.SyntaxException, e: raise SystemExit(str(e))
268

    
269
if __name__ == '__main__':
270
    profile_to = opts.get_env_var('profile_to', None)
271
    if profile_to != None:
272
        import cProfile
273
        cProfile.run(main.func_code, profile_to)
274
    else: main()
(15-15/25)