1 |
11
|
aaronmk
|
#!/usr/bin/env python
|
2 |
|
|
# Imports an XML file into a PostgreSQL database
|
3 |
|
|
# Format: see http://vegbank.org/vegdocs/xml/vegbank_example_ver1.0.2.xml
|
4 |
|
|
|
5 |
|
|
import os
|
6 |
|
|
import psycopg2
|
7 |
|
|
from psycopg2.extensions import ISOLATION_LEVEL_SERIALIZABLE
|
8 |
|
|
import sys
|
9 |
|
|
import xml.dom.minidom
|
10 |
|
|
|
11 |
13
|
aaronmk
|
import xml_db
|
12 |
11
|
aaronmk
|
|
13 |
|
|
def env_flag(name): return name in os.environ and os.environ[name] != ''
|
14 |
|
|
|
15 |
|
|
def main():
|
16 |
|
|
prog_name = sys.argv.pop(0)
|
17 |
|
|
try:
|
18 |
|
|
db_config = {}
|
19 |
|
|
for name in ['host', 'user', 'password', 'database']:
|
20 |
|
|
if os.environ[name] != '': db_config[name] = os.environ[name]
|
21 |
|
|
except KeyError: raise Exception('Usage: env host=... user=... password=...'
|
22 |
|
|
' database=... [commit=1] '+prog_name+' <dataset')
|
23 |
|
|
commit = env_flag('commit')
|
24 |
|
|
|
25 |
|
|
# Process dataset
|
26 |
|
|
db = psycopg2.connect(**db_config)
|
27 |
|
|
db.set_isolation_level(ISOLATION_LEVEL_SERIALIZABLE)
|
28 |
|
|
try:
|
29 |
|
|
doc = xml.dom.minidom.parse(sys.stdin)
|
30 |
13
|
aaronmk
|
print 'Inserted '+str(xml_db.xml2db(doc.documentElement, db))+' rows'
|
31 |
11
|
aaronmk
|
if commit: db.commit()
|
32 |
|
|
finally:
|
33 |
|
|
db.rollback()
|
34 |
|
|
db.close()
|
35 |
|
|
|
36 |
|
|
main()
|