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

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

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

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