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 sql
16
import strings
17
import term
18
import util
19
import xml_dom
20
import xml_func
21

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

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

    
238
def main():
239
    try: main_()
240
    except Parser.SyntaxException, e: raise SystemExit(str(e))
241

    
242
if __name__ == '__main__':
243
    profile_to = opts.get_env_var('profile_to', None)
244
    if profile_to != None:
245
        import cProfile
246
        cProfile.run(main.func_code, profile_to)
247
    else: main()
(10-10/19)