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
9

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

    
12
import opts
13
from Parser import SyntaxException
14
import sql
15
import xml_dom
16
import xml_func
17

    
18
def metadata_value(name):
19
    if name.startswith(':'): return name[1:]
20
    else: return None
21

    
22
def main():
23
    env_names = []
24
    def usage_err():
25
        raise SystemExit('Usage: '+opts.env_usage(env_names, True)
26
            +' [commit=1] '+sys.argv[0]+' [map_path] [<input] [>output]')
27
    limit = int(opts.get_env_var('n', sys.maxint, env_names))
28
    commit = opts.env_flag('commit')
29
    
30
    # Get db config from env vars
31
    db_config_names = ['engine', 'host', 'user', 'password', 'database']
32
    def get_db_config(prefix):
33
        return opts.get_env_vars(db_config_names, prefix, env_names)
34
    in_db_config = get_db_config('in')
35
    out_db_config = get_db_config('out')
36
    in_is_db = 'engine' in in_db_config
37
    out_is_db = 'engine' in out_db_config
38
    
39
    # Parse args
40
    map_path = None
41
    try: _prog_name, map_path = sys.argv
42
    except ValueError:
43
        if in_is_db: usage_err()
44
    
45
    # Load map header
46
    in_is_xpaths = True
47
    if map_path != None:
48
        import copy
49
        import csv
50
        
51
        import xpath
52
        
53
        metadata = []
54
        mappings = []
55
        stream = open(map_path, 'rb')
56
        reader = csv.reader(stream)
57
        src, dest = reader.next()[:2]
58
        def split_col_name(name):
59
            name, sep, root = name.partition(':')
60
            return name, sep != '', root
61
        src, in_is_xpaths, src_root = split_col_name(src)
62
        dest, out_is_xpaths, dest_root = split_col_name(dest)
63
        assert out_is_xpaths # CSV output not supported yet
64
        has_types = dest_root.startswith('/*s/') # outer elements are types
65
        for row in reader:
66
            in_, out = row[:2]
67
            if out != '':
68
                value = metadata_value(in_)
69
                is_metadata = value != None
70
                if in_is_xpaths and not is_metadata:
71
                    in_ = xpath.parse(src_root+in_)
72
                if out_is_xpaths: out = xpath.parse(dest_root+out)
73
                if is_metadata: metadata.append((value, out))
74
                else: mappings.append((in_, out))
75
        stream.close()
76
    in_is_xml = in_is_xpaths and not in_is_db
77
    
78
    # Input datasource to XML tree, mapping if needed
79
    if in_is_xml: doc0 = xml.dom.minidom.parse(sys.stdin)
80
    if map_path != None:
81
        doc1 = xml_dom.create_doc(dest)
82
        root = doc1.documentElement
83
        if in_is_db:
84
            assert in_is_xpaths
85
            
86
            import db_xml
87
            
88
            src_root = xpath.parse(src_root)
89
            src_root_xml = xpath.path2xml(src_root)
90
            mappings = [(xpath.path2xml(in_), out) for in_, out in mappings]
91
            
92
            in_db = sql.connect(in_db_config)
93
            in_pkeys = {}
94
            for row_idx, row in enumerate(sql.rows(db_xml.get(in_db,
95
                src_root_xml, in_pkeys))):
96
                if not row_idx < limit: break
97
                row_id, = row
98
                row_id = str(row_id)
99
                
100
                def put_col(path, value):
101
                    xpath.put_obj(root, path, row_id, has_types, value)
102
                for value, out in metadata: put_col(out, value)
103
                for in_, out in mappings:
104
                    in_ = in_.cloneNode(True) # don't modify orig value!
105
                    xml_dom.set_id(xpath.get(in_, src_root), row_id)
106
                    value = sql.value_or_none(db_xml.get(in_db, in_, in_pkeys))
107
                    if value != None: put_col(out, str(value))
108
            in_db.close()
109
        elif in_is_xml: raise SystemExit('XML input not supported yet')
110
        else: # input is CSV
111
            map_ = dict(mappings)
112
            reader = csv.reader(sys.stdin)
113
            cols = reader.next()
114
            for row_idx, row in enumerate(reader):
115
                if not row_idx < limit: break
116
                row_id = str(row_idx)
117
                
118
                def put_col(path, value):
119
                    xpath.put_obj(root, path, row_id, has_types, value)
120
                for value, out in metadata: put_col(out, value)
121
                for i, col in enumerate(cols):
122
                    if row[i] != '' and col in map_: put_col(map_[col], row[i])
123
        xml_func.process(doc1)
124
    else: doc1 = doc0
125
    
126
    # Output XML tree
127
    if out_is_db:
128
        from psycopg2.extensions import ISOLATION_LEVEL_SERIALIZABLE
129
        import db_xml
130
        
131
        out_db = sql.connect(out_db_config)
132
        out_db.set_isolation_level(ISOLATION_LEVEL_SERIALIZABLE)
133
        try:
134
            row_ct_ref = [0]
135
            db_xml.xml2db(out_db, doc1.documentElement, row_ct_ref)
136
            print 'Inserted '+str(row_ct_ref[0])+' rows'
137
            if commit: out_db.commit()
138
        finally:
139
            out_db.rollback()
140
            out_db.close()
141
    else: xml_dom.writexml(sys.stdout, doc1) # output is XML
142

    
143
try: main()
144
except SyntaxException, ex: raise SystemExit(str(ex))
(2-2/3)