Project

General

Profile

1
#!/usr/bin/env python
2
# Maps one datasource to another, using a map spreadsheet if needed
3
# For outputting an XML file to a PostgreSQL database, use the general format of
4
# http://vegbank.org/vegdocs/xml/vegbank_example_ver1.0.2.xml
5

    
6
import os.path
7
import sys
8
import xml.dom.minidom as minidom
9

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

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

    
23
def metadata_value(name):
24
    if util.is_str(name) and name.startswith(':'): return name[1:]
25
    else: return None
26

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

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

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