Project

General

Profile

1
#!/usr/bin/env python
2
# Loads a command's CSV output stream into a PostgreSQL table.
3
# When no command is specified, just cleans up the specified table.
4
# The command may be run more than once.
5

    
6
import csv
7
import os.path
8
import re
9
import subprocess
10
import sys
11

    
12
sys.path.append(os.path.dirname(__file__)+"/../lib")
13

    
14
import csvs
15
import exc
16
import opts
17
import sql
18
import sql_io
19
import sql_gen
20
import streams
21
import strings
22
import util
23

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

    
129
main()
(10-10/60)