#!/bin/bash
#
# (C) 2005 Markus.Schaber@logi-track.com
#
# This file is free software and licensed under the GNU GPL.
#
# Known weaknesses:
# - I'm not shure whether tables and sequences are the only thing that is
#   ignored by pg_dump --schema_only
# - just like pg_dump, it does not dump large objects
# - sequence data is also bzipped, although it is not worth the effort.
#
# $Id: dump_split.sh,v 1.4 2005/01/26 16:16:50 schabi Exp $

if [ -z $2 ];  then 
	echo usage: $0 basename database
	exit
fi

BASENAME=$1
DATABASE=$2

# first dump the schema.
pg_dump -v --schema-only $DATABASE -f ${BASENAME}-schema.sql

# Select "schemaname | tablename" for all non-system tables and sequences.
# Pipe this into an awk skript that outputs the appropriate commands for every
# non-empty line.
# Pipe the result into a shell that executes those commands

psql -q -t -c "SELECT n.nspname as Schema, c.relname as Name FROM pg_catalog.pg_class c LEFT JOIN pg_catalog.pg_namespace n ON n.oid = c.relnamespace WHERE c.relkind IN ('r','S') AND n.nspname NOT IN ('pg_catalog', 'pg_toast','information_schema') ORDER BY 1,2" $DATABASE | awk "\$3  {print \"pg_dump -v --table=\" \$3 \" --schema \" \$1 \" --data-only $DATABASE | bzip2 -9 >$BASENAME.\" \$1 \".\" \$3 \".sql.bz2\" }" | bash