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 util
18
import xml_dom
19
import xml_func
20

    
21
def metadata_value(name):
22
    if type(name) == str and name.startswith(':'): return name[1:]
23
    else: return None
24

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

    
223
try: main()
224
except Parser.SyntaxException, e: raise SystemExit(str(e))
(9-9/17)