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
7
import os.path
8
import sys
9
import xml.dom.minidom
10

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

    
13
import opts
14
import sql
15
import xml_func
16

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

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

    
128
main()
(2-2/3)