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 os.path
8
import sys
9
import xml.dom.minidom as minidom
10

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

    
13
import exc
14
import opts
15
import Parser
16
import profiling
17
import sql
18
import strings
19
import term
20
import util
21
import xml_dom
22
import xml_func
23

    
24
def metadata_value(name):
25
    if util.is_str(name) and name.startswith(':'): return name[1:]
26
    else: return None
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
        db = sql.connect(db_config)
71
        return db
72
    
73
    out_is_xml_ref = [False]
74
    
75
    def process_input(root, row_ready, map_path):
76
        '''Inputs datasource to XML tree, mapping if needed'''
77
        # Load map header
78
        in_is_xpaths = True
79
        out_is_xpaths = True
80
        out_label = None
81
        if map_path != None:
82
            import copy
83
            import csv
84
            
85
            import xpath
86
            
87
            metadata = []
88
            mappings = []
89
            stream = open(map_path, 'rb')
90
            reader = csv.reader(stream)
91
            in_label, out_label = reader.next()[:2]
92
            def split_col_name(name):
93
                name, sep, root = name.partition(':')
94
                return name, sep != '', root
95
            in_label, in_is_xpaths, in_root = split_col_name(in_label)
96
            out_label, out_is_xpaths, out_root = split_col_name(out_label)
97
            has_types = out_root.startswith('/*s/') # outer elements are types
98
            for row in reader:
99
                in_, out = row[:2]
100
                if out != '':
101
                    if out_is_xpaths: out = xpath.parse(out_root+out)
102
                    mappings.append((in_, out))
103
            stream.close()
104
            
105
            root.ownerDocument.documentElement.tagName = out_label
106
        in_is_xml = in_is_xpaths and not in_is_db
107
        out_is_xml_ref[0] = out_is_xpaths and not out_is_db
108
        
109
        if in_is_xml:
110
            doc0 = minidom.parse(sys.stdin)
111
            if out_label == None: out_label = doc0.documentElement.tagName
112
        
113
        def process_rows(process_row, rows):
114
            '''Processes input rows
115
            @param process_row(in_row, i)
116
            '''
117
            i = -1 # in case for loop does not execute
118
            for i, row in enumerate(rows):
119
                if i < start: continue
120
                if end != None and i >= end: break
121
                process_row(row, i)
122
                row_ready(i, row)
123
            row_ct = i-start+1
124
            return row_ct
125
        
126
        def map_rows(get_value, rows):
127
            '''Maps input rows
128
            @param get_value(in_, row):str
129
            '''
130
            def process_row(row, i):
131
                row_id = str(i)
132
                for in_, out in mappings:
133
                    value = metadata_value(in_)
134
                    if value == None:
135
                        log_start('Getting '+str(in_), debug)
136
                        value = get_value(in_, row)
137
                    if value != None: xpath.put_obj(root, out, row_id,
138
                        has_types, strings.cleanup(value))
139
            return process_rows(process_row, rows)
140
        
141
        if map_path == None:
142
            iter_ = xml_dom.NodeElemIter(doc0.documentElement)
143
            util.skip(iter_, xml_dom.is_text) # skip metadata
144
            row_ct = process_rows(lambda row, i: root.appendChild(row), iter_)
145
        elif in_is_db:
146
            assert in_is_xpaths
147
            
148
            import db_xml
149
            
150
            in_root_xml = xpath.path2xml(in_root)
151
            for i, mapping in enumerate(mappings):
152
                in_, out = mapping
153
                if metadata_value(in_) == None:
154
                    mappings[i] = (xpath.path2xml(in_root+'/'+in_), out)
155
            
156
            in_db = connect_db(in_db_config)
157
            in_pkeys = {}
158
            def get_value(in_, row):
159
                pkey, = row
160
                in_ = in_.cloneNode(True) # don't modify orig value!
161
                xml_dom.set_id(xpath.get(in_, in_root)[0], pkey)
162
                value = sql.value_or_none(db_xml.get(in_db, in_, in_pkeys))
163
                if value != None: return str(value)
164
                else: return None
165
            row_ct = map_rows(get_value, sql.rows(db_xml.get(in_db, in_root_xml,
166
                in_pkeys, end, 0)))
167
            in_db.close()
168
        elif in_is_xml:
169
            def get_value(in_, row):
170
                nodes = xpath.get(row, in_)
171
                if nodes != []: return xml_dom.value(nodes[0])
172
                else: return None
173
            rows = xpath.get(doc0.documentElement, in_root, limit=end)
174
            if rows == []: raise SystemExit('Map error: Root "'+in_root
175
                +'" not found in input')
176
            row_ct = map_rows(get_value, rows)
177
        else: # input is CSV
178
            map_ = dict(mappings)
179
            reader = csv.reader(sys.stdin)
180
            cols = reader.next()
181
            col_idxs = dict([(value, idx) for idx, value in enumerate(cols)])
182
            for i, mapping in enumerate(mappings):
183
                in_, out = mapping
184
                if metadata_value(in_) == None:
185
                    try: mappings[i] = (col_idxs[in_], out)
186
                    except KeyError: pass
187
            
188
            def get_value(in_, row):
189
                value = row[in_]
190
                if value != '': return value
191
                else: return None
192
            row_ct = map_rows(get_value, reader)
193
        
194
        return row_ct
195
    
196
    def process_inputs(root, row_ready):
197
        row_ct = 0
198
        for map_path in map_paths:
199
            row_ct += process_input(root, row_ready, map_path)
200
        return row_ct
201
    
202
    ex_tracker = exc.ExPercentTracker(iter_text='row')
203
    profiler = profiling.ItersProfiler(start_now=True, iter_text='row')
204
    
205
    doc = xml_dom.create_doc()
206
    root = doc.documentElement
207
    if out_is_db:
208
        import db_xml
209
        
210
        out_db = connect_db(out_db_config)
211
        out_pkeys = {}
212
        try:
213
            if redo: sql.empty_db(out_db)
214
            row_ins_ct_ref = [0]
215
            
216
            def row_ready(row_num, input_row):
217
                def on_error(e):
218
                    exc.add_msg(e, term.emph('row #:')+' '+str(row_num))
219
                    exc.add_msg(e, term.emph('input row:')+'\n'+str(input_row))
220
                    exc.add_msg(e, term.emph('output row:')+'\n'+str(root))
221
                    ex_tracker.track(e)
222
                
223
                xml_func.process(root, on_error)
224
                if not xml_dom.is_empty(root):
225
                    assert xml_dom.has_one_child(root)
226
                    try:
227
                        sql.with_savepoint(out_db,
228
                            lambda: db_xml.put(out_db, root.firstChild,
229
                                out_pkeys, row_ins_ct_ref, on_error))
230
                        if commit: out_db.commit()
231
                    except sql.DatabaseErrors, e: on_error(e)
232
                root.clear()
233
            
234
            row_ct = process_inputs(root, row_ready)
235
            sys.stdout.write('Inserted '+str(row_ins_ct_ref[0])+
236
                ' new rows into database\n')
237
        finally:
238
            out_db.rollback()
239
            out_db.close()
240
    else:
241
        def on_error(e): ex_tracker.track(e)
242
        def row_ready(row_num, input_row): pass
243
        row_ct = process_inputs(root, row_ready)
244
        xml_func.process(root, on_error)
245
        if out_is_xml_ref[0]:
246
            doc.writexml(sys.stdout, **xml_dom.prettyxml_config)
247
        else: # output is CSV
248
            raise NotImplementedError('CSV output not supported yet')
249
    
250
    profiler.stop(row_ct)
251
    ex_tracker.add_iters(row_ct)
252
    if verbose:
253
        sys.stderr.write('Processed '+str(row_ct)+' input rows\n')
254
        sys.stderr.write(profiler.msg()+'\n')
255
        sys.stderr.write(ex_tracker.msg()+'\n')
256
    ex_tracker.exit()
257

    
258
def main():
259
    try: main_()
260
    except Parser.SyntaxException, e: raise SystemExit(str(e))
261

    
262
if __name__ == '__main__':
263
    profile_to = opts.get_env_var('profile_to', None)
264
    if profile_to != None:
265
        import cProfile
266
        cProfile.run(main.func_code, profile_to)
267
    else: main()
(15-15/25)