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
        src, sep, src_base = src.partition('/')
56
        in_is_xml = sep != ''
57
    
58
    # Input datasource to XML tree, mapping if needed
59
    if in_is_xml: doc = xml.dom.minidom.parse(sys.stdin)
60
    if uses_map:
61
        import xml_xpath
62
        
63
        map_ = {}
64
        has_types = False # whether outer elements are type containiners
65
        for row in map_reader:
66
            in_, out = row[:2]
67
            if out != '':
68
                if out.startswith('/*s/'): has_types = True # *s for type elem
69
                out = xpath.parse(out)
70
                if in_is_xml: pass # TODO: process the mapping
71
                elif in_is_db: pass # TODO: process the mapping
72
                else: map_[in_] = out
73
        map_stream.close()
74
        
75
        out_doc = xml.dom.minidom.getDOMImplementation().createDocument(None,
76
            dest, None)
77
        if in_is_xml: raise Exception('XML-XML mapping not supported yet')
78
        else: # input is CSV
79
            reader = csv.reader(sys.stdin)
80
            fieldnames = reader.next()
81
            row_idx = 0
82
            for row in reader:
83
                row_id = str(row_idx)
84
                for idx, name in enumerate(fieldnames):
85
                    value = row[idx]
86
                    if value != '' and name in map_:
87
                        path = copy.deepcopy(map_[name]) # don't modify value!
88
                        xpath.set_id(path, row_id, has_types)
89
                        xpath.set_value(path, value)
90
                        xml_xpath.get(out_doc, path, True)
91
                row_idx += 1
92
        doc = out_doc
93
    
94
    # Output XML tree
95
    if to_db_config != None: # output is database
96
        import psycopg2
97
        from psycopg2.extensions import ISOLATION_LEVEL_SERIALIZABLE
98
        
99
        import db_xml
100
        
101
        db = psycopg2.connect(**to_db_config)
102
        db.set_isolation_level(ISOLATION_LEVEL_SERIALIZABLE)
103
        try:
104
            row_ct_ref = [0]
105
            db_xml.xml2db(db, doc.documentElement, row_ct_ref)
106
            print 'Inserted '+str(row_ct_ref[0])+' rows'
107
            if commit: db.commit()
108
        finally:
109
            db.rollback()
110
            db.close()
111
    else: doc.writexml(sys.stdout, addindent='    ', newl='\n') # output is XML
112

    
113
main()
(2-2/3)