#! /bin/sh

# You first run findoidjoins on the template1 database, and send that
# output into this script to generate a list of SQL statements.

# NOTE: any field that findoidjoins thinks joins to more than one table
# will NOT be checked by the output of this script.  You should be
# suspicious of multiple entries in findoidjoins' output.

# Caution: you may need to use GNU awk.
AWK=${AWK:-awk}

TMP=
TMPA=
TMPB=
trap 'rm -f -- "$TMP" "$TMPA" "$TMPB"' EXIT
trap 'trap - EXIT; rm -f -- "$TMP" "$TMPA" "$TMPB"; exit 1' HUP INT QUIT TERM

TMP=`mktemp -t oidjoins.XXXXXX` || exit 1
TMPA=`mktemp -t oidjoins.a.XXXXXX` || exit 1
TMPB=`mktemp -t oidjoins.b.XXXXXX` || exit 1

# Read input
cat "$@" > $TMP

# Look for fields with multiple references.
cat $TMP | cut -d' ' -f2 | sort | uniq -d > $TMPA
if [ -s $TMPA ] ; then
	echo "Ignoring these fields that link to multiple tables:" 1>&2
	cat $TMPA 1>&2
fi

# Get the non-multiply-referenced fields.
cat $TMP | while read LINE
do
	set -- $LINE
	grep "^$2\$" $TMPA >/dev/null 2>&1 || echo $LINE
done > $TMPB

# Generate the output.
cat $TMPB |
$AWK -F'[ \.]' '\
	BEGIN \
	{
		printf "\
--\n\
-- This is created by pgsql/contrib/findoidjoins/make_oidjoin_check\n\
--\n";
	}
	{
		printf "\
SELECT	ctid, %s \n\
FROM	%s.%s fk \n\
WHERE	%s != 0 AND \n\
	NOT EXISTS(SELECT 1 FROM %s.%s pk WHERE pk.oid = fk.%s);\n",
	$4, $2, $3, $4,
	$6, $7, $4;
	}'

exit 0
