Project

General

Profile

1 1920 aaronmk
#!/usr/bin/env python
2
# Makes a PostgreSQL CREATE TABLE statement from a CSV header
3
4
import csv
5
import os.path
6
import sys
7
8
sys.path.append(os.path.dirname(__file__)+"/../lib")
9
10
import csvs
11
import opts
12
import sql
13
14
def esc_name(name):
15
    return sql.esc_name_by_engine('PostgreSQL', name, preserve_case=True)
16
17
def main():
18
    # Usage
19
    env_names = []
20
    def usage_err():
21
        raise SystemExit('Usage: '+opts.env_usage(env_names)+' '+sys.argv[0]
22
            +' <header >ddl')
23
24
    # Get config from env vars
25 1922 aaronmk
    schema = opts.get_env_var('schema', None, env_names)
26 1920 aaronmk
    table = opts.get_env_var('table', None, env_names)
27 1922 aaronmk
    if schema == None or table == None: usage_err()
28 1920 aaronmk
29
    # Get col names
30
    reader, col_names = csvs.reader_and_header(sys.stdin)
31
32
    # Write CREATE TABLE statement
33
    out = sys.stdout
34 1922 aaronmk
    out.write('CREATE TABLE '+esc_name(schema)+'.'+esc_name(table)+' (\n')
35 1920 aaronmk
    out.write('row_num serial NOT NULL\n')
36
    for col_name in col_names: out.write(', '+esc_name(col_name)+' text\n')
37
    out.write(');\n')
38
39
main()