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
def env_flag(name): return name in os.environ and os.environ[name] != ''
14

    
15
def main():
16
    # Get db config from env vars
17
    db_config_names = ['host', 'user', 'password', 'database']
18
    env_names = []
19
    def get_db_config(prefix):
20
        has_all = True
21
        db_config = {}
22
        for name in db_config_names:
23
            env_name = prefix+'_'+name
24
            env_names.append(env_name)
25
            if env_name in os.environ: db_config[name] = os.environ[env_name]
26
            else: has_all = False
27
        if has_all: return db_config
28
        else: return None
29
    from_db_config = get_db_config('from')
30
    to_db_config = get_db_config('to')
31
    in_is_db = from_db_config != None
32
    out_is_db = to_db_config != None
33
    uses_map = in_is_db or not out_is_db
34
    
35
    # Parse args
36
    prog_name = sys.argv[0]
37
    try: prog_name, map_path = sys.argv
38
    except ValueError:
39
        if uses_map: raise SystemExit('Usage: env'+''.join(map(lambda name:
40
            ' ['+name+'=...]', env_names))+' [commit=1] '+prog_name
41
            +' [map_path] [<input] [>output]')
42
    commit = env_flag('commit')
43
    
44
    # Load map header
45
    in_is_xml = True
46
    if uses_map:
47
        import copy
48
        import csv
49
        
50
        import xpath
51
        
52
        map_stream = open(map_path, 'rb')
53
        map_reader = csv.reader(map_stream)
54
        src, dest = map_reader.next()[:2]
55
        def split_col_name(name):
56
            name, sep, prefix = name.partition('/')
57
            return name, sep != '', sep+prefix
58
        src, in_is_xml, src_prefix = split_col_name(src)
59
        dest, out_is_xml, dest_prefix = split_col_name(dest)
60
        assert out_is_xml
61
        has_types = dest_prefix.startswith('/*s/') # outer elements are types
62
    
63
    # Input datasource to XML tree, mapping if needed
64
    if in_is_xml: doc = xml.dom.minidom.parse(sys.stdin)
65
    if uses_map:
66
        from Parser import SyntaxException
67
        import xml_xpath
68
        
69
        map_ = {}
70
        for row in map_reader:
71
            in_, out = row[:2]
72
            if out != '':
73
                try: out = xpath.parse(dest_prefix+out)
74
                except SyntaxException, ex: raise SystemExit(str(ex))
75
                if in_is_xml: pass # TODO: process the mapping
76
                elif in_is_db: pass # TODO: process the mapping
77
                else: map_[in_] = out
78
        map_stream.close()
79
        
80
        out_doc = xml.dom.minidom.getDOMImplementation().createDocument(None,
81
            dest, None)
82
        if in_is_xml: raise Exception('XML-XML mapping not supported yet')
83
        else: # input is CSV
84
            reader = csv.reader(sys.stdin)
85
            fieldnames = reader.next()
86
            row_idx = 0
87
            for row in reader:
88
                row_id = str(row_idx)
89
                for idx, name in enumerate(fieldnames):
90
                    value = row[idx]
91
                    if value != '' and name in map_:
92
                        path = copy.deepcopy(map_[name]) # don't modify value!
93
                        xpath.set_id(path, row_id, has_types)
94
                        xpath.set_value(path, value)
95
                        xml_xpath.get(out_doc, path, True)
96
                row_idx += 1
97
        doc = out_doc
98
    
99
    # Output XML tree
100
    if to_db_config != None: # output is database
101
        import psycopg2
102
        from psycopg2.extensions import ISOLATION_LEVEL_SERIALIZABLE
103
        
104
        import db_xml
105
        
106
        db = psycopg2.connect(**to_db_config)
107
        db.set_isolation_level(ISOLATION_LEVEL_SERIALIZABLE)
108
        try:
109
            row_ct_ref = [0]
110
            db_xml.xml2db(db, doc.documentElement, row_ct_ref)
111
            print 'Inserted '+str(row_ct_ref[0])+' rows'
112
            if commit: db.commit()
113
        finally:
114
            db.rollback()
115
            db.close()
116
    else: doc.writexml(sys.stdout, addindent='    ', newl='\n') # output is XML
117

    
118
main()
(2-2/3)