Skip to content

Instantly share code, notes, and snippets.

@subuk
Forked from smintz/SHOW CREATE TABLE REDSHIFT
Last active September 26, 2017 14:57
Show Gist options
  • Select an option

  • Save subuk/deb829ca4b594069fe197322884a270c to your computer and use it in GitHub Desktop.

Select an option

Save subuk/deb829ca4b594069fe197322884a270c to your computer and use it in GitHub Desktop.
#!/bin/bash
#export PGPASSWORD=
#export PGHOST=
#export PGPORT=
#export PGUSER=
#export PGDATABASE=
SCHEMA="$1"
TABLE="$2"
echo "CREATE TABLE ${SCHEMA}.${TABLE} ("
psql -t -c "select (\"column\" || ' ' || type || ' ENCODE ' || encoding || ',' ) from pg_table_def where schemaname='$SCHEMA' and tablename = '$TABLE'" | sed 's/ENCODE none/ENCODE RAW/' | sed '$d' | sed '$ s/,$//'
echo -n ")"
SORTKEY=$(psql -t -c "select \"column\" from pg_table_def where schemaname='$SCHEMA' and tablename = '$TABLE' and sortkey > 0 order by sortkey" | tr "\n" "," | sed 's/\([,]*\)$//')
[ -n "$SORTKEY" ] && echo -n " sortkey ($SORTKEY)"
DESTKEY=$(psql -t -c "select \"column\" from pg_table_def where schemaname='$SCHEMA' and tablename = '$TABLE' and distkey = true" | tr "\n" "," | sed 's/\([,]*\)$//')
[ -n "$DESTKEY" ] && echo -n " distkey ($DESTKEY)"
echo ";"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment