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 copy
7
import csv
8
import os
9
import os.path
10
import re
11
import sys
12
import xml.dom.minidom
13
from xml.dom.minidom import getDOMImplementation
14
15
sys.path.append(os.path.dirname(__file__)+"/lib")
16
17
def env_flag(name): return name in os.environ and os.environ[name] != ''
18
19
def main():
20
    # Get db config from env vars
21
    db_config_names = ['host', 'user', 'password', 'database']
22
    env_names = []
23
    def get_db_config(prefix):
24
        has_all = True
25
        db_config = {}
26
        for name in db_config_names:
27
            env_name = prefix+'_'+name
28
            env_names.append(env_name)
29
            if env_name in os.environ: db_config[name] = os.environ[env_name]
30
            else: has_all = False
31
        if has_all: return db_config
32
        else: return None
33
    from_db_config = get_db_config('from')
34
    to_db_config = get_db_config('to')
35
    uses_map = not (from_db_config == None and to_db_config != None)
36
37
    # Parse args
38
    prog_name = sys.argv[0]
39
    try: prog_name, map_path = sys.argv
40
    except ValueError:
41 54 aaronmk
        if uses_map: raise SystemExit('Usage: env'+''.join(map(lambda name:
42 53 aaronmk
            ' ['+name+'=...]', env_names))+' [commit=1] '+prog_name
43
            +' [map_path] [<input] [>output]')
44
    commit = env_flag('commit')
45
46
    csv_config = dict(delimiter=',', quotechar='"')
47
48
    # Input datasource to XML tree
49
    if uses_map: # input is CSV
50
        import xpath
51
52
        # Load map
53
        map_ = {}
54
        has_types = False # whether outer elements are type containiners
55
        stream = open(map_path, 'rb')
56
        reader = csv.reader(stream, **csv_config)
57
        src, dest = reader.next()[:2]
58
        for row in reader:
59
            name, path = row[:2]
60
            if name != '' and path != '':
61
                if path.startswith('/*s/'): has_types = True # *s for type elem
62
                path = path.replace('<name>', name)
63
                map_[name] = xpath.XpathParser(path).parse()
64
        stream.close()
65
66
        # Load and map CSV
67
        doc = getDOMImplementation().createDocument(None, dest, None)
68
        reader = csv.reader(sys.stdin, **csv_config)
69
        fieldnames = reader.next()
70
        row_idx = 0
71
        for row in reader:
72
            row_id = str(row_idx)
73
            for idx, name in enumerate(fieldnames):
74
                value = row[idx]
75
                if value != '' and name in map_:
76
                    path = copy.deepcopy(map_[name]) # don't modify main value!
77
                    xpath.set_id(path, row_id, has_types)
78
                    xpath.set_value(path, value)
79
                    xpath.get(doc, path, True)
80
            row_idx += 1
81
    else: doc = xml.dom.minidom.parse(sys.stdin) # input is XML
82
83
    # Output XML tree
84
    if to_db_config != None: # output is database
85
        import psycopg2
86
        from psycopg2.extensions import ISOLATION_LEVEL_SERIALIZABLE
87
88
        import db_xml
89
90
        db = psycopg2.connect(**to_db_config)
91
        db.set_isolation_level(ISOLATION_LEVEL_SERIALIZABLE)
92
        try:
93
            row_ct_ref = [0]
94
            db_xml.xml2db(db, doc.documentElement, row_ct_ref)
95
            print 'Inserted '+str(row_ct_ref[0])+' rows'
96
            if commit: db.commit()
97
        finally:
98
            db.rollback()
99
            db.close()
100
    else: doc.writexml(sys.stdout, addindent='    ', newl='\n') # output is XML
101
102
main()