#! /bin/sh

if [ $# -ne 2 ];
then
  echo Usage: $0 relation database
  exit 1
fi

inherits=`monitor -TN -c "retrieve (inh.relname) from inh in pg_class where pg_class.relname = \"$1\" and pg_class.oid = pg_inherits.inhrel and inh.oid = pg_inherits.inhparent" $2 | awk '{ printf del $1; del= " " }' `

echo $1 inherits from: $inherits

inherited=`monitor -TN -c "retrieve (pg_attribute.attname) where pg_attribute.attrelid = pg_inherits.inhparent and pg_attribute.attnum > 0 and pg_inherits.inhrel = pg_class.oid and pg_class.relname = \"$1\"" $2 | awk '{ printf del $1; del= " " }' `

echo $1 inherits attributes: $inherited

monitor -TN -c "retrieve (pg_attribute.attname, pg_type.typname, pg_attribute.attnum) where pg_type.oid = pg_attribute.atttypid and pg_attribute.attrelid = pg_class.oid and pg_class.relname = \"$1\"" $2 | \
awk '
BEGIN	{ fn= "'$1.schema'"
	  inherits= "'"$inherits"'"
	  inherited= "'"$inherited"'"
	  n_inherits= split(inherits, inherits_a)
	  n_inherited= split(inherited, inherited_a)
	  printf "create '$1' (" > fn
	}
$3 > 0	{ 
	  for (ai= 1; ai <= n_inherited; ai++) {
	    if (inherited_a[ai] == $1)
	      next
	  }
	  printf del $1 "=" $2 > fn
		  del= ","
	}
END	{ printf ")" > fn
	  if (n_inherits > 0) {
	    printf " inherits (" > fn
	    for (i= 1; i <= n_inherits; i++) {
	      printf inherits_a[i] > fn
	      if (i < n_inherits)
		printf "," > fn
	      else
		printf ")" > fn
	    }
	  }
	  printf "\n" > fn
	}
'

monitor -c "copy $1 to \""`pwd`"/$1.copy\"" $2

