/*-------------------------------------------------------------------------
 *
 * constraint.c
 *	  PostgreSQL CONSTRAINTs support code.
 *
 *-------------------------------------------------------------------------
 */
#include "postgres.h"

#include "access/genam.h"
#include "catalog/index.h"
#include "commands/trigger.h"
#include "executor/executor.h"
#include "executor/tuptable.h"
#include "utils/builtins.h"
#include "utils/memutils.h"


/*
 * unique_key_check - trigger function to do a deferred uniqueness check.
 *
 * This is invoked as an AFTER ROW trigger for both INSERT and UPDATE,
 * for any rows recorded as potentially violating a deferrable unique
 * constraint.
 *
 * This may be an end-of-statement check, a commit-time check, or a
 * check brought about by a SET CONSTRAINTS command.
 */
static void
unique_key_check(PG_FUNCTION_ARGS)
{
	TriggerData	   *trigdata = (TriggerData *) fcinfo->context;
	HeapTuple		new_row;
	Relation		indexRel;
	IndexInfo	   *indexInfo;
	EState		   *estate;
	ExprContext	   *econtext;
	TupleTableSlot *slot;
	Datum			values[INDEX_MAX_KEYS];
	bool			isnull[INDEX_MAX_KEYS];

	/*
	 * Make sure this is being called as an after row trigger.
	 */
	if (!CALLED_AS_TRIGGER(fcinfo))
		/* internal error */
		elog(ERROR,
			 "unique_key_check: not called by trigger manager");

	if (!TRIGGER_FIRED_AFTER(trigdata->tg_event) ||
		!TRIGGER_FIRED_FOR_ROW(trigdata->tg_event))
		/* internal error */
		elog(ERROR,
			 "unique_key_check must be fired AFTER ROW");

	/*
	 * Get the new data that was inserted/updated.
	 */
	if (TRIGGER_FIRED_BY_INSERT(trigdata->tg_event))
	{
		new_row = trigdata->tg_trigtuple;
	}
	else
	{
		if (!TRIGGER_FIRED_BY_UPDATE(trigdata->tg_event))
			/* internal error */
			elog(ERROR,
				 "unique_key_check must be fired for INSERT or UPDATE");

		new_row = trigdata->tg_newtuple;
	}

	/*
	 * Open the unique index, acquiring a RowExclusiveLock, as if we were
	 * going to update it. This does not actually protect us against
	 * concurrent insertions - that is done by the index itself which
	 * acquires a write lock on the target page during the uniqueness check.
	 */
	indexRel = index_open(trigdata->tg_trigger->tgconstrrelid,
						  RowExclusiveLock);
	indexInfo = BuildIndexInfo(indexRel);

	/*
	 * Typically the index won't have expressions, but if it does we need
	 * an EState to evaluate them. Also need a slot for the tuple we are
	 * going to test.
	 */
	if (indexInfo->ii_Expressions != NIL)
	{
		estate = CreateExecutorState();
		econtext = GetPerTupleExprContext(estate);
	}
	else
	{
		estate = NULL;
		econtext = NULL;
	}

	slot = MakeSingleTupleTableSlot(RelationGetDescr(trigdata->tg_relation));

	if (econtext != NULL)
	{
		econtext->ecxt_scantuple = slot;
		MemoryContextReset(econtext->ecxt_per_tuple_memory);
	}

	ExecStoreTuple(new_row, slot, InvalidBuffer, false);

	/*
	 * Form the index values and is null flags for the index entry that
	 * we need to check.
	 */
	FormIndexDatum(indexInfo, slot, estate, values, isnull);

	/*
	 * Now do the uniqueness check. This is not a real insert; it is a
	 * check that the index entry that has already been inserted is
	 * unique.
	 */
	index_insert(indexRel, values, isnull, &(new_row->t_self),
				 trigdata->tg_relation, UNIQUE_CHECK_EXISTING, NULL);

	/*
	 * If that worked, then this index entry is unique, and we are done.
	 */
	ExecDropSingleTupleTableSlot(slot);

	index_close(indexRel, RowExclusiveLock);

	if (estate != NULL)
		FreeExecutorState(estate);
}


/*
 * AFTER INSERT row trigger for a DEFERRABLE unique constraint.
 */
Datum
unique_key_check_ins(PG_FUNCTION_ARGS)
{
	unique_key_check(fcinfo);
	return PointerGetDatum(NULL);
}


/*
 * AFTER UPDATE row trigger for a DEFERRABLE unique constraint.
 */
Datum
unique_key_check_upd(PG_FUNCTION_ARGS)
{
	unique_key_check(fcinfo);
	return PointerGetDatum(NULL);
}
