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 traceback
9
import xml.dom.minidom as minidom
10

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

    
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
    env_names = []
26
    def usage_err():
27
        raise SystemExit('Usage: '+opts.env_usage(env_names, True)
28
            +' [commit=1] '+sys.argv[0]+' [map_path] [<input] [>output]')
29
    limit = opts.get_env_var('n', None, env_names)
30
    if limit != None: limit = int(limit)
31
    commit = opts.env_flag('commit')
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
    # Parse args
43
    map_path = None
44
    try: _prog_name, map_path = sys.argv
45
    except ValueError:
46
        if in_is_db: usage_err()
47
    
48
    # Load map header
49
    in_is_xpaths = True
50
    if map_path != None:
51
        import copy
52
        import csv
53
        
54
        import xpath
55
        
56
        metadata = []
57
        mappings = []
58
        stream = open(map_path, 'rb')
59
        reader = csv.reader(stream)
60
        in_label, out_label = reader.next()[:2]
61
        def split_col_name(name):
62
            name, sep, root = name.partition(':')
63
            return name, sep != '', root
64
        in_label, in_is_xpaths, in_root = split_col_name(in_label)
65
        out_label, out_is_xpaths, out_root = split_col_name(out_label)
66
        assert out_is_xpaths # CSV output not supported yet
67
        has_types = out_root.startswith('/*s/') # outer elements are types
68
        for row in reader:
69
            in_, out = row[:2]
70
            if out != '':
71
                if out_is_xpaths: out = out_root+out
72
                mappings.append((in_, out))
73
        stream.close()
74
    in_is_xml = in_is_xpaths and not in_is_db
75
    
76
    if in_is_xml: doc0 = minidom.parse(sys.stdin)
77
    
78
    def process_input(use_row):
79
        '''Inputs datasource to XML tree, mapping if needed'''
80
        doc1 = xml_dom.create_doc(out_label)
81
        root = doc1.documentElement
82
        
83
        def process_rows(get_value, rows):
84
            '''Processes input values
85
            @param get_value f(in_, row):str
86
            '''
87
            try:
88
                for i, row in enumerate(rows):
89
                    if not (limit == None or i < limit): break
90
                    row_id = str(i)
91
                    for in_, out in mappings:
92
                        value = metadata_value(in_)
93
                        if value == None: value = get_value(in_, row)
94
                        if value != None:
95
                            xpath.put_obj(root, out, row_id, has_types, value)
96
            except Exception: traceback.print_exc()
97
        
98
        if map_path == None:
99
            iter_ = xml_dom.NodeElemIter(doc0.documentElement)
100
            util.skip(iter_, xml_dom.is_text) # skip metadata
101
            #map(use_row, iter_)
102
            return doc0
103
        elif in_is_db:
104
            assert in_is_xpaths
105
            
106
            import db_xml
107
            
108
            in_root_xml = xpath.path2xml(in_root)
109
            for i, mapping in enumerate(mappings):
110
                in_, out = mapping
111
                if metadata_value(in_) == None:
112
                    mappings[i] = (xpath.path2xml(in_root+'/'+in_), out)
113
            
114
            in_db = sql.connect(in_db_config)
115
            in_pkeys = {}
116
            def get_value(in_, row):
117
                pkey, = row
118
                in_ = in_.cloneNode(True) # don't modify orig value!
119
                xml_dom.set_id(xpath.get(in_, in_root), pkey)
120
                value = sql.value_or_none(db_xml.get(in_db, in_, in_pkeys))
121
                if value != None: return str(value)
122
                else: return None
123
            process_rows(get_value, sql.rows(db_xml.get(in_db, in_root_xml,
124
                in_pkeys, limit)))
125
            in_db.close()
126
        elif in_is_xml:
127
            def get_value(in_, row):
128
                node = xpath.get(row, in_)
129
                if node != None: return xml_dom.value(node)
130
                else: return None
131
            row0 = xpath.get(doc0.documentElement, in_root)
132
            process_rows(get_value, xml_dom.NodeElemIter(row0.parentNode))
133
        else: # input is CSV
134
            map_ = dict(mappings)
135
            reader = csv.reader(sys.stdin)
136
            cols = reader.next()
137
            col_idxs = dict([(value, idx) for idx, value in enumerate(cols)])
138
            for i, mapping in enumerate(mappings):
139
                in_, out = mapping
140
                if metadata_value(in_) == None:
141
                    try: mappings[i] = (col_idxs[in_], out)
142
                    except KeyError: pass
143
            
144
            def get_value(in_, row):
145
                value = row[in_]
146
                if value != '': return value
147
                else: return None
148
            process_rows(get_value, reader)
149
        xml_func.process(root)
150
        return doc1
151
    
152
    # Output XML tree
153
    if out_is_db:
154
        from psycopg2.extensions import ISOLATION_LEVEL_SERIALIZABLE
155
        import db_xml
156
        
157
        out_db = sql.connect(out_db_config)
158
        out_db.set_isolation_level(ISOLATION_LEVEL_SERIALIZABLE)
159
        out_pkeys = {}
160
        try:
161
            row_ct_ref = [0]
162
            def use_row(root):
163
                try:
164
                    db_xml.put(out_db, root, False, row_ct_ref, out_pkeys)
165
                    if commit: db.commit()
166
                except Exception:
167
                    out_db.rollback()
168
                    traceback.print_exc()
169
            map(use_row, process_input(use_row).firstChild)
170
            print 'Inserted '+str(row_ct_ref[0])+' rows'
171
        finally:
172
            out_db.rollback()
173
            out_db.close()
174
    else: # output is XML
175
        output = sys.stdout
176
        config = xml_dom.prettyxml_config
177
        doc = xml_dom.create_doc(out_label)
178
        doc.write_opening(output, **config)
179
        def use_row(root): root.writexml(output, indent=1, **config)
180
        map(use_row, process_input(use_row).firstChild)
181
        doc.write_closing(output, **config)
182

    
183
try: main()
184
except Parser.SyntaxException, e: raise SystemExit(str(e))
(7-7/14)