Project

General

Profile

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 ((errors_table_only or input_cmd != []) and table != None
42
        and 'engine' in db_config):
43
        usage_err()
44
    
45
    # Connect to DB
46
    def log(msg, level=1):
47
        '''Higher level -> more verbose'''
48
        if level <= verbosity:
49
            sys.stderr.write(strings.to_raw_str(msg.rstrip('\n')+'\n'))
50
    db = sql.connect(db_config, log_debug=log)
51
    
52
    table = sql_gen.Table(table, schema)
53
    
54
    use_copy_from = [True]
55
    
56
    # Loads data into the table using the currently-selected approach.
57
    def load():
58
        # Open input stream
59
        proc = subprocess.Popen(input_cmd, stdout=subprocess.PIPE, bufsize=-1)
60
        in_ = proc.stdout
61
        
62
        # Get format info
63
        info = csvs.stream_info(in_, parse_header=True)
64
        dialect = info.dialect
65
        if csvs.is_tsv(dialect): use_copy_from[0] = False
66
        col_names = map(strings.to_unicode, info.header)
67
        for i, col in enumerate(col_names): # replace empty column names
68
            if col == '': col_names[i] = 'column_'+str(i)
69
        
70
        # Select schema and escape names
71
        def esc_name(name): return db.esc_name(name)
72
        
73
        typed_cols = [sql_gen.TypedCol(v, 'text') for v in col_names]
74
        if has_row_num:
75
            typed_cols.insert(0, sql_gen.TypedCol('row_num', 'serial',
76
                nullable=False))
77
        
78
        log('Creating table')
79
        sql.create_table(db, table, typed_cols, has_pkey=has_row_num,
80
            col_indexes=False)
81
        
82
        # Remove rows from any failed COPY FROM
83
        sql.truncate(db, table)
84
        
85
        def load_():
86
            # Create COPY FROM statement
87
            if use_copy_from[0]:
88
                copy_from = ('COPY '+table.to_str(db)+' ('
89
                    +(', '.join(map(esc_name, col_names)))
90
                    +') FROM STDIN DELIMITER '+db.esc_value(dialect.delimiter)
91
                    +' NULL '+db.esc_value(''))
92
                assert not csvs.is_tsv(dialect)
93
                copy_from += ' CSV'
94
                if dialect.quoting != csv.QUOTE_NONE:
95
                    quote_str = db.esc_value(dialect.quotechar)
96
                    copy_from += ' QUOTE '+quote_str
97
                    if dialect.doublequote: copy_from += ' ESCAPE '+quote_str
98
                copy_from += ';\n'
99
            
100
            # Load the data
101
            line_in = streams.ProgressInputStream(in_, sys.stderr, n=1000)
102
            try:
103
                if use_copy_from[0]:
104
                    log('Using COPY FROM')
105
                    log(copy_from, level=2)
106
                    db.db.cursor().copy_expert(copy_from, line_in)
107
                else:
108
                    log('Using INSERT')
109
                    cols_ct = len(col_names)+1 # +1 for row_num
110
                    for row in csvs.make_reader(line_in, dialect):
111
                        row = map(strings.to_unicode, row)
112
                        row.insert(0, sql.default) # row_num is autogen
113
                        util.list_set_length(row, cols_ct) # truncate extra cols
114
                        sql.insert(db, table, row, cacheable=False, log_level=5)
115
            finally:
116
                line_in.close() # also closes proc.stdout
117
                proc.wait()
118
        sql.with_savepoint(db, load_)
119
        
120
        log('Cleaning up table')
121
        sql_io.cleanup_table(db, table, col_names)
122
        
123
        log('Vacuuming and reanalyzing table')
124
        sql.vacuum(db, table)
125
    
126
    if not errors_table_only:
127
        try: load()
128
        except sql.DatabaseErrors, e:
129
            if use_copy_from[0]: # first try
130
                exc.print_ex(e, plain=True)
131
                use_copy_from[0] = False
132
                load() # try again with different approach
133
            else: raise
134

    
135
main()
(8-8/58)