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

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

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