Project

General

Profile

1 53 aaronmk
#!/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 294 aaronmk
import traceback
9 53 aaronmk
import xml.dom.minidom
10
11 266 aaronmk
sys.path.append(os.path.dirname(__file__)+"/../lib")
12 53 aaronmk
13 64 aaronmk
import opts
14 281 aaronmk
import Parser
15 131 aaronmk
import sql
16 133 aaronmk
import xml_dom
17 86 aaronmk
import xml_func
18 53 aaronmk
19 84 aaronmk
def metadata_value(name):
20 164 aaronmk
    if type(name) == str and name.startswith(':'): return name[1:]
21 84 aaronmk
    else: return None
22
23 53 aaronmk
def main():
24 131 aaronmk
    env_names = []
25
    def usage_err():
26
        raise SystemExit('Usage: '+opts.env_usage(env_names, True)
27
            +' [commit=1] '+sys.argv[0]+' [map_path] [<input] [>output]')
28 146 aaronmk
    limit = opts.get_env_var('n', None, env_names)
29
    if limit != None: limit = int(limit)
30 135 aaronmk
    commit = opts.env_flag('commit')
31 131 aaronmk
32 53 aaronmk
    # Get db config from env vars
33 131 aaronmk
    db_config_names = ['engine', 'host', 'user', 'password', 'database']
34 53 aaronmk
    def get_db_config(prefix):
35 64 aaronmk
        return opts.get_env_vars(db_config_names, prefix, env_names)
36 67 aaronmk
    in_db_config = get_db_config('in')
37
    out_db_config = get_db_config('out')
38 131 aaronmk
    in_is_db = 'engine' in in_db_config
39
    out_is_db = 'engine' in out_db_config
40 53 aaronmk
41
    # Parse args
42 73 aaronmk
    map_path = None
43 67 aaronmk
    try: _prog_name, map_path = sys.argv
44 53 aaronmk
    except ValueError:
45 135 aaronmk
        if in_is_db: usage_err()
46 53 aaronmk
47 57 aaronmk
    # Load map header
48 130 aaronmk
    in_is_xpaths = True
49 73 aaronmk
    if map_path != None:
50 56 aaronmk
        import copy
51
        import csv
52
53 53 aaronmk
        import xpath
54
55 133 aaronmk
        metadata = []
56 73 aaronmk
        mappings = []
57
        stream = open(map_path, 'rb')
58
        reader = csv.reader(stream)
59 161 aaronmk
        in_label, out_label = reader.next()[:2]
60 61 aaronmk
        def split_col_name(name):
61 72 aaronmk
            name, sep, root = name.partition(':')
62
            return name, sep != '', root
63 161 aaronmk
        in_label, in_is_xpaths, in_root = split_col_name(in_label)
64
        out_label, out_is_xpaths, out_root = split_col_name(out_label)
65 133 aaronmk
        assert out_is_xpaths # CSV output not supported yet
66 161 aaronmk
        has_types = out_root.startswith('/*s/') # outer elements are types
67 73 aaronmk
        for row in reader:
68
            in_, out = row[:2]
69
            if out != '':
70 164 aaronmk
                if out_is_xpaths: out = out_root+out
71
                mappings.append((in_, out))
72 73 aaronmk
        stream.close()
73 130 aaronmk
    in_is_xml = in_is_xpaths and not in_is_db
74 56 aaronmk
75 294 aaronmk
    if in_is_xml: doc0 = xml.dom.minidom.parse(sys.stdin)
76
77
    def process_xml(use_row):
78
        '''Maps datasource to XML tree'''
79 161 aaronmk
        doc1 = xml_dom.create_doc(out_label)
80 141 aaronmk
        root = doc1.documentElement
81 126 aaronmk
        if in_is_db:
82 130 aaronmk
            assert in_is_xpaths
83 126 aaronmk
84 117 aaronmk
            import db_xml
85
86 161 aaronmk
            in_root_xml = xpath.path2xml(in_root)
87 164 aaronmk
            for i, mapping in enumerate(mappings):
88
                in_, out = mapping
89
                if metadata_value(in_) == None:
90 168 aaronmk
                    mappings[i] = (xpath.path2xml(in_root+'/'+in_), out)
91 126 aaronmk
92 131 aaronmk
            in_db = sql.connect(in_db_config)
93 133 aaronmk
            in_pkeys = {}
94 167 aaronmk
            for row_idx, row in enumerate(sql.rows(db_xml.get(in_db,
95
                in_root_xml, in_pkeys, limit))):
96
                row_id = str(row_idx)
97
                pkey, = row
98 133 aaronmk
                for in_, out in mappings:
99 164 aaronmk
                    value = metadata_value(in_)
100
                    if value == None:
101
                        in_ = in_.cloneNode(True) # don't modify orig value!
102 167 aaronmk
                        xml_dom.set_id(xpath.get(in_, in_root), pkey)
103 164 aaronmk
                        value = sql.value_or_none(db_xml.get(in_db, in_,
104
                            in_pkeys))
105
                    if value != None:
106 294 aaronmk
                        try: xpath.put_obj(root, out, row_id, has_types,
107
                            str(value))
108
                        except Exception: traceback.print_exc()
109 117 aaronmk
            in_db.close()
110 161 aaronmk
        elif in_is_xml:
111
            row = xpath.get(doc0.documentElement, in_root)
112
            for row_idx, row in enumerate(xml_dom.NodeElemIter(row.parentNode)):
113
                if not (limit == None or row_idx < limit): break
114
                row_id = str(row_idx)
115
                for in_, out in mappings:
116 164 aaronmk
                    value = metadata_value(in_)
117
                    if value == None:
118
                        node = xpath.get(row, in_)
119
                        if node != None: value = xml_dom.value(node)
120
                    if value != None:
121 294 aaronmk
                        try: xpath.put_obj(root, out, row_id, has_types, value)
122
                        except Exception: traceback.print_exc()
123 56 aaronmk
        else: # input is CSV
124 133 aaronmk
            map_ = dict(mappings)
125 59 aaronmk
            reader = csv.reader(sys.stdin)
126 84 aaronmk
            cols = reader.next()
127 162 aaronmk
            col_idxs = dict([(value, idx) for idx, value in enumerate(cols)])
128 164 aaronmk
            for i, mapping in enumerate(mappings):
129
                in_, out = mapping
130
                if metadata_value(in_) == None:
131
                    try: mappings[i] = (col_idxs[in_], out)
132
                    except KeyError: pass
133 162 aaronmk
134 83 aaronmk
            for row_idx, row in enumerate(reader):
135 146 aaronmk
                if not (limit == None or row_idx < limit): break
136 56 aaronmk
                row_id = str(row_idx)
137 162 aaronmk
                for in_, out in mappings:
138 164 aaronmk
                    value = metadata_value(in_)
139
                    if value == None:
140
                        value = row[in_]
141
                        if value == '': value = None
142
                    if value != None:
143 294 aaronmk
                        try: xpath.put_obj(root, out, row_id, has_types, value)
144
                        except Exception: traceback.print_exc()
145 142 aaronmk
        xml_func.process(root)
146 294 aaronmk
        return doc1
147 53 aaronmk
148 294 aaronmk
    def get_xml(use_row):
149
        '''Inputs datasource to XML tree, mapping if needed'''
150
        if map_path != None: return process_xml(use_row)
151
        else: return doc0
152
153 53 aaronmk
    # Output XML tree
154 130 aaronmk
    if out_is_db:
155 53 aaronmk
        from psycopg2.extensions import ISOLATION_LEVEL_SERIALIZABLE
156
        import db_xml
157
158 133 aaronmk
        out_db = sql.connect(out_db_config)
159
        out_db.set_isolation_level(ISOLATION_LEVEL_SERIALIZABLE)
160 53 aaronmk
        try:
161
            row_ct_ref = [0]
162 294 aaronmk
            def use_row(root): db_xml.xml2db(out_db, root, row_ct_ref)
163
            db_xml.xml2db(out_db, get_xml(use_row).documentElement, row_ct_ref)
164 53 aaronmk
            print 'Inserted '+str(row_ct_ref[0])+' rows'
165 133 aaronmk
            if commit: out_db.commit()
166 53 aaronmk
        finally:
167 133 aaronmk
            out_db.rollback()
168
            out_db.close()
169 294 aaronmk
    else:
170
        def use_row(root): pass # TODO: implement this
171
        xml_dom.writexml(sys.stdout, get_xml(use_row)) # output is XML
172 53 aaronmk
173 133 aaronmk
try: main()
174 294 aaronmk
except Parser.SyntaxException, e: raise SystemExit(str(e))