1
|
#!/usr/bin/env python
|
2
|
# Loads a command's CSV output stream into a PostgreSQL table.
|
3
|
# The command may be run more than once.
|
4
|
|
5
|
import csv
|
6
|
import os.path
|
7
|
import re
|
8
|
import subprocess
|
9
|
import sys
|
10
|
|
11
|
sys.path.append(os.path.dirname(__file__)+"/../lib")
|
12
|
|
13
|
import csvs
|
14
|
import exc
|
15
|
import opts
|
16
|
import sql
|
17
|
import sql_io
|
18
|
import sql_gen
|
19
|
import streams
|
20
|
import strings
|
21
|
import util
|
22
|
|
23
|
def main():
|
24
|
# Usage
|
25
|
env_names = []
|
26
|
def usage_err():
|
27
|
raise SystemExit('Usage: '+opts.env_usage(env_names)+' '+sys.argv[0]
|
28
|
+' input_cmd [args...]')
|
29
|
|
30
|
# Parse args
|
31
|
input_cmd = sys.argv[1:]
|
32
|
|
33
|
# Get config from env vars
|
34
|
table = opts.get_env_var('table', None, env_names)
|
35
|
schema = opts.get_env_var('schema', 'public', env_names)
|
36
|
has_row_num = opts.env_flag('has_row_num', True, env_names)
|
37
|
db_config = opts.get_env_vars(sql.db_config_names, None, env_names)
|
38
|
errors_table_only = opts.env_flag('errors_table_only', False, env_names)
|
39
|
verbosity = util.cast(float, opts.get_env_var('verbosity', 3, env_names))
|
40
|
|
41
|
if not (input_cmd != [] and table != None and 'engine' in db_config):
|
42
|
usage_err()
|
43
|
|
44
|
# Connect to DB
|
45
|
def log(msg, level=1):
|
46
|
'''Higher level -> more verbose'''
|
47
|
if level <= verbosity:
|
48
|
sys.stderr.write(strings.to_raw_str(msg.rstrip('\n')+'\n'))
|
49
|
db = sql.connect(db_config, log_debug=log)
|
50
|
|
51
|
table = sql_gen.Table(table, schema)
|
52
|
|
53
|
log('Creating errors table')
|
54
|
errors_table = sql_io.errors_table(db, table, if_exists=False)
|
55
|
if errors_table_only: sql.drop_table(db, errors_table)
|
56
|
typed_cols = [
|
57
|
sql_gen.TypedCol('column', 'text', nullable=False),
|
58
|
sql_gen.TypedCol('value', 'text'),
|
59
|
sql_gen.TypedCol('error_code', 'character varying(5)',
|
60
|
nullable=False),
|
61
|
sql_gen.TypedCol('error', 'text', nullable=False),
|
62
|
]
|
63
|
sql.create_table(db, errors_table, typed_cols, has_pkey=False)
|
64
|
index_cols = ['column', 'value', 'error_code', 'error']
|
65
|
sql.add_index(db, index_cols, errors_table, unique=True)
|
66
|
|
67
|
use_copy_from = [True]
|
68
|
|
69
|
# Loads data into the table using the currently-selected approach.
|
70
|
def load():
|
71
|
# Open input stream
|
72
|
proc = subprocess.Popen(input_cmd, stdout=subprocess.PIPE, bufsize=-1)
|
73
|
in_ = proc.stdout
|
74
|
|
75
|
# Get format info
|
76
|
info = csvs.stream_info(in_, parse_header=True)
|
77
|
dialect = info.dialect
|
78
|
if csvs.is_tsv(dialect): use_copy_from[0] = False
|
79
|
col_names = map(strings.to_unicode, info.header)
|
80
|
for i, col in enumerate(col_names): # replace empty column names
|
81
|
if col == '': col_names[i] = 'column_'+str(i)
|
82
|
|
83
|
# Select schema and escape names
|
84
|
def esc_name(name): return db.esc_name(name)
|
85
|
|
86
|
typed_cols = [sql_gen.TypedCol(v, 'text') for v in col_names]
|
87
|
if has_row_num:
|
88
|
typed_cols.insert(0, sql_gen.TypedCol('row_num', 'serial',
|
89
|
nullable=False))
|
90
|
|
91
|
log('Creating table')
|
92
|
sql.create_table(db, table, typed_cols, has_pkey=has_row_num,
|
93
|
col_indexes=False)
|
94
|
|
95
|
# Remove rows from any failed COPY FROM
|
96
|
sql.truncate(db, table)
|
97
|
|
98
|
def load_():
|
99
|
# Create COPY FROM statement
|
100
|
if use_copy_from[0]:
|
101
|
copy_from = ('COPY '+table.to_str(db)+' ('
|
102
|
+(', '.join(map(esc_name, col_names)))
|
103
|
+') FROM STDIN DELIMITER '+db.esc_value(dialect.delimiter)
|
104
|
+' NULL '+db.esc_value(''))
|
105
|
assert not csvs.is_tsv(dialect)
|
106
|
copy_from += ' CSV'
|
107
|
if dialect.quoting != csv.QUOTE_NONE:
|
108
|
quote_str = db.esc_value(dialect.quotechar)
|
109
|
copy_from += ' QUOTE '+quote_str
|
110
|
if dialect.doublequote: copy_from += ' ESCAPE '+quote_str
|
111
|
copy_from += ';\n'
|
112
|
|
113
|
# Load the data
|
114
|
line_in = streams.ProgressInputStream(in_, sys.stderr, n=1000)
|
115
|
try:
|
116
|
if use_copy_from[0]:
|
117
|
log('Using COPY FROM')
|
118
|
log(copy_from, level=2)
|
119
|
db.db.cursor().copy_expert(copy_from, line_in)
|
120
|
else:
|
121
|
log('Using INSERT')
|
122
|
cols_ct = len(col_names)+1 # +1 for row_num
|
123
|
for row in csvs.make_reader(line_in, dialect):
|
124
|
row = map(strings.to_unicode, row)
|
125
|
row.insert(0, sql.default) # row_num is autogen
|
126
|
util.list_set_length(row, cols_ct) # truncate extra cols
|
127
|
sql.insert(db, table, row, cacheable=False, log_level=5)
|
128
|
finally:
|
129
|
line_in.close() # also closes proc.stdout
|
130
|
proc.wait()
|
131
|
sql.with_savepoint(db, load_)
|
132
|
|
133
|
log('Cleaning up table')
|
134
|
sql_io.cleanup_table(db, table, col_names)
|
135
|
|
136
|
log('Vacuuming and reanalyzing table')
|
137
|
sql.vacuum(db, table)
|
138
|
|
139
|
if not errors_table_only:
|
140
|
try: load()
|
141
|
except sql.DatabaseErrors, e:
|
142
|
if use_copy_from[0]: # first try
|
143
|
exc.print_ex(e, plain=True)
|
144
|
use_copy_from[0] = False
|
145
|
load() # try again with different approach
|
146
|
else: raise
|
147
|
|
148
|
main()
|