*** ./doc/src/sgml/catalogs.sgml.orig	2009-07-19 14:22:11.000000000 +0100
--- ./doc/src/sgml/catalogs.sgml	2009-07-19 14:25:04.000000000 +0100
***************
*** 4507,4513 ****
        <entry><structfield>tgconstrrelid</structfield></entry>
        <entry><type>oid</type></entry>
        <entry><literal><link linkend="catalog-pg-class"><structname>pg_class</structname></link>.oid</literal></entry>
!       <entry>The table referenced by a referential integrity constraint</entry>
       </row>
  
       <row>
--- 4507,4514 ----
        <entry><structfield>tgconstrrelid</structfield></entry>
        <entry><type>oid</type></entry>
        <entry><literal><link linkend="catalog-pg-class"><structname>pg_class</structname></link>.oid</literal></entry>
!       <entry>The table referenced by a referential integrity constraint,
!       or the index enforcing a deferrable unique constraint.</entry>
       </row>
  
       <row>
*** ./doc/src/sgml/indexam.sgml.orig	2009-07-11 22:37:18.000000000 +0100
--- ./doc/src/sgml/indexam.sgml	2009-07-19 15:12:50.000000000 +0100
***************
*** 172,191 ****
            bool *isnull,
            ItemPointer heap_tid,
            Relation heapRelation,
!           bool check_uniqueness);
  </programlisting>
     Insert a new tuple into an existing index.  The <literal>values</> and
     <literal>isnull</> arrays give the key values to be indexed, and
     <literal>heap_tid</> is the TID to be indexed.
     If the access method supports unique indexes (its
     <structname>pg_am</>.<structfield>amcanunique</> flag is true) then
!    <literal>check_uniqueness</> might be true, in which case the access method
!    must verify that there is no conflicting row; this is the only situation in
!    which the access method normally needs the <literal>heapRelation</>
!    parameter.  See <xref linkend="index-unique-checks"> for details.
!    The result is TRUE if an index entry was inserted, FALSE if not. (A FALSE
!    result does not denote an error condition, but is used for cases such
!    as an index method refusing to index a NULL.)
    </para>
  
    <para>
--- 172,199 ----
            bool *isnull,
            ItemPointer heap_tid,
            Relation heapRelation,
!           IndexUniqueCheck uniqueness_check,
!           bool *is_unique);
  </programlisting>
     Insert a new tuple into an existing index.  The <literal>values</> and
     <literal>isnull</> arrays give the key values to be indexed, and
     <literal>heap_tid</> is the TID to be indexed.
     If the access method supports unique indexes (its
     <structname>pg_am</>.<structfield>amcanunique</> flag is true) then
!    <literal>uniqueness_check</> indicates the type of uniqueness check to
!    perform to verify that there is no conflicting row. The type of uniqueness
!    check varies depending on whether the uniqueness constraint is deferrable;
!    see <xref linkend="index-unique-checks"> for more details. Normally the
!    access method only needs the <literal>heapRelation</> parameter to
!    perform uniqueness checking. If uniqueness is violated, the index
!    method should not insert the index entry, except in the case of a partial
!    uniqueness check. The index method should set <literal>is_unique</> to TRUE
!    if the new entry is definitely unique, and FALSE if it might be non-unique.
!    It should not raise an error for non-unique insert attempts.
!    The method return value should be set to TRUE if an index entry was
!    inserted and FALSE if not. (A FALSE result does not necessarily denote an
!    error condition - it is also used for cases such as an index method
!    refusing to index a NULL.)
    </para>
  
    <para>
***************
*** 706,715 ****
    </para>
  
    <para>
!    Furthermore, immediately before raising a uniqueness violation
     according to the above rules, the access method must recheck the
     liveness of the row being inserted.  If it is committed dead then
!    no error should be raised.  (This case cannot occur during the
     ordinary scenario of inserting a row that's just been created by
     the current transaction.  It can happen during
     <command>CREATE UNIQUE INDEX CONCURRENTLY</>, however.)
--- 714,723 ----
    </para>
  
    <para>
!    Furthermore, immediately before reporting a uniqueness violation
     according to the above rules, the access method must recheck the
     liveness of the row being inserted.  If it is committed dead then
!    no violation should be reported.  (This case cannot occur during the
     ordinary scenario of inserting a row that's just been created by
     the current transaction.  It can happen during
     <command>CREATE UNIQUE INDEX CONCURRENTLY</>, however.)
***************
*** 728,737 ****
    </para>
  
    <para>
!    The main limitation of this scheme is that it has no convenient way
!    to support deferred uniqueness checks.
!   </para>
  
   </sect1>
  
   <sect1 id="index-cost-estimation">
--- 736,803 ----
    </para>
  
    <para>
!    If the unique constraint is deferrable, then the final uniqueness check
!    needs to be done later - either at the end of the statement, or when the
!    transaction is committed, or as part of a <command>SET CONSTRAINTS</>
!    operation. This is handled by passing one of the following enumeration
!    values to the index insert access method:
! 
! <programlisting>
! typedef enum IndexUniqueCheck
! {
!         UNIQUE_CHECK_NO,
!         UNIQUE_CHECK_YES,
!         UNIQUE_CHECK_PARTIAL,
!         UNIQUE_CHECK_EXISTING
! } IndexUniqueCheck;
! </programlisting>
! 
!     <itemizedlist>
!      <listitem>
!       <para>
!        <literal>UNQIUE_CHECK_NO</> indicates that no uniqueness checking
!        need be done (this is not a unique index).
!       </para>
!      </listitem>
!      <listitem>
!       <para>
!        <literal>UNIQUE_CHECK_YES</> indicates that this is a non-deferrable
!        unique index, and the uniqueness check must be done immediately, as
!        described above.
!       </para>
!      </listitem>
!      <listitem>
!       <para>
!        <literal>UNIQUE_CHECK_PARTIAL</> indicates that the uniqueness
!        constraint is deferrable. <productname>PostgreSQL</productname>
!        will use this mode to insert each row's index entry; the access
!        method must allow duplicate entries into the index, and report any
!        potential duplicates by setting <literal>is_unique</> to false. All
!        such rows will then be re-checked later when the deferred constraint
!        check is triggered.
!       </para>
  
+       <para>
+        The access method must identify any rows which might violate the
+        uniqueness constraint, but it is not an error for it to report false
+        positives. This allows the check to be done without waiting for other
+        transactions to finish; conflicts reported here are not treated as
+        errors and will be re-checked later, by which time they may no longer
+        be conflicts.
+       </para>
+      </listitem>
+      <listitem>
+       <para>
+        <literal>UNIQUE_CHECK_EXISTING</> indicates that this is a deferred
+        check of a row which was reported as a potential uniqueness violation.
+        This is only used when a deferred check is triggered (after the index
+        entry has already been inserted). The access method is expected to
+        check the existing entry for uniqueness, without re-inserting it - this
+        is a read-only operation.
+       </para>
+      </listitem>
+     </itemizedlist>
+   </para>
   </sect1>
  
   <sect1 id="index-cost-estimation">
*** ./doc/src/sgml/ref/create_table.sgml.orig	2009-07-11 22:21:03.000000000 +0100
--- ./doc/src/sgml/ref/create_table.sgml	2009-07-11 22:23:01.000000000 +0100
***************
*** 535,541 ****
        deferrable can be postponed until the end of the transaction
        (using the <xref linkend="sql-set-constraints" endterm="sql-set-constraints-title"> command).
        <literal>NOT DEFERRABLE</literal> is the default.  Only foreign
!       key constraints currently accept this clause.  All other
        constraint types are not deferrable.
       </para>
      </listitem>
--- 535,541 ----
        deferrable can be postponed until the end of the transaction
        (using the <xref linkend="sql-set-constraints" endterm="sql-set-constraints-title"> command).
        <literal>NOT DEFERRABLE</literal> is the default.  Only foreign
!       key and unique constraints currently accept this clause.  All other
        constraint types are not deferrable.
       </para>
      </listitem>
*** ./doc/src/sgml/ref/set_constraints.sgml.orig	2009-07-11 22:24:31.000000000 +0100
--- ./doc/src/sgml/ref/set_constraints.sgml	2009-07-11 22:27:37.000000000 +0100
***************
*** 66,73 ****
    </para>
  
    <para>
!    Currently, only foreign key constraints are affected by this
!    setting. Check and unique constraints are always effectively
     not deferrable. Triggers that are declared as <quote>constraint
     triggers</> are also affected.
    </para>
--- 66,73 ----
    </para>
  
    <para>
!    Currently, only foreign key and unique constraints are affected by this
!    setting. Check constraints are always effectively
     not deferrable. Triggers that are declared as <quote>constraint
     triggers</> are also affected.
    </para>
***************
*** 92,98 ****
     This command complies with the behavior defined in the SQL
     standard, except for the limitation that, in
     <productname>PostgreSQL</productname>, it only applies to
!    foreign-key constraints.
    </para>
  
   </refsect1>
--- 92,98 ----
     This command complies with the behavior defined in the SQL
     standard, except for the limitation that, in
     <productname>PostgreSQL</productname>, it only applies to
!    foreign-key and unique constraints.
    </para>
  
   </refsect1>
*** ./src/backend/access/gin/gininsert.c.orig	2009-07-19 10:34:09.000000000 +0100
--- ./src/backend/access/gin/gininsert.c	2009-07-19 10:40:12.000000000 +0100
***************
*** 415,421 ****
  
  #ifdef NOT_USED
  	Relation	heapRel = (Relation) PG_GETARG_POINTER(4);
! 	bool		checkUnique = PG_GETARG_BOOL(5);
  #endif
  	GinState	ginstate;
  	MemoryContext oldCtx;
--- 415,422 ----
  
  #ifdef NOT_USED
  	Relation	heapRel = (Relation) PG_GETARG_POINTER(4);
! 	IndexUniqueCheck	checkUnique = (IndexUniqueCheck) PG_GETARG_INT32(5);
! 	bool	   *is_unique = (bool *) PG_GETARG_POINTER(6);
  #endif
  	GinState	ginstate;
  	MemoryContext oldCtx;
*** ./src/backend/access/gist/gist.c.orig	2009-07-19 10:42:20.000000000 +0100
--- ./src/backend/access/gist/gist.c	2009-07-19 10:42:58.000000000 +0100
***************
*** 225,231 ****
  
  #ifdef NOT_USED
  	Relation	heapRel = (Relation) PG_GETARG_POINTER(4);
! 	bool		checkUnique = PG_GETARG_BOOL(5);
  #endif
  	IndexTuple	itup;
  	GISTSTATE	giststate;
--- 225,232 ----
  
  #ifdef NOT_USED
  	Relation	heapRel = (Relation) PG_GETARG_POINTER(4);
! 	IndexUniqueCheck	checkUnique = (IndexUniqueCheck) PG_GETARG_INT32(5);
! 	bool	   *is_unique = (bool *) PG_GETARG_POINTER(6);
  #endif
  	IndexTuple	itup;
  	GISTSTATE	giststate;
*** ./src/backend/access/hash/hash.c.orig	2009-07-19 10:39:43.000000000 +0100
--- ./src/backend/access/hash/hash.c	2009-07-19 10:41:29.000000000 +0100
***************
*** 165,171 ****
  
  #ifdef NOT_USED
  	Relation	heapRel = (Relation) PG_GETARG_POINTER(4);
! 	bool		checkUnique = PG_GETARG_BOOL(5);
  #endif
  	IndexTuple	itup;
  
--- 165,172 ----
  
  #ifdef NOT_USED
  	Relation	heapRel = (Relation) PG_GETARG_POINTER(4);
! 	IndexUniqueCheck	checkUnique = (IndexUniqueCheck) PG_GETARG_INT32(5);
! 	bool	   *is_unique = (bool *) PG_GETARG_POINTER(6);
  #endif
  	IndexTuple	itup;
  
*** ./src/backend/access/heap/tuptoaster.c.orig	2009-07-22 11:31:43.000000000 +0100
--- ./src/backend/access/heap/tuptoaster.c	2009-07-22 11:31:42.000000000 +0100
***************
*** 1229,1235 ****
  		 */
  		index_insert(toastidx, t_values, t_isnull,
  					 &(toasttup->t_self),
! 					 toastrel, toastidx->rd_index->indisunique);
  
  		/*
  		 * Free memory
--- 1229,1238 ----
  		 */
  		index_insert(toastidx, t_values, t_isnull,
  					 &(toasttup->t_self),
! 					 toastrel,
! 					 toastidx->rd_index->indisunique ?
! 					 UNIQUE_CHECK_YES : UNIQUE_CHECK_NO,
! 					 NULL);
  
  		/*
  		 * Free memory
*** ./src/backend/access/index/indexam.c.orig	2009-07-04 15:43:47.000000000 +0100
--- ./src/backend/access/index/indexam.c	2009-07-18 12:37:35.000000000 +0100
***************
*** 185,193 ****
  			 bool *isnull,
  			 ItemPointer heap_t_ctid,
  			 Relation heapRelation,
! 			 bool check_uniqueness)
  {
  	FmgrInfo   *procedure;
  
  	RELATION_CHECKS;
  	GET_REL_PROCEDURE(aminsert);
--- 185,195 ----
  			 bool *isnull,
  			 ItemPointer heap_t_ctid,
  			 Relation heapRelation,
! 			 IndexUniqueCheck uniqueness_check,
! 			 bool *is_unique)
  {
  	FmgrInfo   *procedure;
+ 	bool		unique_result, result;
  
  	RELATION_CHECKS;
  	GET_REL_PROCEDURE(aminsert);
***************
*** 195,207 ****
  	/*
  	 * have the am's insert proc do all the work.
  	 */
! 	return DatumGetBool(FunctionCall6(procedure,
! 									  PointerGetDatum(indexRelation),
! 									  PointerGetDatum(values),
! 									  PointerGetDatum(isnull),
! 									  PointerGetDatum(heap_t_ctid),
! 									  PointerGetDatum(heapRelation),
! 									  BoolGetDatum(check_uniqueness)));
  }
  
  /*
--- 197,229 ----
  	/*
  	 * have the am's insert proc do all the work.
  	 */
! 	result = DatumGetBool(FunctionCall7(procedure,
! 										PointerGetDatum(indexRelation),
! 										PointerGetDatum(values),
! 										PointerGetDatum(isnull),
! 										PointerGetDatum(heap_t_ctid),
! 										PointerGetDatum(heapRelation),
! 										Int32GetDatum((int32) uniqueness_check),
! 										PointerGetDatum(&unique_result)));
! 
! 	/*
! 	 * check the uniqueness result if necessary. We deliberately
! 	 * allow non-unique entries into the index for a partial check,
! 	 * which is used to support a deferrable unique constraint.
! 	 */
! 	if ( (uniqueness_check == UNIQUE_CHECK_YES ||
! 		  uniqueness_check == UNIQUE_CHECK_EXISTING) && !unique_result )
! 	{
! 		ereport(ERROR,
! 				(errcode(ERRCODE_UNIQUE_VIOLATION),
! 				 errmsg("duplicate key value violates unique constraint \"%s\"",
! 						RelationGetRelationName(indexRelation))));
! 	}
! 
! 	if (is_unique)
! 		*is_unique = unique_result;
! 
! 	return result;
  }
  
  /*
*** ./src/backend/access/nbtree/nbtinsert.c.orig	2009-07-04 15:43:47.000000000 +0100
--- ./src/backend/access/nbtree/nbtinsert.c	2009-07-19 14:39:19.000000000 +0100
***************
*** 50,56 ****
  
  static TransactionId _bt_check_unique(Relation rel, IndexTuple itup,
  				 Relation heapRel, Buffer buf, OffsetNumber ioffset,
! 				 ScanKey itup_scankey);
  static void _bt_findinsertloc(Relation rel,
  				  Buffer *bufptr,
  				  OffsetNumber *offsetptr,
--- 50,57 ----
  
  static TransactionId _bt_check_unique(Relation rel, IndexTuple itup,
  				 Relation heapRel, Buffer buf, OffsetNumber ioffset,
! 				 ScanKey itup_scankey, IndexUniqueCheck unique_check,
! 				 bool *is_unique);
  static void _bt_findinsertloc(Relation rel,
  				  Buffer *bufptr,
  				  OffsetNumber *offsetptr,
***************
*** 85,95 ****
   *
   *		This routine is called by the public interface routines, btbuild
   *		and btinsert.  By here, itup is filled in, including the TID.
   */
! void
  _bt_doinsert(Relation rel, IndexTuple itup,
! 			 bool index_is_unique, Relation heapRel)
  {
  	int			natts = rel->rd_rel->relnatts;
  	ScanKey		itup_scankey;
  	BTStack		stack;
--- 86,107 ----
   *
   *		This routine is called by the public interface routines, btbuild
   *		and btinsert.  By here, itup is filled in, including the TID.
+  *
+  *		If unique_check is UNIQUE_CHECK_NO or UNIQUE_CHECK_PARTIAL, this
+  *		will allow duplicates and set is_unique to false if the entry is
+  *		potentially non-unique.
+  *
+  *		Otherwise (UNIQUE_CHECK_YES or UNIQUE_CHECK_EXISTING) it will not
+  *		allow duplicates. The attempt to insert a duplicate will not raise
+  *		an error, but is_unique will be set the false. The caller is
+  *		expected to check this.
   */
! bool
  _bt_doinsert(Relation rel, IndexTuple itup,
! 			 IndexUniqueCheck unique_check, Relation heapRel,
! 			 bool *is_unique)
  {
+ 	bool		do_insert = unique_check != UNIQUE_CHECK_EXISTING;
  	int			natts = rel->rd_rel->relnatts;
  	ScanKey		itup_scankey;
  	BTStack		stack;
***************
*** 134,165 ****
  	 *
  	 * If we must wait for another xact, we release the lock while waiting,
  	 * and then must start over completely.
  	 */
! 	if (index_is_unique)
  	{
  		TransactionId xwait;
  
  		offset = _bt_binsrch(rel, buf, natts, itup_scankey, false);
! 		xwait = _bt_check_unique(rel, itup, heapRel, buf, offset, itup_scankey);
  
! 		if (TransactionIdIsValid(xwait))
  		{
! 			/* Have to wait for the other guy ... */
! 			_bt_relbuf(rel, buf);
! 			XactLockTableWait(xwait);
! 			/* start over... */
! 			_bt_freestack(stack);
! 			goto top;
  		}
  	}
  
! 	/* do the insertion */
! 	_bt_findinsertloc(rel, &buf, &offset, natts, itup_scankey, itup);
! 	_bt_insertonpg(rel, buf, stack, itup, offset, false);
  
  	/* be tidy */
  	_bt_freestack(stack);
  	_bt_freeskey(itup_scankey);
  }
  
  /*
--- 146,205 ----
  	 *
  	 * If we must wait for another xact, we release the lock while waiting,
  	 * and then must start over completely.
+ 	 *
+ 	 * For a partial uniqueness check, don't wait for the other xact. Just let
+ 	 * the tuple in and return false for possibly non-unique, or true for
+ 	 * definitely unique.
  	 */
! 	if (unique_check != UNIQUE_CHECK_NO)
  	{
  		TransactionId xwait;
  
  		offset = _bt_binsrch(rel, buf, natts, itup_scankey, false);
! 		xwait = _bt_check_unique(rel, itup, heapRel, buf, offset, itup_scankey,
! 								 unique_check, is_unique);
  
! 		if (!*is_unique)
  		{
! 			if (TransactionIdIsValid(xwait))
! 			{
! 				/* Have to wait for the other guy ... */
! 				_bt_relbuf(rel, buf);
! 				XactLockTableWait(xwait);
! 				/* start over... */
! 				_bt_freestack(stack);
! 				goto top;
! 			}
! 
! 			/*
! 			 * If we only did a partial uniqueness check, then this is
! 			 * only a potential conflict; let the entry in. Otherwise
! 			 * it is a real conflict, so don't add it to the index.
! 			 */
! 			if (unique_check != UNIQUE_CHECK_PARTIAL)
! 				do_insert = false;
  		}
  	}
+ 	else
+ 		*is_unique = false;
  
! 	if (do_insert)
! 	{
! 		/* do the insertion */
! 		_bt_findinsertloc(rel, &buf, &offset, natts, itup_scankey, itup);
! 		_bt_insertonpg(rel, buf, stack, itup, offset, false);
! 	}
! 	else
! 	{
! 		/* just release the buffer */
! 		_bt_relbuf(rel, buf);
! 	}
  
  	/* be tidy */
  	_bt_freestack(stack);
  	_bt_freeskey(itup_scankey);
+ 
+ 	return do_insert;
  }
  
  /*
***************
*** 169,182 ****
   * also point to end-of-page, which means that the first tuple to check
   * is the first tuple on the next page.
   *
!  * Returns InvalidTransactionId if there is no conflict, else an xact ID
!  * we must wait for to see if it commits a conflicting tuple.	If an actual
!  * conflict is detected, no return --- just ereport().
   */
  static TransactionId
  _bt_check_unique(Relation rel, IndexTuple itup, Relation heapRel,
! 				 Buffer buf, OffsetNumber offset, ScanKey itup_scankey)
  {
  	TupleDesc	itupdesc = RelationGetDescr(rel);
  	int			natts = rel->rd_rel->relnatts;
  	SnapshotData SnapshotDirty;
--- 209,230 ----
   * also point to end-of-page, which means that the first tuple to check
   * is the first tuple on the next page.
   *
!  * This only sets is_unique to true if the entry is definitely unique.
!  * Otherwise the entry is a definite or potential conflict, and the
!  * return value is the xact ID we have to wait on to find out for sure.
!  *
!  * The return value will be InvalidTransactionId if the entry is
!  * definitely unique or non-unique, or if we are only doing a partial
!  * check. For a partial unique check, _bt_doinsert() will not block,
!  * but just go ahead with the insert. The proper check will be done later
!  * (at the end of the statement or transaction).
   */
  static TransactionId
  _bt_check_unique(Relation rel, IndexTuple itup, Relation heapRel,
! 				 Buffer buf, OffsetNumber offset, ScanKey itup_scankey,
! 				 IndexUniqueCheck unique_check, bool *is_unique)
  {
+ 	TransactionId xwait = InvalidTransactionId;
  	TupleDesc	itupdesc = RelationGetDescr(rel);
  	int			natts = rel->rd_rel->relnatts;
  	SnapshotData SnapshotDirty;
***************
*** 184,189 ****
--- 232,238 ----
  	Page		page;
  	BTPageOpaque opaque;
  	Buffer		nbuf = InvalidBuffer;
+ 	bool		found = false;
  
  	InitDirtySnapshot(SnapshotDirty);
  
***************
*** 191,196 ****
--- 240,248 ----
  	opaque = (BTPageOpaque) PageGetSpecialPointer(page);
  	maxoff = PageGetMaxOffsetNumber(page);
  
+ 	/* Assume unique unless we find a duplicate */
+ 	*is_unique = true;
+ 
  	/*
  	 * Scan over all equal tuples, looking for live conflicts.
  	 */
***************
*** 247,263 ****
  				 */
  				if (heap_hot_search(&htid, heapRel, &SnapshotDirty, &all_dead))
  				{
! 					/* it is a duplicate */
! 					TransactionId xwait =
! 					(TransactionIdIsValid(SnapshotDirty.xmin)) ?
! 					SnapshotDirty.xmin : SnapshotDirty.xmax;
  
  					/*
! 					 * If this tuple is being updated by other transaction
! 					 * then we have to wait for its commit/abort.
  					 */
! 					if (TransactionIdIsValid(xwait))
  					{
  						if (nbuf != InvalidBuffer)
  							_bt_relbuf(rel, nbuf);
  						/* Tell _bt_doinsert to wait... */
--- 299,353 ----
  				 */
  				if (heap_hot_search(&htid, heapRel, &SnapshotDirty, &all_dead))
  				{
! 					/*
! 					 * We have a duplicate. If we are only doing a partial
! 					 * check, then don't bother checking if the tuple is
! 					 * being updated in another transaction. Just return
! 					 * the fact that it is a potential conflict and leave
! 					 * the full check till later. This is used for deferrable
! 					 * unique constraints.
! 					 */
! 					if (unique_check == UNIQUE_CHECK_PARTIAL)
! 					{
! 						*is_unique = false;
! 						if (nbuf != InvalidBuffer)
! 							_bt_relbuf(rel, nbuf);
! 						return InvalidTransactionId;
! 					}
  
  					/*
! 					 * Otherwise we need to do a proper check to see if
! 					 * it really is a duplicate. First check if it is
! 					 * being updated by another transaction, in which case
! 					 * we may have to wait for it's commit/abort.
  					 */
! 					if (TransactionIdIsValid(SnapshotDirty.xmin) ||
! 						TransactionIdIsValid(SnapshotDirty.xmax))
  					{
+ 						xwait = TransactionIdIsValid(SnapshotDirty.xmin) ?
+ 								SnapshotDirty.xmin : SnapshotDirty.xmax;
+ 
+ 						/*
+ 						 * If this is a deferred uniqueness check, of a
+ 						 * tuple that we have already inserted, then there
+ 						 * may be other conflicting tuples which we can
+ 						 * see without waiting, so reset the snapshot and
+ 						 * keep looking, but remember that we may need to
+ 						 * wait on this one after all.
+ 						 */
+ 						if (unique_check == UNIQUE_CHECK_EXISTING)
+ 						{
+ 							SnapshotDirty.xmin = InvalidTransactionId;
+ 							SnapshotDirty.xmax = InvalidTransactionId;
+ 
+ 							goto next_tuple;
+ 						}
+ 
+ 						/*
+ 						 * Otherwise return the other transaction ID
+ 						 * that we have to wait for.
+ 						 */
+ 						*is_unique = false;
  						if (nbuf != InvalidBuffer)
  							_bt_relbuf(rel, nbuf);
  						/* Tell _bt_doinsert to wait... */
***************
*** 265,271 ****
  					}
  
  					/*
! 					 * Otherwise we have a definite conflict.  But before
  					 * complaining, look to see if the tuple we want to insert
  					 * is itself now committed dead --- if so, don't complain.
  					 * This is a waste of time in normal scenarios but we must
--- 355,361 ----
  					}
  
  					/*
! 					 * This appears to be a definite conflict.  But before
  					 * complaining, look to see if the tuple we want to insert
  					 * is itself now committed dead --- if so, don't complain.
  					 * This is a waste of time in normal scenarios but we must
***************
*** 289,304 ****
  					else
  					{
  						/*
! 						 * It's been deleted, so no error, and no need to
! 						 * continue searching
  						 */
  						break;
  					}
  
! 					ereport(ERROR,
! 							(errcode(ERRCODE_UNIQUE_VIOLATION),
! 							 errmsg("duplicate key value violates unique constraint \"%s\"",
! 									RelationGetRelationName(rel))));
  				}
  				else if (all_dead)
  				{
--- 379,415 ----
  					else
  					{
  						/*
! 						 * It's been deleted, so no error. If this is a
! 						 * deferred check, there may be other duplicates which
! 						 * are live.
  						 */
+ 						if (unique_check == UNIQUE_CHECK_EXISTING)
+ 							goto next_tuple;
+ 
+ 						/* Otherwise, no need to continue searching */
  						break;
  					}
  
! 					/*
! 					 * We have a definite match. If this is a deferred check,
! 					 * of a tuple that we have already inserted, the first
! 					 * match is not a conflict, so look for another. This
! 					 * is used for the final check of a deferrable uniquenes
! 					 * constraint.
! 					 */
! 					if (unique_check == UNIQUE_CHECK_EXISTING && !found)
! 					{
! 						found = true;
! 						goto next_tuple;
! 					}
! 
! 					/*
! 					 * This is a definite conflict.
! 					 */
! 					*is_unique = false;
! 					if (nbuf != InvalidBuffer)
! 						_bt_relbuf(rel, nbuf);
! 					return InvalidTransactionId;
  				}
  				else if (all_dead)
  				{
***************
*** 318,323 ****
--- 429,435 ----
  			}
  		}
  
+ next_tuple:
  		/*
  		 * Advance to next tuple to continue checking.
  		 */
***************
*** 352,357 ****
--- 464,481 ----
  	if (nbuf != InvalidBuffer)
  		_bt_relbuf(rel, nbuf);
  
+ 	/*
+ 	 * If we reach here, then we didn't find a duplicate. However, in a
+ 	 * deferred uniqueness check, we may have found 1 visible tuple plus
+ 	 * another being updated in another transaction, in which case we need
+ 	 * to wait for it's commit/abort.
+ 	 */
+ 	if (found && TransactionIdIsValid(xwait))
+ 	{
+ 		*is_unique = false;
+ 		return xwait;
+ 	}
+ 
  	return InvalidTransactionId;
  }
  
*** ./src/backend/access/nbtree/nbtree.c.orig	2009-07-04 15:43:47.000000000 +0100
--- ./src/backend/access/nbtree/nbtree.c	2009-07-18 11:29:54.000000000 +0100
***************
*** 212,234 ****
  Datum
  btinsert(PG_FUNCTION_ARGS)
  {
! 	Relation	rel = (Relation) PG_GETARG_POINTER(0);
! 	Datum	   *values = (Datum *) PG_GETARG_POINTER(1);
! 	bool	   *isnull = (bool *) PG_GETARG_POINTER(2);
! 	ItemPointer ht_ctid = (ItemPointer) PG_GETARG_POINTER(3);
! 	Relation	heapRel = (Relation) PG_GETARG_POINTER(4);
! 	bool		checkUnique = PG_GETARG_BOOL(5);
! 	IndexTuple	itup;
  
  	/* generate an index tuple */
  	itup = index_form_tuple(RelationGetDescr(rel), values, isnull);
  	itup->t_tid = *ht_ctid;
  
! 	_bt_doinsert(rel, itup, checkUnique, heapRel);
  
  	pfree(itup);
  
! 	PG_RETURN_BOOL(true);
  }
  
  /*
--- 212,236 ----
  Datum
  btinsert(PG_FUNCTION_ARGS)
  {
! 	Relation			rel = (Relation) PG_GETARG_POINTER(0);
! 	Datum			   *values = (Datum *) PG_GETARG_POINTER(1);
! 	bool			   *isnull = (bool *) PG_GETARG_POINTER(2);
! 	ItemPointer 		ht_ctid = (ItemPointer) PG_GETARG_POINTER(3);
! 	Relation			heapRel = (Relation) PG_GETARG_POINTER(4);
! 	IndexUniqueCheck	checkUnique = (IndexUniqueCheck) PG_GETARG_INT32(5);
! 	bool			   *is_unique = (bool *) PG_GETARG_POINTER(6);
! 	IndexTuple			itup;
! 	bool				ok;
  
  	/* generate an index tuple */
  	itup = index_form_tuple(RelationGetDescr(rel), values, isnull);
  	itup->t_tid = *ht_ctid;
  
! 	ok = _bt_doinsert(rel, itup, checkUnique, heapRel, is_unique);
  
  	pfree(itup);
  
! 	PG_RETURN_BOOL(ok);
  }
  
  /*
*** ./src/backend/bootstrap/bootparse.y.orig	2009-07-04 15:43:47.000000000 +0100
--- ./src/backend/bootstrap/bootparse.y	2009-07-04 16:54:25.000000000 +0100
***************
*** 266,272 ****
  								NULL,
  								$10,
  								NULL, NIL,
! 								false, false, false,
  								false, false, true, false, false);
  					do_end();
  				}
--- 266,272 ----
  								NULL,
  								$10,
  								NULL, NIL,
! 								false, false, false, false, false,
  								false, false, true, false, false);
  					do_end();
  				}
***************
*** 284,290 ****
  								NULL,
  								$11,
  								NULL, NIL,
! 								true, false, false,
  								false, false, true, false, false);
  					do_end();
  				}
--- 284,290 ----
  								NULL,
  								$11,
  								NULL, NIL,
! 								true, false, false, false, false,
  								false, false, true, false, false);
  					do_end();
  				}
*** ./src/backend/catalog/index.c.orig	2009-07-04 15:43:47.000000000 +0100
--- ./src/backend/catalog/index.c	2009-07-19 10:30:37.000000000 +0100
***************
*** 40,53 ****
--- 40,58 ----
  #include "catalog/pg_operator.h"
  #include "catalog/pg_opclass.h"
  #include "catalog/pg_tablespace.h"
+ #include "catalog/pg_trigger.h"
  #include "catalog/pg_type.h"
  #include "catalog/storage.h"
  #include "commands/tablecmds.h"
+ #include "commands/trigger.h"
  #include "executor/executor.h"
  #include "miscadmin.h"
+ #include "nodes/makefuncs.h"
  #include "nodes/nodeFuncs.h"
  #include "optimizer/clauses.h"
  #include "optimizer/var.h"
+ #include "parser/gramparse.h"
+ #include "parser/parser.h"
  #include "storage/bufmgr.h"
  #include "storage/lmgr.h"
  #include "storage/procarray.h"
***************
*** 726,733 ****
  			conOid = CreateConstraintEntry(indexRelationName,
  										   namespaceId,
  										   constraintType,
! 										   false,		/* isDeferrable */
! 										   false,		/* isDeferred */
  										   heapRelationId,
  										   indexInfo->ii_KeyAttrNumbers,
  										   indexInfo->ii_NumIndexAttrs,
--- 731,738 ----
  			conOid = CreateConstraintEntry(indexRelationName,
  										   namespaceId,
  										   constraintType,
! 										   indexInfo->ii_Deferrable,
! 										   indexInfo->ii_InitDeferred,
  										   heapRelationId,
  										   indexInfo->ii_KeyAttrNumbers,
  										   indexInfo->ii_NumIndexAttrs,
***************
*** 753,758 ****
--- 758,808 ----
  			referenced.objectSubId = 0;
  
  			recordDependencyOn(&myself, &referenced, DEPENDENCY_INTERNAL);
+ 
+ 			/*
+ 			 * If the constraint is deferrable, define the deferred uniqueness
+ 			 * checking triggers. The index will temporarily allow duplicates and
+ 			 * then these triggers will re-check for duplicates at the end of the
+ 			 * statement or transaction. These triggers are only queued if
+ 			 * potentially non-unique entries are detected during index insertion.
+ 			 */
+ 			if (indexInfo->ii_Deferrable)
+ 			{
+ 				char *nsname = get_namespace_name(namespaceId);
+ 				RangeVar *heapRel = makeRangeVar(nsname, pstrdup(RelationGetRelationName(heapRelation)), -1);
+ 				RangeVar *indexRel = makeRangeVar(nsname, pstrdup(indexRelationName), -1);
+ 				CreateTrigStmt *trigger;
+ 
+ 				/*
+ 				 * Advance the command counter so that we can see the
+ 				 * newly-entered catalog tuples for the index.
+ 				 */
+ 				CommandCounterIncrement();
+ 
+ 				trigger = makeNode(CreateTrigStmt);
+ 				trigger->trigname = pstrdup(indexRelationName);
+ 				trigger->relation = heapRel;
+ 				trigger->funcname = SystemFuncName("unique_key_check_ins");
+ 				trigger->args = NIL;
+ 				trigger->before = false;
+ 				trigger->row = true;
+ 				trigger->events = TRIGGER_TYPE_INSERT;
+ 				trigger->isconstraint = true;
+ 				trigger->deferrable = true;
+ 				trigger->initdeferred = indexInfo->ii_InitDeferred;
+ 				trigger->constrrel = indexRel;
+ 
+ 				(void) CreateTrigger(trigger, conOid, false);
+ 
+ 				CommandCounterIncrement();
+ 
+ 				trigger->funcname = SystemFuncName("unique_key_check_upd");
+ 				trigger->events = TRIGGER_TYPE_UPDATE;
+ 
+ 				(void) CreateTrigger(trigger, conOid, false);
+ 
+ 				CommandCounterIncrement();
+ 			}
  		}
  		else
  		{
***************
*** 1026,1031 ****
--- 1076,1105 ----
  	ii->ii_Concurrent = false;
  	ii->ii_BrokenHotChain = false;
  
+ 	/* fetch the details of the index constraint if any */
+ 	ii->ii_ConstraintId = get_index_constraint(RelationGetRelid(index));
+ 	if (OidIsValid(ii->ii_ConstraintId))
+ 	{
+ 		HeapTuple ht_constr = SearchSysCache(CONSTROID,
+ 											 ObjectIdGetDatum(ii->ii_ConstraintId),
+ 											 0, 0, 0);
+ 		Form_pg_constraint conrec;
+ 
+ 		if (!HeapTupleIsValid(ht_constr))
+ 			elog(ERROR, "cache lookup failed for constraint %u", ii->ii_ConstraintId);
+ 		conrec = (Form_pg_constraint) GETSTRUCT(ht_constr);
+ 
+ 		ii->ii_Deferrable = conrec->condeferrable;
+ 		ii->ii_InitDeferred = conrec->condeferred;
+ 
+ 		ReleaseSysCache(ht_constr);
+ 	}
+ 	else
+ 	{
+ 		ii->ii_Deferrable = false;
+ 		ii->ii_InitDeferred = false;
+ 	}
+ 
  	return ii;
  }
  
***************
*** 2190,2196 ****
  						 isnull,
  						 &rootTuple,
  						 heapRelation,
! 						 indexInfo->ii_Unique);
  
  			state->tups_inserted += 1;
  		}
--- 2264,2272 ----
  						 isnull,
  						 &rootTuple,
  						 heapRelation,
! 						 indexInfo->ii_Unique ?
! 						 UNIQUE_CHECK_YES : UNIQUE_CHECK_NO,
! 						 NULL);
  
  			state->tups_inserted += 1;
  		}
*** ./src/backend/catalog/indexing.c.orig	2009-07-04 15:43:47.000000000 +0100
--- ./src/backend/catalog/indexing.c	2009-07-18 12:01:58.000000000 +0100
***************
*** 134,140 ****
  					 isnull,	/* is-null flags */
  					 &(heapTuple->t_self),		/* tid of heap tuple */
  					 heapRelation,
! 					 relationDescs[i]->rd_index->indisunique);
  	}
  
  	ExecDropSingleTupleTableSlot(slot);
--- 134,142 ----
  					 isnull,	/* is-null flags */
  					 &(heapTuple->t_self),		/* tid of heap tuple */
  					 heapRelation,
! 					 relationDescs[i]->rd_index->indisunique ?
! 					 UNIQUE_CHECK_YES : UNIQUE_CHECK_NO,
! 					 NULL);
  	}
  
  	ExecDropSingleTupleTableSlot(slot);
*** ./src/backend/catalog/sql_features.txt.orig	2009-07-11 23:37:21.000000000 +0100
--- ./src/backend/catalog/sql_features.txt	2009-07-11 23:38:32.000000000 +0100
***************
*** 289,295 ****
  F696	Additional translation documentation			NO	
  F701	Referential update actions			YES	
  F711	ALTER domain			YES	
! F721	Deferrable constraints			NO	foreign keys only
  F731	INSERT column privileges			YES	
  F741	Referential MATCH types			NO	no partial match yet
  F751	View CHECK enhancements			NO	
--- 289,295 ----
  F696	Additional translation documentation			NO	
  F701	Referential update actions			YES	
  F711	ALTER domain			YES	
! F721	Deferrable constraints			NO	foreign and unique keys only
  F731	INSERT column privileges			YES	
  F741	Referential MATCH types			NO	no partial match yet
  F751	View CHECK enhancements			NO	
*** ./src/backend/catalog/toasting.c.orig	2009-07-04 15:43:47.000000000 +0100
--- ./src/backend/catalog/toasting.c	2009-07-04 16:56:10.000000000 +0100
***************
*** 241,246 ****
--- 241,249 ----
  	indexInfo->ii_ReadyForInserts = true;
  	indexInfo->ii_Concurrent = false;
  	indexInfo->ii_BrokenHotChain = false;
+ 	indexInfo->ii_ConstraintId = InvalidOid;
+ 	indexInfo->ii_Deferrable = false;
+ 	indexInfo->ii_InitDeferred = false;
  
  	classObjectId[0] = OID_BTREE_OPS_OID;
  	classObjectId[1] = INT4_BTREE_OPS_OID;
*** ./src/backend/commands/copy.c.orig	2009-07-04 15:44:36.000000000 +0100
--- ./src/backend/commands/copy.c	2009-07-04 18:15:59.000000000 +0100
***************
*** 2119,2124 ****
--- 2119,2126 ----
  
  		if (!skip_tuple)
  		{
+ 			List *problemIndexList = NIL;
+ 
  			/* Place tuple in tuple slot */
  			ExecStoreTuple(tuple, slot, InvalidBuffer, false);
  
***************
*** 2130,2139 ****
  			heap_insert(cstate->rel, tuple, mycid, hi_options, bistate);
  
  			if (resultRelInfo->ri_NumIndices > 0)
! 				ExecInsertIndexTuples(slot, &(tuple->t_self), estate, false);
  
  			/* AFTER ROW INSERT Triggers */
! 			ExecARInsertTriggers(estate, resultRelInfo, tuple);
  
  			/*
  			 * We count only tuples not suppressed by a BEFORE INSERT trigger;
--- 2132,2141 ----
  			heap_insert(cstate->rel, tuple, mycid, hi_options, bistate);
  
  			if (resultRelInfo->ri_NumIndices > 0)
! 				problemIndexList = ExecInsertIndexTuples(slot, &(tuple->t_self), estate, false);
  
  			/* AFTER ROW INSERT Triggers */
! 			ExecARInsertTriggers(estate, resultRelInfo, tuple, problemIndexList);
  
  			/*
  			 * We count only tuples not suppressed by a BEFORE INSERT trigger;
*** ./src/backend/commands/indexcmds.c.orig	2009-07-19 09:02:44.000000000 +0100
--- ./src/backend/commands/indexcmds.c	2009-07-19 08:54:46.000000000 +0100
***************
*** 87,92 ****
--- 87,94 ----
   * 'primary': mark the index as a primary key in the catalogs.
   * 'isconstraint': index is for a PRIMARY KEY or UNIQUE constraint,
   *		so build a pg_constraint entry for it.
+  * 'constrDeferrable': constraint is DEFERRABLE (UNIQUE constraint).
+  * 'constrInitDeferred': constraint is INITIALLY DEFERRED (UNIQUE constraint).
   * 'is_alter_table': this is due to an ALTER rather than a CREATE operation.
   * 'check_rights': check for CREATE rights in the namespace.  (This should
   *		be true except when ALTER is deleting/recreating an index.)
***************
*** 107,112 ****
--- 109,116 ----
  			bool unique,
  			bool primary,
  			bool isconstraint,
+ 			bool constrDeferrable,
+ 			bool constrInitDeferred,
  			bool is_alter_table,
  			bool check_rights,
  			bool skip_build,
***************
*** 419,424 ****
--- 423,431 ----
  	indexInfo->ii_ReadyForInserts = !concurrent;
  	indexInfo->ii_Concurrent = concurrent;
  	indexInfo->ii_BrokenHotChain = false;
+ 	indexInfo->ii_ConstraintId = InvalidOid; /* index_create() may create this */
+ 	indexInfo->ii_Deferrable = constrDeferrable;
+ 	indexInfo->ii_InitDeferred = constrInitDeferred;
  
  	classObjectId = (Oid *) palloc(numberOfAttributes * sizeof(Oid));
  	coloptions = (int16 *) palloc(numberOfAttributes * sizeof(int16));
*** ./src/backend/commands/Makefile.orig	2009-07-22 10:31:21.000000000 +0100
--- ./src/backend/commands/Makefile	2009-07-22 10:33:15.000000000 +0100
***************
*** 13,19 ****
  include $(top_builddir)/src/Makefile.global
  
  OBJS = aggregatecmds.o alter.o analyze.o async.o cluster.o comment.o  \
! 	conversioncmds.o copy.o \
  	dbcommands.o define.o discard.o explain.o foreigncmds.o functioncmds.o \
  	indexcmds.o lockcmds.o operatorcmds.o opclasscmds.o \
  	portalcmds.o prepare.o proclang.o \
--- 13,19 ----
  include $(top_builddir)/src/Makefile.global
  
  OBJS = aggregatecmds.o alter.o analyze.o async.o cluster.o comment.o  \
! 	constraint.o conversioncmds.o copy.o \
  	dbcommands.o define.o discard.o explain.o foreigncmds.o functioncmds.o \
  	indexcmds.o lockcmds.o operatorcmds.o opclasscmds.o \
  	portalcmds.o prepare.o proclang.o \
*** ./src/backend/commands/tablecmds.c.orig	2009-07-22 11:33:37.000000000 +0100
--- ./src/backend/commands/tablecmds.c	2009-07-22 11:33:36.000000000 +0100
***************
*** 4388,4393 ****
--- 4388,4395 ----
  				stmt->unique,
  				stmt->primary,
  				stmt->isconstraint,
+ 				stmt->constrDeferrable,
+ 				stmt->constrInitDeferred,
  				true,			/* is_alter_table */
  				check_rights,
  				skip_build,
*** ./src/backend/commands/trigger.c.orig	2009-07-04 15:44:36.000000000 +0100
--- ./src/backend/commands/trigger.c	2009-07-22 11:26:45.000000000 +0100
***************
*** 63,69 ****
  					Instrumentation *instr,
  					MemoryContext per_tuple_context);
  static void AfterTriggerSaveEvent(ResultRelInfo *relinfo, int event,
! 					  bool row_trigger, HeapTuple oldtup, HeapTuple newtup);
  
  
  /*
--- 63,70 ----
  					Instrumentation *instr,
  					MemoryContext per_tuple_context);
  static void AfterTriggerSaveEvent(ResultRelInfo *relinfo, int event,
! 					  bool row_trigger, HeapTuple oldtup, HeapTuple newtup,
! 					  List *problemIndexList);
  
  
  /*
***************
*** 211,224 ****
  	trigoid = GetNewOid(tgrel);
  
  	/*
! 	 * If trigger is for an RI constraint, the passed-in name is the
! 	 * constraint name; save that and build a unique trigger name to avoid
! 	 * collisions with user-selected trigger names.
  	 */
  	if (OidIsValid(constraintOid))
  	{
  		snprintf(constrtrigname, sizeof(constrtrigname),
! 				 "RI_ConstraintTrigger_%u", trigoid);
  		trigname = constrtrigname;
  		constrname = stmt->trigname;
  	}
--- 212,258 ----
  	trigoid = GetNewOid(tgrel);
  
  	/*
! 	 * If trigger is for a constraint, the passed-in name is the constraint
! 	 * name; save that and build a unique trigger name based on the type of
! 	 * the constraint to avoid collisions with user-selected trigger names.
  	 */
  	if (OidIsValid(constraintOid))
  	{
+ 		HeapTuple ht_constr = SearchSysCache(CONSTROID,
+ 											 ObjectIdGetDatum(constraintOid),
+ 											 0, 0, 0);
+ 		Form_pg_constraint conrec;
+ 		char *prefix;
+ 
+ 		if (!HeapTupleIsValid(ht_constr))
+ 			elog(ERROR, "cache lookup failed for constraint %u", constraintOid);
+ 		conrec = (Form_pg_constraint) GETSTRUCT(ht_constr);
+ 
+ 		/*
+ 		 * Prefix for trigger name, based on constraint type.
+ 		 */
+ 		switch (conrec->contype)
+ 		{
+ 			case CONSTRAINT_CHECK:
+ 				prefix = "Check_ConstraintTrigger";
+ 				break;
+ 			case CONSTRAINT_FOREIGN:
+ 				prefix = "RI_ConstraintTrigger";
+ 				break;
+ 			case CONSTRAINT_PRIMARY:
+ 				prefix = "PK_ConstraintTrigger";
+ 				break;
+ 			case CONSTRAINT_UNIQUE:
+ 				prefix = "Unique_ConstraintTrigger";
+ 				break;
+ 			default:
+ 				prefix = "ConstraintTrigger";
+ 				break;
+ 		}
+ 		ReleaseSysCache(ht_constr);
+ 
  		snprintf(constrtrigname, sizeof(constrtrigname),
! 				 "%s_%u", prefix, trigoid);
  		trigname = constrtrigname;
  		constrname = stmt->trigname;
  	}
***************
*** 1639,1645 ****
  
  	if (trigdesc && trigdesc->n_after_statement[TRIGGER_EVENT_INSERT] > 0)
  		AfterTriggerSaveEvent(relinfo, TRIGGER_EVENT_INSERT,
! 							  false, NULL, NULL);
  }
  
  HeapTuple
--- 1673,1679 ----
  
  	if (trigdesc && trigdesc->n_after_statement[TRIGGER_EVENT_INSERT] > 0)
  		AfterTriggerSaveEvent(relinfo, TRIGGER_EVENT_INSERT,
! 							  false, NULL, NULL, NIL);
  }
  
  HeapTuple
***************
*** 1695,1707 ****
  
  void
  ExecARInsertTriggers(EState *estate, ResultRelInfo *relinfo,
! 					 HeapTuple trigtuple)
  {
  	TriggerDesc *trigdesc = relinfo->ri_TrigDesc;
  
  	if (trigdesc && trigdesc->n_after_row[TRIGGER_EVENT_INSERT] > 0)
  		AfterTriggerSaveEvent(relinfo, TRIGGER_EVENT_INSERT,
! 							  true, NULL, trigtuple);
  }
  
  void
--- 1729,1741 ----
  
  void
  ExecARInsertTriggers(EState *estate, ResultRelInfo *relinfo,
! 					 HeapTuple trigtuple, List *problemIndexList)
  {
  	TriggerDesc *trigdesc = relinfo->ri_TrigDesc;
  
  	if (trigdesc && trigdesc->n_after_row[TRIGGER_EVENT_INSERT] > 0)
  		AfterTriggerSaveEvent(relinfo, TRIGGER_EVENT_INSERT,
! 							  true, NULL, trigtuple, problemIndexList);
  }
  
  void
***************
*** 1770,1776 ****
  
  	if (trigdesc && trigdesc->n_after_statement[TRIGGER_EVENT_DELETE] > 0)
  		AfterTriggerSaveEvent(relinfo, TRIGGER_EVENT_DELETE,
! 							  false, NULL, NULL);
  }
  
  bool
--- 1804,1810 ----
  
  	if (trigdesc && trigdesc->n_after_statement[TRIGGER_EVENT_DELETE] > 0)
  		AfterTriggerSaveEvent(relinfo, TRIGGER_EVENT_DELETE,
! 							  false, NULL, NULL, NIL);
  }
  
  bool
***************
*** 1847,1853 ****
  												   tupleid, NULL);
  
  		AfterTriggerSaveEvent(relinfo, TRIGGER_EVENT_DELETE,
! 							  true, trigtuple, NULL);
  		heap_freetuple(trigtuple);
  	}
  }
--- 1881,1887 ----
  												   tupleid, NULL);
  
  		AfterTriggerSaveEvent(relinfo, TRIGGER_EVENT_DELETE,
! 							  true, trigtuple, NULL, NIL);
  		heap_freetuple(trigtuple);
  	}
  }
***************
*** 1918,1924 ****
  
  	if (trigdesc && trigdesc->n_after_statement[TRIGGER_EVENT_UPDATE] > 0)
  		AfterTriggerSaveEvent(relinfo, TRIGGER_EVENT_UPDATE,
! 							  false, NULL, NULL);
  }
  
  HeapTuple
--- 1952,1958 ----
  
  	if (trigdesc && trigdesc->n_after_statement[TRIGGER_EVENT_UPDATE] > 0)
  		AfterTriggerSaveEvent(relinfo, TRIGGER_EVENT_UPDATE,
! 							  false, NULL, NULL, NIL);
  }
  
  HeapTuple
***************
*** 1988,1994 ****
  
  void
  ExecARUpdateTriggers(EState *estate, ResultRelInfo *relinfo,
! 					 ItemPointer tupleid, HeapTuple newtuple)
  {
  	TriggerDesc *trigdesc = relinfo->ri_TrigDesc;
  
--- 2022,2029 ----
  
  void
  ExecARUpdateTriggers(EState *estate, ResultRelInfo *relinfo,
! 					 ItemPointer tupleid, HeapTuple newtuple,
! 					 List *problemIndexList)
  {
  	TriggerDesc *trigdesc = relinfo->ri_TrigDesc;
  
***************
*** 1998,2004 ****
  												   tupleid, NULL);
  
  		AfterTriggerSaveEvent(relinfo, TRIGGER_EVENT_UPDATE,
! 							  true, trigtuple, newtuple);
  		heap_freetuple(trigtuple);
  	}
  }
--- 2033,2039 ----
  												   tupleid, NULL);
  
  		AfterTriggerSaveEvent(relinfo, TRIGGER_EVENT_UPDATE,
! 							  true, trigtuple, newtuple, problemIndexList);
  		heap_freetuple(trigtuple);
  	}
  }
***************
*** 2069,2075 ****
  
  	if (trigdesc && trigdesc->n_after_statement[TRIGGER_EVENT_TRUNCATE] > 0)
  		AfterTriggerSaveEvent(relinfo, TRIGGER_EVENT_TRUNCATE,
! 							  false, NULL, NULL);
  }
  
  
--- 2104,2110 ----
  
  	if (trigdesc && trigdesc->n_after_statement[TRIGGER_EVENT_TRUNCATE] > 0)
  		AfterTriggerSaveEvent(relinfo, TRIGGER_EVENT_TRUNCATE,
! 							  false, NULL, NULL, NIL);
  }
  
  
***************
*** 3782,3796 ****
  /* ----------
   * AfterTriggerSaveEvent()
   *
!  *	Called by ExecA[RS]...Triggers() to add the event to the queue.
   *
!  *	NOTE: should be called only if we've determined that an event must
!  *	be added to the queue.
   * ----------
   */
  static void
  AfterTriggerSaveEvent(ResultRelInfo *relinfo, int event, bool row_trigger,
! 					  HeapTuple oldtup, HeapTuple newtup)
  {
  	Relation	rel = relinfo->ri_RelationDesc;
  	TriggerDesc *trigdesc = relinfo->ri_TrigDesc;
--- 3817,3834 ----
  /* ----------
   * AfterTriggerSaveEvent()
   *
!  *	Called by ExecA[RS]...Triggers() to queue up the triggers that should
!  *	be fired for an event.
   *
!  *	NOTE: this is called whenever there are any triggers associated with
!  *	the event (even if they are disabled). This function decides which
!  *	triggers actually need to be queued.
   * ----------
   */
  static void
  AfterTriggerSaveEvent(ResultRelInfo *relinfo, int event, bool row_trigger,
! 					  HeapTuple oldtup, HeapTuple newtup,
! 					  List *problemIndexList)
  {
  	Relation	rel = relinfo->ri_RelationDesc;
  	TriggerDesc *trigdesc = relinfo->ri_TrigDesc;
***************
*** 3951,3956 ****
--- 3989,4006 ----
  		}
  
  		/*
+ 		 * If the trigger is a deferred unique constraint check trigger,
+ 		 * only execute it if the unique constraint was potentially
+ 		 * violated, which we know from index insertion time.
+ 		 */
+ 		if (trigger->tgfoid == F_UNIQUE_KEY_CHECK_INS ||
+ 			trigger->tgfoid == F_UNIQUE_KEY_CHECK_UPD)
+ 		{
+ 			if (!list_member_oid(problemIndexList, trigger->tgconstrrelid))
+ 				continue; /* Uniqueness definitely not violated */
+ 		}
+ 
+ 		/*
  		 * Fill in event structure and add it to the current query's queue.
  		 */
  		new_shared.ats_event =
*** ./src/backend/executor/execMain.c.orig	2009-07-04 15:43:47.000000000 +0100
--- ./src/backend/executor/execMain.c	2009-07-04 17:45:41.000000000 +0100
***************
*** 1753,1758 ****
--- 1753,1759 ----
  	ResultRelInfo *resultRelInfo;
  	Relation	resultRelationDesc;
  	Oid			newId;
+ 	List	   *problemIndexList = NIL;
  
  	/*
  	 * get the heap tuple out of the tuple table slot, making sure we have a
***************
*** 1834,1843 ****
  	 * insert index entries for tuple
  	 */
  	if (resultRelInfo->ri_NumIndices > 0)
! 		ExecInsertIndexTuples(slot, &(tuple->t_self), estate, false);
  
  	/* AFTER ROW INSERT Triggers */
! 	ExecARInsertTriggers(estate, resultRelInfo, tuple);
  
  	/* Process RETURNING if present */
  	if (resultRelInfo->ri_projectReturning)
--- 1835,1845 ----
  	 * insert index entries for tuple
  	 */
  	if (resultRelInfo->ri_NumIndices > 0)
! 		problemIndexList = ExecInsertIndexTuples(slot, &(tuple->t_self),
! 												 estate, false);
  
  	/* AFTER ROW INSERT Triggers */
! 	ExecARInsertTriggers(estate, resultRelInfo, tuple, problemIndexList);
  
  	/* Process RETURNING if present */
  	if (resultRelInfo->ri_projectReturning)
***************
*** 1999,2004 ****
--- 2001,2007 ----
  	HTSU_Result result;
  	ItemPointerData update_ctid;
  	TransactionId update_xmax;
+ 	List *problemIndexList = NIL;
  
  	/*
  	 * abort the operation if not running transactions
***************
*** 2132,2141 ****
  	 * If it's a HOT update, we mustn't insert new index entries.
  	 */
  	if (resultRelInfo->ri_NumIndices > 0 && !HeapTupleIsHeapOnly(tuple))
! 		ExecInsertIndexTuples(slot, &(tuple->t_self), estate, false);
  
  	/* AFTER ROW UPDATE Triggers */
! 	ExecARUpdateTriggers(estate, resultRelInfo, tupleid, tuple);
  
  	/* Process RETURNING if present */
  	if (resultRelInfo->ri_projectReturning)
--- 2135,2145 ----
  	 * If it's a HOT update, we mustn't insert new index entries.
  	 */
  	if (resultRelInfo->ri_NumIndices > 0 && !HeapTupleIsHeapOnly(tuple))
! 		problemIndexList = ExecInsertIndexTuples(slot, &(tuple->t_self),
! 												 estate, false);
  
  	/* AFTER ROW UPDATE Triggers */
! 	ExecARUpdateTriggers(estate, resultRelInfo, tupleid, tuple, problemIndexList);
  
  	/* Process RETURNING if present */
  	if (resultRelInfo->ri_projectReturning)
*** ./src/backend/executor/execUtils.c.orig	2009-07-19 09:28:05.000000000 +0100
--- ./src/backend/executor/execUtils.c	2009-07-19 13:27:48.000000000 +0100
***************
*** 1036,1044 ****
   *		CAUTION: this must not be called for a HOT update.
   *		We can't defend against that here for lack of info.
   *		Should we change the API to make it safer?
   * ----------------------------------------------------------------
   */
! void
  ExecInsertIndexTuples(TupleTableSlot *slot,
  					  ItemPointer tupleid,
  					  EState *estate,
--- 1036,1048 ----
   *		CAUTION: this must not be called for a HOT update.
   *		We can't defend against that here for lack of info.
   *		Should we change the API to make it safer?
+  *
+  *		This returns a list of OIDs for any unique indexes
+  *		whose constraint check was deferred and which had
+  *		potential (unconfirmed) conflicts.
   * ----------------------------------------------------------------
   */
! List *
  ExecInsertIndexTuples(TupleTableSlot *slot,
  					  ItemPointer tupleid,
  					  EState *estate,
***************
*** 1053,1058 ****
--- 1057,1063 ----
  	ExprContext *econtext;
  	Datum		values[INDEX_MAX_KEYS];
  	bool		isnull[INDEX_MAX_KEYS];
+ 	List		*result = NIL;
  
  	/*
  	 * Get information from the result relation info structure.
***************
*** 1077,1083 ****
  	 */
  	for (i = 0; i < numIndices; i++)
  	{
! 		IndexInfo  *indexInfo;
  
  		if (relationDescs[i] == NULL)
  			continue;
--- 1082,1090 ----
  	 */
  	for (i = 0; i < numIndices; i++)
  	{
! 		IndexInfo		   *indexInfo;
! 		IndexUniqueCheck	uniqueCheck;
! 		bool				isUnique;
  
  		if (relationDescs[i] == NULL)
  			continue;
***************
*** 1125,1143 ****
  		 * The index AM does the rest.	Note we suppress unique-index checks
  		 * if we are being called from VACUUM, since VACUUM may need to move
  		 * dead tuples that have the same keys as live ones.
  		 */
  		index_insert(relationDescs[i],	/* index relation */
! 					 values,	/* array of index Datums */
! 					 isnull,	/* null flags */
! 					 tupleid,	/* tid of heap tuple */
! 					 heapRelation,
! 					 relationDescs[i]->rd_index->indisunique && !is_vacuum);
  
  		/*
  		 * keep track of index inserts for debugging
  		 */
  		IncrIndexInserted();
  	}
  }
  
  /*
--- 1132,1175 ----
  		 * The index AM does the rest.	Note we suppress unique-index checks
  		 * if we are being called from VACUUM, since VACUUM may need to move
  		 * dead tuples that have the same keys as live ones.
+ 		 *
+ 		 * If there is a deferrable unique constraint associated with the
+ 		 * index, then we don't enforce uniqueness here, we just do a partial
+ 		 * check and record if the tuple was potentially non-unique.
  		 */
+ 		if (is_vacuum || !relationDescs[i]->rd_index->indisunique)
+ 			uniqueCheck = UNIQUE_CHECK_NO;
+ 		else if (indexInfo->ii_Deferrable)
+ 			uniqueCheck = UNIQUE_CHECK_PARTIAL;
+ 		else
+ 			uniqueCheck = UNIQUE_CHECK_YES;
+ 
  		index_insert(relationDescs[i],	/* index relation */
! 					 values,			/* array of index Datums */
! 					 isnull,			/* null flags */
! 					 tupleid,			/* tid of heap tuple */
! 					 heapRelation,		/* heap relation */
! 					 uniqueCheck,		/* type of uniqueness check to do */
! 					 &isUnique);		/* result of uniqueness check */
! 
! 		if (uniqueCheck == UNIQUE_CHECK_PARTIAL && !isUnique)
! 		{
! 			/*
! 			 * The tuple potentially violates the uniqueness constraint,
! 			 * so make a note of the index so that we can re-check it
! 			 * later.
! 			 */
! 			result = lappend_oid(result,
! 								 relationDescs[i]->rd_index->indexrelid);
! 		}
  
  		/*
  		 * keep track of index inserts for debugging
  		 */
  		IncrIndexInserted();
  	}
+ 
+ 	return result;
  }
  
  /*
*** ./src/backend/nodes/copyfuncs.c.orig	2009-07-22 11:35:30.000000000 +0100
--- ./src/backend/nodes/copyfuncs.c	2009-07-22 11:35:29.000000000 +0100
***************
*** 2091,2096 ****
--- 2091,2098 ----
  	COPY_NODE_FIELD(keys);
  	COPY_NODE_FIELD(options);
  	COPY_STRING_FIELD(indexspace);
+ 	COPY_SCALAR_FIELD(deferrable);
+ 	COPY_SCALAR_FIELD(initdeferred);
  
  	return newnode;
  }
***************
*** 2510,2515 ****
--- 2512,2519 ----
  	COPY_SCALAR_FIELD(unique);
  	COPY_SCALAR_FIELD(primary);
  	COPY_SCALAR_FIELD(isconstraint);
+ 	COPY_SCALAR_FIELD(constrDeferrable);
+ 	COPY_SCALAR_FIELD(constrInitDeferred);
  	COPY_SCALAR_FIELD(concurrent);
  
  	return newnode;
*** ./src/backend/nodes/equalfuncs.c.orig	2009-07-22 11:36:42.000000000 +0100
--- ./src/backend/nodes/equalfuncs.c	2009-07-22 11:36:40.000000000 +0100
***************
*** 1160,1165 ****
--- 1160,1167 ----
  	COMPARE_SCALAR_FIELD(unique);
  	COMPARE_SCALAR_FIELD(primary);
  	COMPARE_SCALAR_FIELD(isconstraint);
+ 	COMPARE_SCALAR_FIELD(constrDeferrable);
+ 	COMPARE_SCALAR_FIELD(constrInitDeferred);
  	COMPARE_SCALAR_FIELD(concurrent);
  
  	return true;
***************
*** 2069,2074 ****
--- 2071,2078 ----
  	COMPARE_NODE_FIELD(keys);
  	COMPARE_NODE_FIELD(options);
  	COMPARE_STRING_FIELD(indexspace);
+ 	COMPARE_SCALAR_FIELD(deferrable);
+ 	COMPARE_SCALAR_FIELD(initdeferred);
  
  	return true;
  }
*** ./src/backend/nodes/outfuncs.c.orig	2009-07-19 09:45:02.000000000 +0100
--- ./src/backend/nodes/outfuncs.c	2009-07-19 09:45:01.000000000 +0100
***************
*** 1734,1739 ****
--- 1734,1741 ----
  	WRITE_BOOL_FIELD(unique);
  	WRITE_BOOL_FIELD(primary);
  	WRITE_BOOL_FIELD(isconstraint);
+ 	WRITE_BOOL_FIELD(constrDeferrable);
+ 	WRITE_BOOL_FIELD(constrInitDeferred);
  	WRITE_BOOL_FIELD(concurrent);
  }
  
***************
*** 2292,2297 ****
--- 2294,2301 ----
  			WRITE_NODE_FIELD(keys);
  			WRITE_NODE_FIELD(options);
  			WRITE_STRING_FIELD(indexspace);
+ 			WRITE_BOOL_FIELD(deferrable);
+ 			WRITE_BOOL_FIELD(initdeferred);
  			break;
  
  		case CONSTR_CHECK:
*** ./src/backend/parser/gram.y.orig	2009-07-22 11:38:06.000000000 +0100
--- ./src/backend/parser/gram.y	2009-07-22 11:38:05.000000000 +0100
***************
*** 2212,2217 ****
--- 2212,2219 ----
  					n->cooked_expr = NULL;
  					n->keys = NULL;
  					n->indexspace = NULL;
+ 					n->deferrable = FALSE;
+ 					n->initdeferred = FALSE;
  					$$ = (Node *)n;
  				}
  			| NULL_P
***************
*** 2223,2228 ****
--- 2225,2232 ----
  					n->cooked_expr = NULL;
  					n->keys = NULL;
  					n->indexspace = NULL;
+ 					n->deferrable = FALSE;
+ 					n->initdeferred = FALSE;
  					$$ = (Node *)n;
  				}
  			| UNIQUE opt_definition OptConsTableSpace
***************
*** 2235,2240 ****
--- 2239,2246 ----
  					n->keys = NULL;
  					n->options = $2;
  					n->indexspace = $3;
+ 					n->deferrable = FALSE;
+ 					n->initdeferred = FALSE;
  					$$ = (Node *)n;
  				}
  			| PRIMARY KEY opt_definition OptConsTableSpace
***************
*** 2247,2252 ****
--- 2253,2260 ----
  					n->keys = NULL;
  					n->options = $3;
  					n->indexspace = $4;
+ 					n->deferrable = FALSE;
+ 					n->initdeferred = FALSE;
  					$$ = (Node *)n;
  				}
  			| CHECK '(' a_expr ')'
***************
*** 2258,2263 ****
--- 2266,2273 ----
  					n->cooked_expr = NULL;
  					n->keys = NULL;
  					n->indexspace = NULL;
+ 					n->deferrable = FALSE;
+ 					n->initdeferred = FALSE;
  					$$ = (Node *)n;
  				}
  			| DEFAULT b_expr
***************
*** 2269,2274 ****
--- 2279,2286 ----
  					n->cooked_expr = NULL;
  					n->keys = NULL;
  					n->indexspace = NULL;
+ 					n->deferrable = FALSE;
+ 					n->initdeferred = FALSE;
  					$$ = (Node *)n;
  				}
  			| REFERENCES qualified_name opt_column_list key_match key_actions
***************
*** 2398,2406 ****
--- 2410,2421 ----
  					n->raw_expr = $3;
  					n->cooked_expr = NULL;
  					n->indexspace = NULL;
+ 					n->deferrable = FALSE;
+ 					n->initdeferred = FALSE;
  					$$ = (Node *)n;
  				}
  			| UNIQUE '(' columnList ')' opt_definition OptConsTableSpace
+ 				ConstraintAttributeSpec
  				{
  					Constraint *n = makeNode(Constraint);
  					n->contype = CONSTR_UNIQUE;
***************
*** 2410,2415 ****
--- 2425,2432 ----
  					n->keys = $3;
  					n->options = $5;
  					n->indexspace = $6;
+ 					n->deferrable = ($7 & 1) != 0;
+ 					n->initdeferred = ($7 & 2) != 0;
  					$$ = (Node *)n;
  				}
  			| PRIMARY KEY '(' columnList ')' opt_definition OptConsTableSpace
***************
*** 2422,2427 ****
--- 2439,2446 ----
  					n->keys = $4;
  					n->options = $6;
  					n->indexspace = $7;
+ 					n->deferrable = FALSE;
+ 					n->initdeferred = FALSE;
  					$$ = (Node *)n;
  				}
  			| FOREIGN KEY '(' columnList ')' REFERENCES qualified_name
*** ./src/backend/parser/parse_utilcmd.c.orig	2009-07-19 09:53:57.000000000 +0100
--- ./src/backend/parser/parse_utilcmd.c	2009-07-19 09:53:56.000000000 +0100
***************
*** 34,39 ****
--- 34,40 ----
  #include "catalog/index.h"
  #include "catalog/namespace.h"
  #include "catalog/pg_opclass.h"
+ #include "catalog/pg_constraint.h"
  #include "catalog/pg_type.h"
  #include "commands/defrem.h"
  #include "commands/tablecmds.h"
***************
*** 809,815 ****
  	else if (!index->unique)
  		index->isconstraint = false;
  	else
! 		index->isconstraint = OidIsValid(get_index_constraint(source_relid));
  
  	/* Get the index expressions, if any */
  	datum = SysCacheGetAttr(INDEXRELID, ht_idx,
--- 810,843 ----
  	else if (!index->unique)
  		index->isconstraint = false;
  	else
! 	{
! 		/*
! 		 * The index is marked UNIQUE, so there may be an associated unique
! 		 * constraint. If there is, we need to fetch its DEFERRABLE and
! 		 * INITIALLY DEFERRED attributes.
! 		 */
! 		Oid constraintId = get_index_constraint(source_relid);
! 
! 		if (OidIsValid(constraintId))
! 		{
! 			HeapTuple ht_constr = SearchSysCache(CONSTROID,
! 												 ObjectIdGetDatum(constraintId),
! 												 0, 0, 0);
! 			Form_pg_constraint conrec;
! 
! 			if (!HeapTupleIsValid(ht_constr))
! 				elog(ERROR, "cache lookup failed for constraint %u", constraintId);
! 			conrec = (Form_pg_constraint) GETSTRUCT(ht_constr);
! 
! 			index->isconstraint = true;
! 			index->constrDeferrable = conrec->condeferrable;
! 			index->constrInitDeferred = conrec->condeferred;
! 
! 			ReleaseSysCache(ht_constr);
! 		}
! 		else
! 			index->isconstraint = false;
! 	}
  
  	/* Get the index expressions, if any */
  	datum = SysCacheGetAttr(INDEXRELID, ht_idx,
***************
*** 1092,1097 ****
--- 1120,1127 ----
  		 */
  	}
  	index->isconstraint = true;
+ 	index->constrDeferrable = constraint->deferrable;
+ 	index->constrInitDeferred = constraint->initdeferred;
  
  	if (constraint->name != NULL)
  		index->idxname = pstrdup(constraint->name);
***************
*** 1853,1861 ****
   * to attach constraint attributes to their primary constraint nodes
   * and detect inconsistent/misplaced constraint attributes.
   *
!  * NOTE: currently, attributes are only supported for FOREIGN KEY primary
!  * constraints, but someday they ought to be supported for other constraints.
   */
  static void
  transformConstraintAttrs(List *constraintList)
  {
--- 1883,1898 ----
   * to attach constraint attributes to their primary constraint nodes
   * and detect inconsistent/misplaced constraint attributes.
   *
!  * NOTE: currently, attributes are only supported for FOREIGN KEY and
!  * UNIQUE primary constraints, but someday they ought to be supported
!  * for other constraints.
   */
+ #define SUPPORTS_ATTRS(node)								\
+ 	((node) != NULL &&										\
+ 	 (IsA((node), FkConstraint) ||							\
+ 	  (IsA((node), Constraint) &&							\
+ 	   ((Constraint *)(node))->contype == CONSTR_UNIQUE)))
+ 
  static void
  transformConstraintAttrs(List *constraintList)
  {
***************
*** 1882,1889 ****
  			switch (con->contype)
  			{
  				case CONSTR_ATTR_DEFERRABLE:
! 					if (lastprimarynode == NULL ||
! 						!IsA(lastprimarynode, FkConstraint))
  						ereport(ERROR,
  								(errcode(ERRCODE_SYNTAX_ERROR),
  								 errmsg("misplaced DEFERRABLE clause")));
--- 1919,1925 ----
  			switch (con->contype)
  			{
  				case CONSTR_ATTR_DEFERRABLE:
! 					if (!SUPPORTS_ATTRS(lastprimarynode))
  						ereport(ERROR,
  								(errcode(ERRCODE_SYNTAX_ERROR),
  								 errmsg("misplaced DEFERRABLE clause")));
***************
*** 1892,1902 ****
  								(errcode(ERRCODE_SYNTAX_ERROR),
  								 errmsg("multiple DEFERRABLE/NOT DEFERRABLE clauses not allowed")));
  					saw_deferrability = true;
! 					((FkConstraint *) lastprimarynode)->deferrable = true;
  					break;
  				case CONSTR_ATTR_NOT_DEFERRABLE:
! 					if (lastprimarynode == NULL ||
! 						!IsA(lastprimarynode, FkConstraint))
  						ereport(ERROR,
  								(errcode(ERRCODE_SYNTAX_ERROR),
  								 errmsg("misplaced NOT DEFERRABLE clause")));
--- 1928,1941 ----
  								(errcode(ERRCODE_SYNTAX_ERROR),
  								 errmsg("multiple DEFERRABLE/NOT DEFERRABLE clauses not allowed")));
  					saw_deferrability = true;
! 					if (IsA(lastprimarynode, FkConstraint))
! 						((FkConstraint *) lastprimarynode)->deferrable = true;
! 					else
! 						((Constraint *) lastprimarynode)->deferrable = true;
  					break;
+ 
  				case CONSTR_ATTR_NOT_DEFERRABLE:
! 					if (!SUPPORTS_ATTRS(lastprimarynode))
  						ereport(ERROR,
  								(errcode(ERRCODE_SYNTAX_ERROR),
  								 errmsg("misplaced NOT DEFERRABLE clause")));
***************
*** 1905,1920 ****
  								(errcode(ERRCODE_SYNTAX_ERROR),
  								 errmsg("multiple DEFERRABLE/NOT DEFERRABLE clauses not allowed")));
  					saw_deferrability = true;
! 					((FkConstraint *) lastprimarynode)->deferrable = false;
! 					if (saw_initially &&
! 						((FkConstraint *) lastprimarynode)->initdeferred)
! 						ereport(ERROR,
! 								(errcode(ERRCODE_SYNTAX_ERROR),
! 								 errmsg("constraint declared INITIALLY DEFERRED must be DEFERRABLE")));
  					break;
  				case CONSTR_ATTR_DEFERRED:
! 					if (lastprimarynode == NULL ||
! 						!IsA(lastprimarynode, FkConstraint))
  						ereport(ERROR,
  								(errcode(ERRCODE_SYNTAX_ERROR),
  							 errmsg("misplaced INITIALLY DEFERRED clause")));
--- 1944,1971 ----
  								(errcode(ERRCODE_SYNTAX_ERROR),
  								 errmsg("multiple DEFERRABLE/NOT DEFERRABLE clauses not allowed")));
  					saw_deferrability = true;
! 					if (IsA(lastprimarynode, FkConstraint))
! 					{
! 						((FkConstraint *) lastprimarynode)->deferrable = false;
! 						if (saw_initially &&
! 							((FkConstraint *) lastprimarynode)->initdeferred)
! 							ereport(ERROR,
! 									(errcode(ERRCODE_SYNTAX_ERROR),
! 									 errmsg("constraint declared INITIALLY DEFERRED must be DEFERRABLE")));
! 					}
! 					else
! 					{
! 						((Constraint *) lastprimarynode)->deferrable = false;
! 						if (saw_initially &&
! 							((Constraint *) lastprimarynode)->initdeferred)
! 							ereport(ERROR,
! 									(errcode(ERRCODE_SYNTAX_ERROR),
! 									 errmsg("constraint declared INITIALLY DEFERRED must be DEFERRABLE")));
! 					}
  					break;
+ 
  				case CONSTR_ATTR_DEFERRED:
! 					if (!SUPPORTS_ATTRS(lastprimarynode))
  						ereport(ERROR,
  								(errcode(ERRCODE_SYNTAX_ERROR),
  							 errmsg("misplaced INITIALLY DEFERRED clause")));
***************
*** 1923,1943 ****
  								(errcode(ERRCODE_SYNTAX_ERROR),
  								 errmsg("multiple INITIALLY IMMEDIATE/DEFERRED clauses not allowed")));
  					saw_initially = true;
- 					((FkConstraint *) lastprimarynode)->initdeferred = true;
  
  					/*
  					 * If only INITIALLY DEFERRED appears, assume DEFERRABLE
  					 */
! 					if (!saw_deferrability)
! 						((FkConstraint *) lastprimarynode)->deferrable = true;
! 					else if (!((FkConstraint *) lastprimarynode)->deferrable)
! 						ereport(ERROR,
! 								(errcode(ERRCODE_SYNTAX_ERROR),
! 								 errmsg("constraint declared INITIALLY DEFERRED must be DEFERRABLE")));
  					break;
  				case CONSTR_ATTR_IMMEDIATE:
! 					if (lastprimarynode == NULL ||
! 						!IsA(lastprimarynode, FkConstraint))
  						ereport(ERROR,
  								(errcode(ERRCODE_SYNTAX_ERROR),
  							errmsg("misplaced INITIALLY IMMEDIATE clause")));
--- 1974,2009 ----
  								(errcode(ERRCODE_SYNTAX_ERROR),
  								 errmsg("multiple INITIALLY IMMEDIATE/DEFERRED clauses not allowed")));
  					saw_initially = true;
  
  					/*
  					 * If only INITIALLY DEFERRED appears, assume DEFERRABLE
  					 */
! 					if (IsA(lastprimarynode, FkConstraint))
! 					{
! 						((FkConstraint *) lastprimarynode)->initdeferred = true;
! 
! 						if (!saw_deferrability)
! 							((FkConstraint *) lastprimarynode)->deferrable = true;
! 						else if (!((FkConstraint *) lastprimarynode)->deferrable)
! 							ereport(ERROR,
! 									(errcode(ERRCODE_SYNTAX_ERROR),
! 									 errmsg("constraint declared INITIALLY DEFERRED must be DEFERRABLE")));
! 					}
! 					else
! 					{
! 						((Constraint *) lastprimarynode)->initdeferred = true;
! 
! 						if (!saw_deferrability)
! 							((Constraint *) lastprimarynode)->deferrable = true;
! 						else if (!((Constraint *) lastprimarynode)->deferrable)
! 							ereport(ERROR,
! 									(errcode(ERRCODE_SYNTAX_ERROR),
! 									 errmsg("constraint declared INITIALLY DEFERRED must be DEFERRABLE")));
! 					}
  					break;
+ 
  				case CONSTR_ATTR_IMMEDIATE:
! 					if (!SUPPORTS_ATTRS(lastprimarynode))
  						ereport(ERROR,
  								(errcode(ERRCODE_SYNTAX_ERROR),
  							errmsg("misplaced INITIALLY IMMEDIATE clause")));
***************
*** 1946,1953 ****
  								(errcode(ERRCODE_SYNTAX_ERROR),
  								 errmsg("multiple INITIALLY IMMEDIATE/DEFERRED clauses not allowed")));
  					saw_initially = true;
! 					((FkConstraint *) lastprimarynode)->initdeferred = false;
  					break;
  				default:
  					/* Otherwise it's not an attribute */
  					lastprimarynode = node;
--- 2012,2023 ----
  								(errcode(ERRCODE_SYNTAX_ERROR),
  								 errmsg("multiple INITIALLY IMMEDIATE/DEFERRED clauses not allowed")));
  					saw_initially = true;
! 					if (IsA(lastprimarynode, FkConstraint))
! 						((FkConstraint *) lastprimarynode)->initdeferred = false;
! 					else
! 						((Constraint *) lastprimarynode)->initdeferred = false;
  					break;
+ 
  				default:
  					/* Otherwise it's not an attribute */
  					lastprimarynode = node;
*** ./src/backend/tcop/utility.c.orig	2009-07-19 09:57:54.000000000 +0100
--- ./src/backend/tcop/utility.c	2009-07-19 09:57:53.000000000 +0100
***************
*** 795,800 ****
--- 795,802 ----
  							stmt->unique,
  							stmt->primary,
  							stmt->isconstraint,
+ 							stmt->constrDeferrable,
+ 							stmt->constrInitDeferred,
  							false,		/* is_alter_table */
  							true,		/* check_rights */
  							false,		/* skip_build */
*** ./src/backend/utils/adt/ruleutils.c.orig	2009-07-19 10:00:24.000000000 +0100
--- ./src/backend/utils/adt/ruleutils.c	2009-07-19 10:00:23.000000000 +0100
***************
*** 1096,1101 ****
--- 1096,1106 ----
  							  quote_identifier(get_tablespace_name(tblspc)));
  				}
  
+ 				if (conForm->condeferrable)
+ 					appendStringInfo(&buf, " DEFERRABLE");
+ 				if (conForm->condeferred)
+ 					appendStringInfo(&buf, " INITIALLY DEFERRED");
+ 
  				break;
  			}
  		case CONSTRAINT_CHECK:
*** ./src/bin/pg_dump/pg_dump.c.orig	2009-07-22 11:39:55.000000000 +0100
--- ./src/bin/pg_dump/pg_dump.c	2009-07-22 11:39:53.000000000 +0100
***************
*** 3657,3663 ****
  				i_contableoid,
  				i_conoid,
  				i_tablespace,
! 				i_options;
  	int			ntups;
  
  	for (i = 0; i < numTables; i++)
--- 3657,3665 ----
  				i_contableoid,
  				i_conoid,
  				i_tablespace,
! 				i_options,
! 				i_condeferrable,
! 				i_coninitdeferred;
  	int			ntups;
  
  	for (i = 0; i < numTables; i++)
***************
*** 3698,3704 ****
  							  "c.tableoid AS contableoid, "
  							  "c.oid AS conoid, "
  							  "(SELECT spcname FROM pg_catalog.pg_tablespace s WHERE s.oid = t.reltablespace) AS tablespace, "
! 							"array_to_string(t.reloptions, ', ') AS options "
  							  "FROM pg_catalog.pg_index i "
  					  "JOIN pg_catalog.pg_class t ON (t.oid = i.indexrelid) "
  							  "LEFT JOIN pg_catalog.pg_depend d "
--- 3700,3708 ----
  							  "c.tableoid AS contableoid, "
  							  "c.oid AS conoid, "
  							  "(SELECT spcname FROM pg_catalog.pg_tablespace s WHERE s.oid = t.reltablespace) AS tablespace, "
! 							"array_to_string(t.reloptions, ', ') AS options, "
! 							  "c.condeferrable AS condeferrable, "
! 							  "c.condeferred AS coninitdeferred "
  							  "FROM pg_catalog.pg_index i "
  					  "JOIN pg_catalog.pg_class t ON (t.oid = i.indexrelid) "
  							  "LEFT JOIN pg_catalog.pg_depend d "
***************
*** 3724,3730 ****
  							  "c.tableoid AS contableoid, "
  							  "c.oid AS conoid, "
  							  "(SELECT spcname FROM pg_catalog.pg_tablespace s WHERE s.oid = t.reltablespace) AS tablespace, "
! 							  "null AS options "
  							  "FROM pg_catalog.pg_index i "
  					  "JOIN pg_catalog.pg_class t ON (t.oid = i.indexrelid) "
  							  "LEFT JOIN pg_catalog.pg_depend d "
--- 3728,3736 ----
  							  "c.tableoid AS contableoid, "
  							  "c.oid AS conoid, "
  							  "(SELECT spcname FROM pg_catalog.pg_tablespace s WHERE s.oid = t.reltablespace) AS tablespace, "
! 							  "null AS options, "
! 							  "false AS condeferrable, "
! 							  "false AS coninitdeferred "
  							  "FROM pg_catalog.pg_index i "
  					  "JOIN pg_catalog.pg_class t ON (t.oid = i.indexrelid) "
  							  "LEFT JOIN pg_catalog.pg_depend d "
***************
*** 3750,3756 ****
  							  "c.tableoid AS contableoid, "
  							  "c.oid AS conoid, "
  							  "NULL AS tablespace, "
! 							  "null AS options "
  							  "FROM pg_catalog.pg_index i "
  					  "JOIN pg_catalog.pg_class t ON (t.oid = i.indexrelid) "
  							  "LEFT JOIN pg_catalog.pg_depend d "
--- 3756,3764 ----
  							  "c.tableoid AS contableoid, "
  							  "c.oid AS conoid, "
  							  "NULL AS tablespace, "
! 							  "null AS options, "
! 							  "false AS condeferrable, "
! 							  "false AS coninitdeferred "
  							  "FROM pg_catalog.pg_index i "
  					  "JOIN pg_catalog.pg_class t ON (t.oid = i.indexrelid) "
  							  "LEFT JOIN pg_catalog.pg_depend d "
***************
*** 3778,3784 ****
  							  "0::oid AS contableoid, "
  							  "t.oid AS conoid, "
  							  "NULL AS tablespace, "
! 							  "null AS options "
  							  "FROM pg_index i, pg_class t "
  							  "WHERE t.oid = i.indexrelid "
  							  "AND i.indrelid = '%u'::oid "
--- 3786,3794 ----
  							  "0::oid AS contableoid, "
  							  "t.oid AS conoid, "
  							  "NULL AS tablespace, "
! 							  "null AS options, "
! 							  "false AS condeferrable, "
! 							  "false AS coninitdeferred "
  							  "FROM pg_index i, pg_class t "
  							  "WHERE t.oid = i.indexrelid "
  							  "AND i.indrelid = '%u'::oid "
***************
*** 3801,3807 ****
  							  "0::oid AS contableoid, "
  							  "t.oid AS conoid, "
  							  "NULL AS tablespace, "
! 							  "null AS options "
  							  "FROM pg_index i, pg_class t "
  							  "WHERE t.oid = i.indexrelid "
  							  "AND i.indrelid = '%u'::oid "
--- 3811,3819 ----
  							  "0::oid AS contableoid, "
  							  "t.oid AS conoid, "
  							  "NULL AS tablespace, "
! 							  "null AS options, "
! 							  "false AS condeferrable, "
! 							  "false AS coninitdeferred "
  							  "FROM pg_index i, pg_class t "
  							  "WHERE t.oid = i.indexrelid "
  							  "AND i.indrelid = '%u'::oid "
***************
*** 3827,3832 ****
--- 3839,3846 ----
  		i_conoid = PQfnumber(res, "conoid");
  		i_tablespace = PQfnumber(res, "tablespace");
  		i_options = PQfnumber(res, "options");
+ 		i_condeferrable = PQfnumber(res, "condeferrable");
+ 		i_coninitdeferred = PQfnumber(res, "coninitdeferred");
  
  		indxinfo = (IndxInfo *) malloc(ntups * sizeof(IndxInfo));
  		constrinfo = (ConstraintInfo *) malloc(ntups * sizeof(ConstraintInfo));
***************
*** 3885,3890 ****
--- 3899,3906 ----
  				constrinfo[j].conindex = indxinfo[j].dobj.dumpId;
  				constrinfo[j].conislocal = true;
  				constrinfo[j].separate = true;
+ 				constrinfo[j].condeferrable = *(PQgetvalue(res, j, i_condeferrable)) == 't';
+ 				constrinfo[j].coninitdeferred = *(PQgetvalue(res, j, i_coninitdeferred)) == 't';
  
  				indxinfo[j].indexconstraint = constrinfo[j].dobj.dumpId;
  
***************
*** 3989,3994 ****
--- 4005,4012 ----
  			constrinfo[j].conindex = 0;
  			constrinfo[j].conislocal = true;
  			constrinfo[j].separate = true;
+ 			constrinfo[j].condeferrable = false;	/* Part of condef */
+ 			constrinfo[j].coninitdeferred = false;	/* Part of condef */
  		}
  
  		PQclear(res);
***************
*** 4073,4078 ****
--- 4091,4098 ----
  		constrinfo[i].conindex = 0;
  		constrinfo[i].conislocal = true;
  		constrinfo[i].separate = false;
+ 		constrinfo[i].condeferrable = false;
+ 		constrinfo[i].coninitdeferred = false;
  
  		/*
  		 * Make the domain depend on the constraint, ensuring it won't be
***************
*** 5072,5077 ****
--- 5092,5099 ----
  				constrs[j].conindex = 0;
  				constrs[j].conislocal = (PQgetvalue(res, j, 4)[0] == 't');
  				constrs[j].separate = false;
+ 				constrs[j].condeferrable = false;
+ 				constrs[j].coninitdeferred = false;
  
  				constrs[j].dobj.dump = tbinfo->dobj.dump;
  
***************
*** 10340,10345 ****
--- 10362,10374 ----
  		if (indxinfo->options && strlen(indxinfo->options) > 0)
  			appendPQExpBuffer(q, " WITH (%s)", indxinfo->options);
  
+ 		if (coninfo->condeferrable)
+ 		{
+ 			appendPQExpBuffer(q, " DEFERRABLE");
+ 			if (coninfo->coninitdeferred)
+ 				appendPQExpBuffer(q, " INITIALLY DEFERRED");
+ 		}
+ 
  		appendPQExpBuffer(q, ";\n");
  
  		/* If the index is clustered, we need to record that. */
*** ./src/bin/pg_dump/pg_dump.h.orig	2009-07-09 10:15:54.000000000 +0100
--- ./src/bin/pg_dump/pg_dump.h	2009-07-09 10:21:12.000000000 +0100
***************
*** 344,349 ****
--- 344,351 ----
  	DumpId		conindex;		/* identifies associated index if any */
  	bool		conislocal;		/* TRUE if constraint has local definition */
  	bool		separate;		/* TRUE if must dump as separate item */
+ 	bool		condeferrable;	/* TRUE if constraint is DEFERRABLE */
+ 	bool		coninitdeferred; /* TRUE if constraint is INITIALLY DEFERRED */
  } ConstraintInfo;
  
  typedef struct _procLangInfo
*** ./src/bin/psql/describe.c.orig	2009-07-22 11:41:17.000000000 +0100
--- ./src/bin/psql/describe.c	2009-07-22 11:41:16.000000000 +0100
***************
*** 1324,1329 ****
--- 1324,1340 ----
  			appendPQExpBuffer(&buf, "i.indisvalid, ");
  		else
  			appendPQExpBuffer(&buf, "true as indisvalid, ");
+ 		if (pset.sversion >= 80500)
+ 			appendPQExpBuffer(&buf,
+ 							  "EXISTS (SELECT 1 FROM pg_catalog.pg_depend d, "
+ 							  "pg_catalog.pg_constraint con WHERE d.objid = i.indexrelid "
+ 							  "AND con.oid = d.refobjid AND con.condeferrable) "
+ 							  "as condeferrable, EXISTS (SELECT 1 FROM "
+ 							  "pg_catalog.pg_depend d, pg_catalog.pg_constraint con "
+ 							  "WHERE d.objid = i.indexrelid AND con.oid = d.refobjid "
+ 							  "AND con.condeferred) as condeferred, ");
+ 		else
+ 			appendPQExpBuffer(&buf, "false as condeferrable, false as condeferred, ");
  		appendPQExpBuffer(&buf, "a.amname, c2.relname,\n"
  					"  pg_catalog.pg_get_expr(i.indpred, i.indrelid, true)\n"
  						  "FROM pg_catalog.pg_index i, pg_catalog.pg_class c, pg_catalog.pg_class c2, pg_catalog.pg_am a\n"
***************
*** 1345,1353 ****
  			char	   *indisprimary = PQgetvalue(result, 0, 1);
  			char	   *indisclustered = PQgetvalue(result, 0, 2);
  			char	   *indisvalid = PQgetvalue(result, 0, 3);
! 			char	   *indamname = PQgetvalue(result, 0, 4);
! 			char	   *indtable = PQgetvalue(result, 0, 5);
! 			char	   *indpred = PQgetvalue(result, 0, 6);
  
  			if (strcmp(indisprimary, "t") == 0)
  				printfPQExpBuffer(&tmpbuf, _("primary key, "));
--- 1356,1366 ----
  			char	   *indisprimary = PQgetvalue(result, 0, 1);
  			char	   *indisclustered = PQgetvalue(result, 0, 2);
  			char	   *indisvalid = PQgetvalue(result, 0, 3);
! 			char	   *deferrable = PQgetvalue(result, 0, 4);
! 			char	   *deferred = PQgetvalue(result, 0, 5);
! 			char	   *indamname = PQgetvalue(result, 0, 6);
! 			char	   *indtable = PQgetvalue(result, 0, 7);
! 			char	   *indpred = PQgetvalue(result, 0, 8);
  
  			if (strcmp(indisprimary, "t") == 0)
  				printfPQExpBuffer(&tmpbuf, _("primary key, "));
***************
*** 1370,1375 ****
--- 1383,1394 ----
  			if (strcmp(indisvalid, "t") != 0)
  				appendPQExpBuffer(&tmpbuf, _(", invalid"));
  
+ 			if (strcmp(deferrable, "t") == 0)
+ 				appendPQExpBuffer(&tmpbuf, _(", deferrable"));
+ 
+ 			if (strcmp(deferred, "t") == 0)
+ 				appendPQExpBuffer(&tmpbuf, _(", initially deferred"));
+ 
  			printTableAddFooter(&cont, tmpbuf.data);
  			add_tablespace_footer(&cont, tableinfo.relkind,
  								  tableinfo.tablespace, true);
***************
*** 1431,1436 ****
--- 1450,1466 ----
  			else
  				appendPQExpBuffer(&buf, "true as indisvalid, ");
  			appendPQExpBuffer(&buf, "pg_catalog.pg_get_indexdef(i.indexrelid, 0, true)");
+ 			if (pset.sversion >= 80500)
+ 				appendPQExpBuffer(&buf,
+ 								  ", EXISTS (SELECT 1 FROM pg_catalog.pg_depend d, "
+ 								  "pg_catalog.pg_constraint con WHERE d.objid = i.indexrelid "
+ 								  "AND con.oid = d.refobjid AND con.condeferrable) "
+ 								  "as condeferrable, EXISTS (SELECT 1 FROM "
+ 								  "pg_catalog.pg_depend d, pg_catalog.pg_constraint con "
+ 								  "WHERE d.objid = i.indexrelid AND con.oid = d.refobjid "
+ 								  "AND con.condeferred) as condeferred");
+ 			else
+ 				appendPQExpBuffer(&buf, ", false as condeferrable, false as condeferred");
  			if (pset.sversion >= 80000)
  				appendPQExpBuffer(&buf, ", c2.reltablespace");
  			appendPQExpBuffer(&buf,
***************
*** 1477,1488 ****
  					if (strcmp(PQgetvalue(result, i, 4), "t") != 0)
  						appendPQExpBuffer(&buf, " INVALID");
  
  					printTableAddFooter(&cont, buf.data);
  
  					/* Print tablespace of the index on the same line */
  					if (pset.sversion >= 80000)
  						add_tablespace_footer(&cont, 'i',
! 											atooid(PQgetvalue(result, i, 6)),
  											  false);
  				}
  			}
--- 1507,1524 ----
  					if (strcmp(PQgetvalue(result, i, 4), "t") != 0)
  						appendPQExpBuffer(&buf, " INVALID");
  
+ 					if (strcmp(PQgetvalue(result, i, 6), "t") == 0)
+ 						appendPQExpBuffer(&buf, " DEFERRABLE");
+ 
+ 					if (strcmp(PQgetvalue(result, i, 7), "t") == 0)
+ 						appendPQExpBuffer(&buf, " INITIALLY DEFERRED");
+ 
  					printTableAddFooter(&cont, buf.data);
  
  					/* Print tablespace of the index on the same line */
  					if (pset.sversion >= 80000)
  						add_tablespace_footer(&cont, 'i',
! 											atooid(PQgetvalue(result, i, 8)),
  											  false);
  				}
  			}
*** ./src/include/access/genam.h.orig	2009-07-04 15:42:49.000000000 +0100
--- ./src/include/access/genam.h	2009-07-18 11:19:44.000000000 +0100
***************
*** 85,90 ****
--- 85,118 ----
  typedef struct IndexScanDescData *IndexScanDesc;
  typedef struct SysScanDescData *SysScanDesc;
  
+ /*
+  * Enumeration specifying the type of uniqueness check to perform for
+  * index_insert().
+  *
+  * For deferrable unique constraints, UNIQUE_CHECK_PARTIAL is used at
+  * insertion time. This tests if the tuple is unique but doesn't error,
+  * block or prevent the insertion if the tuple appears not to be unique.
+  * Since it isn't blocking, it can't know for sure if the tuple is not
+  * unique (the other transaction might be rolled back). The return value
+  * of index_insert() in this case is true if the tuple is definitely
+  * unique and false if it is possibly non-unique.
+  *
+  * UNIQUE_CHECK_EXISTING is for deferred unqiue constraint checks. The
+  * tuple is already in the index when the check is performed, so it is
+  * not inserted again. This just checks if the tuple in the index is
+  * unique.
+  */
+ typedef enum IndexUniqueCheck
+ {
+ 	UNIQUE_CHECK_NO,			/* Don't do any uniqueness checking */
+ 	UNIQUE_CHECK_YES,			/* Enforce uniqueness at insertion time */
+ 								/* (possibly blocking on another xact) */
+ 	UNIQUE_CHECK_PARTIAL,		/* Test uniqueness, but don't block and */
+ 								/* no error if potentially not unique */
+ 	UNIQUE_CHECK_EXISTING		/* Don't do the insert, just check if */
+ 								/* the existing tuple is unique */
+ } IndexUniqueCheck;
+ 
  
  /*
   * generalized index_ interface routines (in indexam.c)
***************
*** 103,109 ****
  			 Datum *values, bool *isnull,
  			 ItemPointer heap_t_ctid,
  			 Relation heapRelation,
! 			 bool check_uniqueness);
  
  extern IndexScanDesc index_beginscan(Relation heapRelation,
  				Relation indexRelation,
--- 131,138 ----
  			 Datum *values, bool *isnull,
  			 ItemPointer heap_t_ctid,
  			 Relation heapRelation,
! 			 IndexUniqueCheck uniqueness,
! 			 bool *is_unique);
  
  extern IndexScanDesc index_beginscan(Relation heapRelation,
  				Relation indexRelation,
*** ./src/include/access/nbtree.h.orig	2009-07-04 15:42:49.000000000 +0100
--- ./src/include/access/nbtree.h	2009-07-18 12:34:19.000000000 +0100
***************
*** 517,524 ****
  /*
   * prototypes for functions in nbtinsert.c
   */
! extern void _bt_doinsert(Relation rel, IndexTuple itup,
! 			 bool index_is_unique, Relation heapRel);
  extern Buffer _bt_getstackbuf(Relation rel, BTStack stack, int access);
  extern void _bt_insert_parent(Relation rel, Buffer buf, Buffer rbuf,
  				  BTStack stack, bool is_root, bool is_only);
--- 517,524 ----
  /*
   * prototypes for functions in nbtinsert.c
   */
! extern bool _bt_doinsert(Relation rel, IndexTuple itup,
! 			 IndexUniqueCheck unique_check, Relation heapRel, bool *is_unique);
  extern Buffer _bt_getstackbuf(Relation rel, BTStack stack, int access);
  extern void _bt_insert_parent(Relation rel, Buffer buf, Buffer rbuf,
  				  BTStack stack, bool is_root, bool is_only);
*** ./src/include/catalog/pg_proc.h.orig	2009-07-11 13:12:26.000000000 +0100
--- ./src/include/catalog/pg_proc.h	2009-07-18 12:48:21.000000000 +0100
***************
*** 663,669 ****
  DESCR("btree(internal)");
  DATA(insert OID = 636 (  btgetbitmap	   PGNSP PGUID 12 1 0 0 f f f t f v 2 0 20 "2281 2281" _null_ _null_ _null_ _null_	btgetbitmap _null_ _null_ _null_ ));
  DESCR("btree(internal)");
! DATA(insert OID = 331 (  btinsert		   PGNSP PGUID 12 1 0 0 f f f t f v 6 0 16 "2281 2281 2281 2281 2281 2281" _null_ _null_ _null_ _null_	btinsert _null_ _null_ _null_ ));
  DESCR("btree(internal)");
  DATA(insert OID = 333 (  btbeginscan	   PGNSP PGUID 12 1 0 0 f f f t f v 3 0 2281 "2281 2281 2281" _null_ _null_ _null_ _null_	btbeginscan _null_ _null_ _null_ ));
  DESCR("btree(internal)");
--- 663,669 ----
  DESCR("btree(internal)");
  DATA(insert OID = 636 (  btgetbitmap	   PGNSP PGUID 12 1 0 0 f f f t f v 2 0 20 "2281 2281" _null_ _null_ _null_ _null_	btgetbitmap _null_ _null_ _null_ ));
  DESCR("btree(internal)");
! DATA(insert OID = 331 (  btinsert		   PGNSP PGUID 12 1 0 0 f f f t f v 7 0 16 "2281 2281 2281 2281 2281 2281 2281" _null_ _null_ _null_ _null_	btinsert _null_ _null_ _null_ ));
  DESCR("btree(internal)");
  DATA(insert OID = 333 (  btbeginscan	   PGNSP PGUID 12 1 0 0 f f f t f v 3 0 2281 "2281 2281 2281" _null_ _null_ _null_ _null_	btbeginscan _null_ _null_ _null_ ));
  DESCR("btree(internal)");
***************
*** 782,788 ****
  DESCR("hash(internal)");
  DATA(insert OID = 637 (  hashgetbitmap	   PGNSP PGUID 12 1 0 0 f f f t f v 2 0 20 "2281 2281" _null_ _null_ _null_ _null_	hashgetbitmap _null_ _null_ _null_ ));
  DESCR("hash(internal)");
! DATA(insert OID = 441 (  hashinsert		   PGNSP PGUID 12 1 0 0 f f f t f v 6 0 16 "2281 2281 2281 2281 2281 2281" _null_ _null_ _null_ _null_	hashinsert _null_ _null_ _null_ ));
  DESCR("hash(internal)");
  DATA(insert OID = 443 (  hashbeginscan	   PGNSP PGUID 12 1 0 0 f f f t f v 3 0 2281 "2281 2281 2281" _null_ _null_ _null_ _null_	hashbeginscan _null_ _null_ _null_ ));
  DESCR("hash(internal)");
--- 782,788 ----
  DESCR("hash(internal)");
  DATA(insert OID = 637 (  hashgetbitmap	   PGNSP PGUID 12 1 0 0 f f f t f v 2 0 20 "2281 2281" _null_ _null_ _null_ _null_	hashgetbitmap _null_ _null_ _null_ ));
  DESCR("hash(internal)");
! DATA(insert OID = 441 (  hashinsert		   PGNSP PGUID 12 1 0 0 f f f t f v 7 0 16 "2281 2281 2281 2281 2281 2281 2281" _null_ _null_ _null_ _null_	hashinsert _null_ _null_ _null_ ));
  DESCR("hash(internal)");
  DATA(insert OID = 443 (  hashbeginscan	   PGNSP PGUID 12 1 0 0 f f f t f v 3 0 2281 "2281 2281 2281" _null_ _null_ _null_ _null_	hashbeginscan _null_ _null_ _null_ ));
  DESCR("hash(internal)");
***************
*** 1067,1073 ****
  DESCR("gist(internal)");
  DATA(insert OID = 638 (  gistgetbitmap	   PGNSP PGUID 12 1 0 0 f f f t f v 2 0 20 "2281 2281" _null_ _null_ _null_ _null_	gistgetbitmap _null_ _null_ _null_ ));
  DESCR("gist(internal)");
! DATA(insert OID = 775 (  gistinsert		   PGNSP PGUID 12 1 0 0 f f f t f v 6 0 16 "2281 2281 2281 2281 2281 2281" _null_ _null_ _null_ _null_	gistinsert _null_ _null_ _null_ ));
  DESCR("gist(internal)");
  DATA(insert OID = 777 (  gistbeginscan	   PGNSP PGUID 12 1 0 0 f f f t f v 3 0 2281 "2281 2281 2281" _null_ _null_ _null_ _null_	gistbeginscan _null_ _null_ _null_ ));
  DESCR("gist(internal)");
--- 1067,1073 ----
  DESCR("gist(internal)");
  DATA(insert OID = 638 (  gistgetbitmap	   PGNSP PGUID 12 1 0 0 f f f t f v 2 0 20 "2281 2281" _null_ _null_ _null_ _null_	gistgetbitmap _null_ _null_ _null_ ));
  DESCR("gist(internal)");
! DATA(insert OID = 775 (  gistinsert		   PGNSP PGUID 12 1 0 0 f f f t f v 7 0 16 "2281 2281 2281 2281 2281 2281 2281" _null_ _null_ _null_ _null_	gistinsert _null_ _null_ _null_ ));
  DESCR("gist(internal)");
  DATA(insert OID = 777 (  gistbeginscan	   PGNSP PGUID 12 1 0 0 f f f t f v 3 0 2281 "2281 2281 2281" _null_ _null_ _null_ _null_	gistbeginscan _null_ _null_ _null_ ));
  DESCR("gist(internal)");
***************
*** 2349,2354 ****
--- 2349,2360 ----
  DATA(insert OID = 1655 (  RI_FKey_noaction_upd PGNSP PGUID 12 1 0 0 f f f t f v 0 0 2279 "" _null_ _null_ _null_ _null_ RI_FKey_noaction_upd _null_ _null_ _null_ ));
  DESCR("referential integrity ON UPDATE NO ACTION");
  
+ /* Deferrable unique constraint triggers */
+ DATA(insert OID = 1029 (  unique_key_check_ins     PGNSP PGUID 12 1 0 0 f f f t f v 0 0 2279 "" _null_ _null_ _null_ _null_ unique_key_check_ins _null_ _null_ _null_ ));
+ DESCR("deferred check UNIQUE ... DEFERRABLE");
+ DATA(insert OID = 1030 (  unique_key_check_upd     PGNSP PGUID 12 1 0 0 f f f t f v 0 0 2279 "" _null_ _null_ _null_ _null_ unique_key_check_upd _null_ _null_ _null_ ));
+ DESCR("deferred check UNIQUE ... DEFERRABLE");
+ 
  DATA(insert OID = 1666 (  varbiteq			PGNSP PGUID 12 1 0 0 f f f t f i 2 0 16 "1562 1562" _null_ _null_ _null_ _null_ biteq _null_ _null_ _null_ ));
  DESCR("equal");
  DATA(insert OID = 1667 (  varbitne			PGNSP PGUID 12 1 0 0 f f f t f i 2 0 16 "1562 1562" _null_ _null_ _null_ _null_ bitne _null_ _null_ _null_ ));
***************
*** 4187,4193 ****
  /* GIN */
  DATA(insert OID = 2731 (  gingetbitmap	   PGNSP PGUID 12 1 0 0 f f f t f v 2 0 20 "2281 2281" _null_ _null_ _null_ _null_	gingetbitmap _null_ _null_ _null_ ));
  DESCR("gin(internal)");
! DATA(insert OID = 2732 (  gininsert		   PGNSP PGUID 12 1 0 0 f f f t f v 6 0 16 "2281 2281 2281 2281 2281 2281" _null_ _null_ _null_ _null_	gininsert _null_ _null_ _null_ ));
  DESCR("gin(internal)");
  DATA(insert OID = 2733 (  ginbeginscan	   PGNSP PGUID 12 1 0 0 f f f t f v 3 0 2281 "2281 2281 2281" _null_ _null_ _null_ _null_	ginbeginscan _null_ _null_ _null_ ));
  DESCR("gin(internal)");
--- 4193,4199 ----
  /* GIN */
  DATA(insert OID = 2731 (  gingetbitmap	   PGNSP PGUID 12 1 0 0 f f f t f v 2 0 20 "2281 2281" _null_ _null_ _null_ _null_	gingetbitmap _null_ _null_ _null_ ));
  DESCR("gin(internal)");
! DATA(insert OID = 2732 (  gininsert		   PGNSP PGUID 12 1 0 0 f f f t f v 7 0 16 "2281 2281 2281 2281 2281 2281 2281" _null_ _null_ _null_ _null_	gininsert _null_ _null_ _null_ ));
  DESCR("gin(internal)");
  DATA(insert OID = 2733 (  ginbeginscan	   PGNSP PGUID 12 1 0 0 f f f t f v 3 0 2281 "2281 2281 2281" _null_ _null_ _null_ _null_	ginbeginscan _null_ _null_ _null_ ));
  DESCR("gin(internal)");
*** ./src/include/commands/defrem.h.orig	2009-07-19 10:03:56.000000000 +0100
--- ./src/include/commands/defrem.h	2009-07-19 10:03:56.000000000 +0100
***************
*** 29,34 ****
--- 29,36 ----
  			bool unique,
  			bool primary,
  			bool isconstraint,
+ 			bool constrDeferrable,
+ 			bool constrInitDeferred,
  			bool is_alter_table,
  			bool check_rights,
  			bool skip_build,
*** ./src/include/commands/trigger.h.orig	2009-07-04 15:42:49.000000000 +0100
--- ./src/include/commands/trigger.h	2009-07-04 16:46:36.000000000 +0100
***************
*** 131,137 ****
  					 HeapTuple trigtuple);
  extern void ExecARInsertTriggers(EState *estate,
  					 ResultRelInfo *relinfo,
! 					 HeapTuple trigtuple);
  extern void ExecBSDeleteTriggers(EState *estate,
  					 ResultRelInfo *relinfo);
  extern void ExecASDeleteTriggers(EState *estate,
--- 131,138 ----
  					 HeapTuple trigtuple);
  extern void ExecARInsertTriggers(EState *estate,
  					 ResultRelInfo *relinfo,
! 					 HeapTuple trigtuple,
! 					 List *problemIndexList);
  extern void ExecBSDeleteTriggers(EState *estate,
  					 ResultRelInfo *relinfo);
  extern void ExecASDeleteTriggers(EState *estate,
***************
*** 153,159 ****
  extern void ExecARUpdateTriggers(EState *estate,
  					 ResultRelInfo *relinfo,
  					 ItemPointer tupleid,
! 					 HeapTuple newtuple);
  extern void ExecBSTruncateTriggers(EState *estate,
  					   ResultRelInfo *relinfo);
  extern void ExecASTruncateTriggers(EState *estate,
--- 154,161 ----
  extern void ExecARUpdateTriggers(EState *estate,
  					 ResultRelInfo *relinfo,
  					 ItemPointer tupleid,
! 					 HeapTuple newtuple,
! 					 List *problemIndexList);
  extern void ExecBSTruncateTriggers(EState *estate,
  					   ResultRelInfo *relinfo);
  extern void ExecASTruncateTriggers(EState *estate,
*** ./src/include/executor/executor.h.orig	2009-07-19 10:05:15.000000000 +0100
--- ./src/include/executor/executor.h	2009-07-19 10:05:15.000000000 +0100
***************
*** 301,307 ****
  
  extern void ExecOpenIndices(ResultRelInfo *resultRelInfo);
  extern void ExecCloseIndices(ResultRelInfo *resultRelInfo);
! extern void ExecInsertIndexTuples(TupleTableSlot *slot, ItemPointer tupleid,
  					  EState *estate, bool is_vacuum);
  
  extern void RegisterExprContextCallback(ExprContext *econtext,
--- 301,307 ----
  
  extern void ExecOpenIndices(ResultRelInfo *resultRelInfo);
  extern void ExecCloseIndices(ResultRelInfo *resultRelInfo);
! extern List *ExecInsertIndexTuples(TupleTableSlot *slot, ItemPointer tupleid,
  					  EState *estate, bool is_vacuum);
  
  extern void RegisterExprContextCallback(ExprContext *econtext,
*** ./src/include/nodes/execnodes.h.orig	2009-07-04 15:42:49.000000000 +0100
--- ./src/include/nodes/execnodes.h	2009-07-04 16:34:51.000000000 +0100
***************
*** 44,49 ****
--- 44,52 ----
   *		ReadyForInserts		is it valid for inserts?
   *		Concurrent			are we doing a concurrent index build?
   *		BrokenHotChain		did we detect any broken HOT chains?
+  *		ConstraintId		OID of constraint associated with this index
+  *		Deferrable			is the constraint DEFERRABLE?
+  *		InitDeferred		is the constraint INITIALLY DEFERRED?
   *
   * ii_Concurrent and ii_BrokenHotChain are used only during index build;
   * they're conventionally set to false otherwise.
***************
*** 62,67 ****
--- 65,73 ----
  	bool		ii_ReadyForInserts;
  	bool		ii_Concurrent;
  	bool		ii_BrokenHotChain;
+ 	Oid			ii_ConstraintId;
+ 	bool		ii_Deferrable;
+ 	bool		ii_InitDeferred;
  } IndexInfo;
  
  /* ----------------
*** ./src/include/nodes/parsenodes.h.orig	2009-07-22 11:43:07.000000000 +0100
--- ./src/include/nodes/parsenodes.h	2009-07-22 11:43:06.000000000 +0100
***************
*** 1355,1361 ****
   * Constraint attributes (DEFERRABLE etc) are initially represented as
   * separate Constraint nodes for simplicity of parsing.  parse_utilcmd.c makes
   * a pass through the constraints list to attach the info to the appropriate
!  * FkConstraint node (and, perhaps, someday to other kinds of constraints).
   * ----------
   */
  
--- 1355,1361 ----
   * Constraint attributes (DEFERRABLE etc) are initially represented as
   * separate Constraint nodes for simplicity of parsing.  parse_utilcmd.c makes
   * a pass through the constraints list to attach the info to the appropriate
!  * Constraint and FkConstraint nodes.
   * ----------
   */
  
***************
*** 1385,1390 ****
--- 1385,1392 ----
  	List	   *options;		/* options from WITH clause */
  	char	   *indexspace;		/* index tablespace for PKEY/UNIQUE
  								 * constraints; NULL for default */
+ 	bool		deferrable;		/* DEFERRABLE */
+ 	bool		initdeferred;	/* INITIALLY DEFERRED */
  } Constraint;
  
  /* ----------
***************
*** 1864,1869 ****
--- 1866,1873 ----
  	bool		unique;			/* is index unique? */
  	bool		primary;		/* is index on primary key? */
  	bool		isconstraint;	/* is it from a CONSTRAINT clause? */
+ 	bool		constrDeferrable; /* is the constraint DEFERRABLE? */
+ 	bool		constrInitDeferred; /* is the constraint INITIALLY DEFERRED? */
  	bool		concurrent;		/* should this be a concurrent index build? */
  } IndexStmt;
  
*** ./src/include/utils/builtins.h.orig	2009-07-19 10:09:52.000000000 +0100
--- ./src/include/utils/builtins.h	2009-07-22 10:28:49.000000000 +0100
***************
*** 1029,1034 ****
--- 1029,1038 ----
  /* access/transam/twophase.c */
  extern Datum pg_prepared_xact(PG_FUNCTION_ARGS);
  
+ /* commands/constraint.c */
+ extern Datum unique_key_check_ins(PG_FUNCTION_ARGS);
+ extern Datum unique_key_check_upd(PG_FUNCTION_ARGS);
+ 
  /* commands/prepare.c */
  extern Datum pg_prepared_statement(PG_FUNCTION_ARGS);
  
*** ./src/test/regress/input/constraints.source.orig	2009-07-11 18:17:41.000000000 +0100
--- ./src/test/regress/input/constraints.source	2009-07-11 18:59:44.000000000 +0100
***************
*** 259,261 ****
--- 259,345 ----
  
  DROP TABLE UNIQUE_TBL;
  
+ --
+ -- Deferrable unique constraints
+ --
+ 
+ CREATE TABLE UNIQUE_TBL (i int UNIQUE DEFERRABLE, t text);
+ 
+ INSERT INTO UNIQUE_TBL VALUES (0, 'one');
+ INSERT INTO UNIQUE_TBL VALUES (1, 'two');
+ INSERT INTO UNIQUE_TBL VALUES (2, 'tree');
+ INSERT INTO UNIQUE_TBL VALUES (3, 'four');
+ INSERT INTO UNIQUE_TBL VALUES (4, 'five');
+ 
+ -- default is immediate so this should fail
+ UPDATE UNIQUE_TBL SET i = 1 WHERE i = 0;
+ 
+ -- check is done at end of statement, so this should succeed
+ UPDATE UNIQUE_TBL SET i = i+1;
+ 
+ -- explicitly defer the constraint
+ BEGIN;
+ 
+ SET CONSTRAINTS UNIQUE_TBL_I_KEY DEFERRED;
+ 
+ INSERT INTO UNIQUE_TBL VALUES (3, 'three');
+ DELETE FROM UNIQUE_TBL WHERE t = 'tree'; -- makes constraint valid again
+ 
+ COMMIT; -- should succeed
+ 
+ SELECT '' AS five, * FROM UNIQUE_TBL;
+ 
+ -- initially deferred constraint
+ ALTER TABLE UNIQUE_TBL DROP CONSTRAINT UNIQUE_TBL_I_KEY;
+ ALTER TABLE UNIQUE_TBL ADD CONSTRAINT UNIQUE_TBL_I_KEY
+ 	UNIQUE (i) DEFERRABLE INITIALLY DEFERRED;
+ 
+ BEGIN;
+ 
+ INSERT INTO UNIQUE_TBL VALUES (1, 'five');
+ INSERT INTO UNIQUE_TBL VALUES (5, 'one');
+ UPDATE UNIQUE_TBL SET i = 4 WHERE i = 2;
+ UPDATE UNIQUE_TBL SET i = 2 WHERE i = 4 AND t = 'four';
+ DELETE FROM UNIQUE_TBL WHERE i = 1 AND t = 'one';
+ DELETE FROM UNIQUE_TBL WHERE i = 5 AND t = 'five';
+ 
+ COMMIT;
+ 
+ SELECT '' AS five, * FROM UNIQUE_TBL;
+ 
+ -- should fail at commit-time
+ BEGIN;
+ INSERT INTO UNIQUE_TBL VALUES (3, 'Three'); -- should succeed for now
+ COMMIT; -- should fail
+ 
+ -- make constraint check immediate
+ BEGIN;
+ 
+ SET CONSTRAINTS ALL IMMEDIATE;
+ INSERT INTO UNIQUE_TBL VALUES (3, 'Three'); -- should fail
+ 
+ COMMIT;
+ 
+ -- forced check when SET CONSTRAINTS is called
+ BEGIN;
+ 
+ SET CONSTRAINTS ALL DEFERRED;
+ 
+ INSERT INTO UNIQUE_TBL VALUES (3, 'Three'); -- should succeed for now
+ 
+ SET CONSTRAINTS ALL IMMEDIATE; -- should fail
+ 
+ COMMIT;
+ 
+ -- test a HOT update which invalidates the conflicting tuple, - the trigger
+ -- should still fire and catch the violation
+ 
+ BEGIN;
+ 
+ INSERT INTO UNIQUE_TBL VALUES (3, 'Three'); -- should succeed for now
+ UPDATE UNIQUE_TBL SET t = 'THREE' WHERE i = 3 AND t = 'Three';
+ 
+ COMMIT; -- should fail
+ 
+ DROP TABLE UNIQUE_TBL;
+ 
*** ./src/test/regress/output/constraints.source.orig	2009-07-11 19:07:40.000000000 +0100
--- ./src/test/regress/output/constraints.source	2009-07-11 19:08:46.000000000 +0100
***************
*** 375,377 ****
--- 375,457 ----
  (5 rows)
  
  DROP TABLE UNIQUE_TBL;
+ --
+ -- Deferrable unique constraints
+ --
+ CREATE TABLE UNIQUE_TBL (i int UNIQUE DEFERRABLE, t text);
+ NOTICE:  CREATE TABLE / UNIQUE will create implicit index "unique_tbl_i_key" for table "unique_tbl"
+ INSERT INTO UNIQUE_TBL VALUES (0, 'one');
+ INSERT INTO UNIQUE_TBL VALUES (1, 'two');
+ INSERT INTO UNIQUE_TBL VALUES (2, 'tree');
+ INSERT INTO UNIQUE_TBL VALUES (3, 'four');
+ INSERT INTO UNIQUE_TBL VALUES (4, 'five');
+ -- default is immediate so this should fail
+ UPDATE UNIQUE_TBL SET i = 1 WHERE i = 0;
+ ERROR:  duplicate key value violates unique constraint "unique_tbl_i_key"
+ -- check is done at end of statement, so this should succeed
+ UPDATE UNIQUE_TBL SET i = i+1;
+ -- explicitly defer the constraint
+ BEGIN;
+ SET CONSTRAINTS UNIQUE_TBL_I_KEY DEFERRED;
+ INSERT INTO UNIQUE_TBL VALUES (3, 'three');
+ DELETE FROM UNIQUE_TBL WHERE t = 'tree'; -- makes constraint valid again
+ COMMIT; -- should succeed
+ SELECT '' AS five, * FROM UNIQUE_TBL;
+  five | i |   t   
+ ------+---+-------
+       | 1 | one
+       | 2 | two
+       | 4 | four
+       | 5 | five
+       | 3 | three
+ (5 rows)
+ 
+ -- initially deferred constraint
+ ALTER TABLE UNIQUE_TBL DROP CONSTRAINT UNIQUE_TBL_I_KEY;
+ ALTER TABLE UNIQUE_TBL ADD CONSTRAINT UNIQUE_TBL_I_KEY
+ 	UNIQUE (i) DEFERRABLE INITIALLY DEFERRED;
+ NOTICE:  ALTER TABLE / ADD UNIQUE will create implicit index "unique_tbl_i_key" for table "unique_tbl"
+ BEGIN;
+ INSERT INTO UNIQUE_TBL VALUES (1, 'five');
+ INSERT INTO UNIQUE_TBL VALUES (5, 'one');
+ UPDATE UNIQUE_TBL SET i = 4 WHERE i = 2;
+ UPDATE UNIQUE_TBL SET i = 2 WHERE i = 4 AND t = 'four';
+ DELETE FROM UNIQUE_TBL WHERE i = 1 AND t = 'one';
+ DELETE FROM UNIQUE_TBL WHERE i = 5 AND t = 'five';
+ COMMIT;
+ SELECT '' AS five, * FROM UNIQUE_TBL;
+  five | i |   t   
+ ------+---+-------
+       | 3 | three
+       | 1 | five
+       | 5 | one
+       | 4 | two
+       | 2 | four
+ (5 rows)
+ 
+ -- should fail at commit-time
+ BEGIN;
+ INSERT INTO UNIQUE_TBL VALUES (3, 'Three'); -- should succeed for now
+ COMMIT; -- should fail
+ ERROR:  duplicate key value violates unique constraint "unique_tbl_i_key"
+ -- make constraint check immediate
+ BEGIN;
+ SET CONSTRAINTS ALL IMMEDIATE;
+ INSERT INTO UNIQUE_TBL VALUES (3, 'Three'); -- should fail
+ ERROR:  duplicate key value violates unique constraint "unique_tbl_i_key"
+ COMMIT;
+ -- forced check when SET CONSTRAINTS is called
+ BEGIN;
+ SET CONSTRAINTS ALL DEFERRED;
+ INSERT INTO UNIQUE_TBL VALUES (3, 'Three'); -- should succeed for now
+ SET CONSTRAINTS ALL IMMEDIATE; -- should fail
+ ERROR:  duplicate key value violates unique constraint "unique_tbl_i_key"
+ COMMIT;
+ -- test a HOT update which invalidates the conflicting tuple, - the trigger
+ -- should still fire and catch the violation
+ BEGIN;
+ INSERT INTO UNIQUE_TBL VALUES (3, 'Three'); -- should succeed for now
+ UPDATE UNIQUE_TBL SET t = 'THREE' WHERE i = 3 AND t = 'Three';
+ COMMIT; -- should fail
+ ERROR:  duplicate key value violates unique constraint "unique_tbl_i_key"
+ DROP TABLE UNIQUE_TBL;
