PostgreSQL Source Code  git master
execIndexing.c File Reference
#include "postgres.h"
#include "access/genam.h"
#include "access/relscan.h"
#include "access/tableam.h"
#include "access/xact.h"
#include "catalog/index.h"
#include "executor/executor.h"
#include "nodes/nodeFuncs.h"
#include "storage/lmgr.h"
#include "utils/snapmgr.h"
Include dependency graph for execIndexing.c:

Go to the source code of this file.

Enumerations

enum  CEOUC_WAIT_MODE { CEOUC_WAIT, CEOUC_NOWAIT, CEOUC_LIVELOCK_PREVENTING_WAIT }
 

Functions

static bool check_exclusion_or_unique_constraint (Relation heap, Relation index, IndexInfo *indexInfo, ItemPointer tupleid, Datum *values, bool *isnull, EState *estate, bool newIndex, CEOUC_WAIT_MODE waitMode, bool errorOK, ItemPointer conflictTid)
 
static bool index_recheck_constraint (Relation index, Oid *constr_procs, Datum *existing_values, bool *existing_isnull, Datum *new_values)
 
void ExecOpenIndices (ResultRelInfo *resultRelInfo, bool speculative)
 
void ExecCloseIndices (ResultRelInfo *resultRelInfo)
 
ListExecInsertIndexTuples (ResultRelInfo *resultRelInfo, TupleTableSlot *slot, EState *estate, bool noDupErr, bool *specConflict, List *arbiterIndexes)
 
bool ExecCheckIndexConstraints (ResultRelInfo *resultRelInfo, TupleTableSlot *slot, EState *estate, ItemPointer conflictTid, List *arbiterIndexes)
 
void check_exclusion_constraint (Relation heap, Relation index, IndexInfo *indexInfo, ItemPointer tupleid, Datum *values, bool *isnull, EState *estate, bool newIndex)
 

Enumeration Type Documentation

◆ CEOUC_WAIT_MODE

Enumerator
CEOUC_WAIT 
CEOUC_NOWAIT 
CEOUC_LIVELOCK_PREVENTING_WAIT 

Definition at line 120 of file execIndexing.c.

Function Documentation

◆ check_exclusion_constraint()

void check_exclusion_constraint ( Relation  heap,
Relation  index,
IndexInfo indexInfo,
ItemPointer  tupleid,
Datum values,
bool isnull,
EState estate,
bool  newIndex 
)

Definition at line 863 of file execIndexing.c.

References CEOUC_WAIT, and check_exclusion_or_unique_constraint().

Referenced by exec_rt_fetch(), IndexCheckExclusion(), and unique_key_recheck().

868 {
869  (void) check_exclusion_or_unique_constraint(heap, index, indexInfo, tupleid,
870  values, isnull,
871  estate, newIndex,
872  CEOUC_WAIT, false, NULL);
873 }
static bool check_exclusion_or_unique_constraint(Relation heap, Relation index, IndexInfo *indexInfo, ItemPointer tupleid, Datum *values, bool *isnull, EState *estate, bool newIndex, CEOUC_WAIT_MODE waitMode, bool errorOK, ItemPointer conflictTid)
Definition: execIndexing.c:643
static Datum values[MAXATTR]
Definition: bootstrap.c:165

◆ check_exclusion_or_unique_constraint()

static bool check_exclusion_or_unique_constraint ( Relation  heap,
Relation  index,
IndexInfo indexInfo,
ItemPointer  tupleid,
Datum values,
bool isnull,
EState estate,
bool  newIndex,
CEOUC_WAIT_MODE  waitMode,
bool  errorOK,
ItemPointer  conflictTid 
)
static

Definition at line 643 of file execIndexing.c.

References BuildIndexValueDescription(), CEOUC_LIVELOCK_PREVENTING_WAIT, CEOUC_WAIT, ExprContext::ecxt_scantuple, elog, ereport, errcode(), errdetail(), errmsg(), ERROR, errtableconstraint(), ExecDropSingleTupleTableSlot(), FormIndexDatum(), ForwardScanDirection, GetCurrentTransactionId(), GetPerTupleExprContext, i, IndexInfo::ii_ExclusionOps, IndexInfo::ii_ExclusionProcs, IndexInfo::ii_ExclusionStrats, IndexInfo::ii_UniqueProcs, IndexInfo::ii_UniqueStrats, index_beginscan(), index_endscan(), index_getnext_slot(), INDEX_MAX_KEYS, index_recheck_constraint(), index_rescan(), IndexRelationGetNumberOfKeyAttributes, InitDirtySnapshot, InvalidOid, ItemPointerEquals(), ItemPointerIsValid, RelationData::rd_indcollation, RelationGetRelationName, ScanKeyEntryInitialize(), SpeculativeInsertionWait(), SnapshotData::speculativeToken, table_slot_create(), TransactionIdIsValid, TransactionIdPrecedes(), TupleTableSlot::tts_tid, XactLockTableWait(), XLTW_InsertIndex, XLTW_RecheckExclusionConstr, SnapshotData::xmax, SnapshotData::xmin, and IndexScanDescData::xs_recheck.

Referenced by check_exclusion_constraint(), ExecCheckIndexConstraints(), and ExecInsertIndexTuples().

651 {
652  Oid *constr_procs;
653  uint16 *constr_strats;
654  Oid *index_collations = index->rd_indcollation;
655  int indnkeyatts = IndexRelationGetNumberOfKeyAttributes(index);
656  IndexScanDesc index_scan;
657  ScanKeyData scankeys[INDEX_MAX_KEYS];
658  SnapshotData DirtySnapshot;
659  int i;
660  bool conflict;
661  bool found_self;
662  ExprContext *econtext;
663  TupleTableSlot *existing_slot;
664  TupleTableSlot *save_scantuple;
665 
666  if (indexInfo->ii_ExclusionOps)
667  {
668  constr_procs = indexInfo->ii_ExclusionProcs;
669  constr_strats = indexInfo->ii_ExclusionStrats;
670  }
671  else
672  {
673  constr_procs = indexInfo->ii_UniqueProcs;
674  constr_strats = indexInfo->ii_UniqueStrats;
675  }
676 
677  /*
678  * If any of the input values are NULL, the constraint check is assumed to
679  * pass (i.e., we assume the operators are strict).
680  */
681  for (i = 0; i < indnkeyatts; i++)
682  {
683  if (isnull[i])
684  return true;
685  }
686 
687  /*
688  * Search the tuples that are in the index for any violations, including
689  * tuples that aren't visible yet.
690  */
691  InitDirtySnapshot(DirtySnapshot);
692 
693  for (i = 0; i < indnkeyatts; i++)
694  {
695  ScanKeyEntryInitialize(&scankeys[i],
696  0,
697  i + 1,
698  constr_strats[i],
699  InvalidOid,
700  index_collations[i],
701  constr_procs[i],
702  values[i]);
703  }
704 
705  /*
706  * Need a TupleTableSlot to put existing tuples in.
707  *
708  * To use FormIndexDatum, we have to make the econtext's scantuple point
709  * to this slot. Be sure to save and restore caller's value for
710  * scantuple.
711  */
712  existing_slot = table_slot_create(heap, NULL);
713 
714  econtext = GetPerTupleExprContext(estate);
715  save_scantuple = econtext->ecxt_scantuple;
716  econtext->ecxt_scantuple = existing_slot;
717 
718  /*
719  * May have to restart scan from this point if a potential conflict is
720  * found.
721  */
722 retry:
723  conflict = false;
724  found_self = false;
725  index_scan = index_beginscan(heap, index, &DirtySnapshot, indnkeyatts, 0);
726  index_rescan(index_scan, scankeys, indnkeyatts, NULL, 0);
727 
728  while (index_getnext_slot(index_scan, ForwardScanDirection, existing_slot))
729  {
730  TransactionId xwait;
731  XLTW_Oper reason_wait;
732  Datum existing_values[INDEX_MAX_KEYS];
733  bool existing_isnull[INDEX_MAX_KEYS];
734  char *error_new;
735  char *error_existing;
736 
737  /*
738  * Ignore the entry for the tuple we're trying to check.
739  */
740  if (ItemPointerIsValid(tupleid) &&
741  ItemPointerEquals(tupleid, &existing_slot->tts_tid))
742  {
743  if (found_self) /* should not happen */
744  elog(ERROR, "found self tuple multiple times in index \"%s\"",
745  RelationGetRelationName(index));
746  found_self = true;
747  continue;
748  }
749 
750  /*
751  * Extract the index column values and isnull flags from the existing
752  * tuple.
753  */
754  FormIndexDatum(indexInfo, existing_slot, estate,
755  existing_values, existing_isnull);
756 
757  /* If lossy indexscan, must recheck the condition */
758  if (index_scan->xs_recheck)
759  {
760  if (!index_recheck_constraint(index,
761  constr_procs,
762  existing_values,
763  existing_isnull,
764  values))
765  continue; /* tuple doesn't actually match, so no
766  * conflict */
767  }
768 
769  /*
770  * At this point we have either a conflict or a potential conflict.
771  *
772  * If an in-progress transaction is affecting the visibility of this
773  * tuple, we need to wait for it to complete and then recheck (unless
774  * the caller requested not to). For simplicity we do rechecking by
775  * just restarting the whole scan --- this case probably doesn't
776  * happen often enough to be worth trying harder, and anyway we don't
777  * want to hold any index internal locks while waiting.
778  */
779  xwait = TransactionIdIsValid(DirtySnapshot.xmin) ?
780  DirtySnapshot.xmin : DirtySnapshot.xmax;
781 
782  if (TransactionIdIsValid(xwait) &&
783  (waitMode == CEOUC_WAIT ||
784  (waitMode == CEOUC_LIVELOCK_PREVENTING_WAIT &&
785  DirtySnapshot.speculativeToken &&
787  {
788  reason_wait = indexInfo->ii_ExclusionOps ?
790  index_endscan(index_scan);
791  if (DirtySnapshot.speculativeToken)
792  SpeculativeInsertionWait(DirtySnapshot.xmin,
793  DirtySnapshot.speculativeToken);
794  else
795  XactLockTableWait(xwait, heap,
796  &existing_slot->tts_tid, reason_wait);
797  goto retry;
798  }
799 
800  /*
801  * We have a definite conflict (or a potential one, but the caller
802  * didn't want to wait). Return it to caller, or report it.
803  */
804  if (violationOK)
805  {
806  conflict = true;
807  if (conflictTid)
808  *conflictTid = existing_slot->tts_tid;
809  break;
810  }
811 
812  error_new = BuildIndexValueDescription(index, values, isnull);
813  error_existing = BuildIndexValueDescription(index, existing_values,
814  existing_isnull);
815  if (newIndex)
816  ereport(ERROR,
817  (errcode(ERRCODE_EXCLUSION_VIOLATION),
818  errmsg("could not create exclusion constraint \"%s\"",
819  RelationGetRelationName(index)),
820  error_new && error_existing ?
821  errdetail("Key %s conflicts with key %s.",
822  error_new, error_existing) :
823  errdetail("Key conflicts exist."),
824  errtableconstraint(heap,
825  RelationGetRelationName(index))));
826  else
827  ereport(ERROR,
828  (errcode(ERRCODE_EXCLUSION_VIOLATION),
829  errmsg("conflicting key value violates exclusion constraint \"%s\"",
830  RelationGetRelationName(index)),
831  error_new && error_existing ?
832  errdetail("Key %s conflicts with existing key %s.",
833  error_new, error_existing) :
834  errdetail("Key conflicts with existing key."),
835  errtableconstraint(heap,
836  RelationGetRelationName(index))));
837  }
838 
839  index_endscan(index_scan);
840 
841  /*
842  * Ordinarily, at this point the search should have found the originally
843  * inserted tuple (if any), unless we exited the loop early because of
844  * conflict. However, it is possible to define exclusion constraints for
845  * which that wouldn't be true --- for instance, if the operator is <>. So
846  * we no longer complain if found_self is still false.
847  */
848 
849  econtext->ecxt_scantuple = save_scantuple;
850 
851  ExecDropSingleTupleTableSlot(existing_slot);
852 
853  return !conflict;
854 }
TupleTableSlot * table_slot_create(Relation relation, List **reglist)
Definition: tableam.c:91
#define ItemPointerIsValid(pointer)
Definition: itemptr.h:82
void FormIndexDatum(IndexInfo *indexInfo, TupleTableSlot *slot, EState *estate, Datum *values, bool *isnull)
Definition: index.c:2585
uint16 * ii_UniqueStrats
Definition: execnodes.h:169
#define InitDirtySnapshot(snapshotdata)
Definition: snapmgr.h:75
uint32 TransactionId
Definition: c.h:521
void index_rescan(IndexScanDesc scan, ScanKey keys, int nkeys, ScanKey orderbys, int norderbys)
Definition: indexam.c:295
Oid * ii_ExclusionProcs
Definition: execnodes.h:165
int errcode(int sqlerrcode)
Definition: elog.c:610
unsigned int Oid
Definition: postgres_ext.h:31
#define GetPerTupleExprContext(estate)
Definition: executor.h:509
int errtableconstraint(Relation rel, const char *conname)
Definition: relcache.c:5551
unsigned short uint16
Definition: c.h:374
Oid * rd_indcollation
Definition: rel.h:199
static bool index_recheck_constraint(Relation index, Oid *constr_procs, Datum *existing_values, bool *existing_isnull, Datum *new_values)
Definition: execIndexing.c:880
#define ERROR
Definition: elog.h:43
void SpeculativeInsertionWait(TransactionId xid, uint32 token)
Definition: lmgr.c:796
TransactionId GetCurrentTransactionId(void)
Definition: xact.c:438
void ScanKeyEntryInitialize(ScanKey entry, int flags, AttrNumber attributeNumber, StrategyNumber strategy, Oid subtype, Oid collation, RegProcedure procedure, Datum argument)
Definition: scankey.c:32
void ExecDropSingleTupleTableSlot(TupleTableSlot *slot)
Definition: execTuples.c:1224
Oid * ii_UniqueProcs
Definition: execnodes.h:168
int errdetail(const char *fmt,...)
Definition: elog.c:954
#define RelationGetRelationName(relation)
Definition: rel.h:490
TransactionId xmax
Definition: snapshot.h:158
TransactionId xmin
Definition: snapshot.h:157
#define IndexRelationGetNumberOfKeyAttributes(relation)
Definition: rel.h:475
void index_endscan(IndexScanDesc scan)
Definition: indexam.c:321
bool TransactionIdPrecedes(TransactionId id1, TransactionId id2)
Definition: transam.c:300
uintptr_t Datum
Definition: postgres.h:367
#define InvalidOid
Definition: postgres_ext.h:36
#define ereport(elevel,...)
Definition: elog.h:144
uint32 speculativeToken
Definition: snapshot.h:193
void XactLockTableWait(TransactionId xid, Relation rel, ItemPointer ctid, XLTW_Oper oper)
Definition: lmgr.c:639
#define INDEX_MAX_KEYS
bool index_getnext_slot(IndexScanDesc scan, ScanDirection direction, TupleTableSlot *slot)
Definition: indexam.c:614
TupleTableSlot * ecxt_scantuple
Definition: execnodes.h:225
bool ItemPointerEquals(ItemPointer pointer1, ItemPointer pointer2)
Definition: itemptr.c:29
static Datum values[MAXATTR]
Definition: bootstrap.c:165
XLTW_Oper
Definition: lmgr.h:24
Oid * ii_ExclusionOps
Definition: execnodes.h:164
int errmsg(const char *fmt,...)
Definition: elog.c:821
#define elog(elevel,...)
Definition: elog.h:214
int i
char * BuildIndexValueDescription(Relation indexRelation, Datum *values, bool *isnull)
Definition: genam.c:177
#define TransactionIdIsValid(xid)
Definition: transam.h:41
uint16 * ii_ExclusionStrats
Definition: execnodes.h:166
ItemPointerData tts_tid
Definition: tuptable.h:130
IndexScanDesc index_beginscan(Relation heapRelation, Relation indexRelation, Snapshot snapshot, int nkeys, int norderbys)
Definition: indexam.c:203

◆ ExecCheckIndexConstraints()

bool ExecCheckIndexConstraints ( ResultRelInfo resultRelInfo,
TupleTableSlot slot,
EState estate,
ItemPointer  conflictTid,
List arbiterIndexes 
)

Definition at line 481 of file execIndexing.c.

References CEOUC_WAIT, check_exclusion_or_unique_constraint(), ExprContext::ecxt_scantuple, elog, ereport, errcode(), errmsg(), ERROR, errtableconstraint(), ExecPrepareQual(), ExecQual(), FormIndexDatum(), GetPerTupleExprContext, i, IndexInfo::ii_ExclusionOps, IndexInfo::ii_Predicate, IndexInfo::ii_PredicateState, IndexInfo::ii_ReadyForInserts, IndexInfo::ii_Unique, INDEX_MAX_KEYS, ItemPointerSetInvalid, list_member_oid(), NIL, RelationData::rd_index, RelationGetRelationName, ResultRelInfo::ri_IndexRelationDescs, ResultRelInfo::ri_IndexRelationInfo, ResultRelInfo::ri_NumIndices, ResultRelInfo::ri_RelationDesc, and values.

Referenced by exec_rt_fetch(), and ExecInsert().

484 {
485  int i;
486  int numIndices;
487  RelationPtr relationDescs;
488  Relation heapRelation;
489  IndexInfo **indexInfoArray;
490  ExprContext *econtext;
492  bool isnull[INDEX_MAX_KEYS];
493  ItemPointerData invalidItemPtr;
494  bool checkedIndex = false;
495 
496  ItemPointerSetInvalid(conflictTid);
497  ItemPointerSetInvalid(&invalidItemPtr);
498 
499  /*
500  * Get information from the result relation info structure.
501  */
502  numIndices = resultRelInfo->ri_NumIndices;
503  relationDescs = resultRelInfo->ri_IndexRelationDescs;
504  indexInfoArray = resultRelInfo->ri_IndexRelationInfo;
505  heapRelation = resultRelInfo->ri_RelationDesc;
506 
507  /*
508  * We will use the EState's per-tuple context for evaluating predicates
509  * and index expressions (creating it if it's not already there).
510  */
511  econtext = GetPerTupleExprContext(estate);
512 
513  /* Arrange for econtext's scan tuple to be the tuple under test */
514  econtext->ecxt_scantuple = slot;
515 
516  /*
517  * For each index, form index tuple and check if it satisfies the
518  * constraint.
519  */
520  for (i = 0; i < numIndices; i++)
521  {
522  Relation indexRelation = relationDescs[i];
523  IndexInfo *indexInfo;
524  bool satisfiesConstraint;
525 
526  if (indexRelation == NULL)
527  continue;
528 
529  indexInfo = indexInfoArray[i];
530 
531  if (!indexInfo->ii_Unique && !indexInfo->ii_ExclusionOps)
532  continue;
533 
534  /* If the index is marked as read-only, ignore it */
535  if (!indexInfo->ii_ReadyForInserts)
536  continue;
537 
538  /* When specific arbiter indexes requested, only examine them */
539  if (arbiterIndexes != NIL &&
540  !list_member_oid(arbiterIndexes,
541  indexRelation->rd_index->indexrelid))
542  continue;
543 
544  if (!indexRelation->rd_index->indimmediate)
545  ereport(ERROR,
546  (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
547  errmsg("ON CONFLICT does not support deferrable unique constraints/exclusion constraints as arbiters"),
548  errtableconstraint(heapRelation,
549  RelationGetRelationName(indexRelation))));
550 
551  checkedIndex = true;
552 
553  /* Check for partial index */
554  if (indexInfo->ii_Predicate != NIL)
555  {
556  ExprState *predicate;
557 
558  /*
559  * If predicate state not set up yet, create it (in the estate's
560  * per-query context)
561  */
562  predicate = indexInfo->ii_PredicateState;
563  if (predicate == NULL)
564  {
565  predicate = ExecPrepareQual(indexInfo->ii_Predicate, estate);
566  indexInfo->ii_PredicateState = predicate;
567  }
568 
569  /* Skip this index-update if the predicate isn't satisfied */
570  if (!ExecQual(predicate, econtext))
571  continue;
572  }
573 
574  /*
575  * FormIndexDatum fills in its values and isnull parameters with the
576  * appropriate values for the column(s) of the index.
577  */
578  FormIndexDatum(indexInfo,
579  slot,
580  estate,
581  values,
582  isnull);
583 
584  satisfiesConstraint =
585  check_exclusion_or_unique_constraint(heapRelation, indexRelation,
586  indexInfo, &invalidItemPtr,
587  values, isnull, estate, false,
588  CEOUC_WAIT, true,
589  conflictTid);
590  if (!satisfiesConstraint)
591  return false;
592  }
593 
594  if (arbiterIndexes != NIL && !checkedIndex)
595  elog(ERROR, "unexpected failure to find arbiter index");
596 
597  return true;
598 }
void FormIndexDatum(IndexInfo *indexInfo, TupleTableSlot *slot, EState *estate, Datum *values, bool *isnull)
Definition: index.c:2585
int ri_NumIndices
Definition: execnodes.h:415
#define NIL
Definition: pg_list.h:65
Relation ri_RelationDesc
Definition: execnodes.h:412
List * ii_Predicate
Definition: execnodes.h:162
ExprState * ii_PredicateState
Definition: execnodes.h:163
int errcode(int sqlerrcode)
Definition: elog.c:610
static bool ExecQual(ExprState *state, ExprContext *econtext)
Definition: executor.h:372
static bool check_exclusion_or_unique_constraint(Relation heap, Relation index, IndexInfo *indexInfo, ItemPointer tupleid, Datum *values, bool *isnull, EState *estate, bool newIndex, CEOUC_WAIT_MODE waitMode, bool errorOK, ItemPointer conflictTid)
Definition: execIndexing.c:643
#define GetPerTupleExprContext(estate)
Definition: executor.h:509
int errtableconstraint(Relation rel, const char *conname)
Definition: relcache.c:5551
Form_pg_index rd_index
Definition: rel.h:174
#define ERROR
Definition: elog.h:43
#define RelationGetRelationName(relation)
Definition: rel.h:490
ExprState * ExecPrepareQual(List *qual, EState *estate)
Definition: execExpr.c:520
bool ii_ReadyForInserts
Definition: execnodes.h:172
uintptr_t Datum
Definition: postgres.h:367
#define ereport(elevel,...)
Definition: elog.h:144
bool ii_Unique
Definition: execnodes.h:171
bool list_member_oid(const List *list, Oid datum)
Definition: list.c:674
#define INDEX_MAX_KEYS
TupleTableSlot * ecxt_scantuple
Definition: execnodes.h:225
static Datum values[MAXATTR]
Definition: bootstrap.c:165
#define ItemPointerSetInvalid(pointer)
Definition: itemptr.h:172
Oid * ii_ExclusionOps
Definition: execnodes.h:164
int errmsg(const char *fmt,...)
Definition: elog.c:821
#define elog(elevel,...)
Definition: elog.h:214
IndexInfo ** ri_IndexRelationInfo
Definition: execnodes.h:421
int i
RelationPtr ri_IndexRelationDescs
Definition: execnodes.h:418

◆ ExecCloseIndices()

void ExecCloseIndices ( ResultRelInfo resultRelInfo)

Definition at line 226 of file execIndexing.c.

References i, index_close(), ResultRelInfo::ri_IndexRelationDescs, ResultRelInfo::ri_NumIndices, and RowExclusiveLock.

Referenced by apply_handle_delete_internal(), apply_handle_insert_internal(), apply_handle_tuple_routing(), apply_handle_update_internal(), CatalogCloseIndexes(), exec_rt_fetch(), ExecCleanupTupleRouting(), and ExecCloseResultRelations().

227 {
228  int i;
229  int numIndices;
230  RelationPtr indexDescs;
231 
232  numIndices = resultRelInfo->ri_NumIndices;
233  indexDescs = resultRelInfo->ri_IndexRelationDescs;
234 
235  for (i = 0; i < numIndices; i++)
236  {
237  if (indexDescs[i] == NULL)
238  continue; /* shouldn't happen? */
239 
240  /* Drop lock acquired by ExecOpenIndices */
241  index_close(indexDescs[i], RowExclusiveLock);
242  }
243 
244  /*
245  * XXX should free indexInfo array here too? Currently we assume that
246  * such stuff will be cleaned up automatically in FreeExecutorState.
247  */
248 }
int ri_NumIndices
Definition: execnodes.h:415
#define RowExclusiveLock
Definition: lockdefs.h:38
void index_close(Relation relation, LOCKMODE lockmode)
Definition: indexam.c:158
int i
RelationPtr ri_IndexRelationDescs
Definition: execnodes.h:418

◆ ExecInsertIndexTuples()

List* ExecInsertIndexTuples ( ResultRelInfo resultRelInfo,
TupleTableSlot slot,
EState estate,
bool  noDupErr,
bool specConflict,
List arbiterIndexes 
)

Definition at line 273 of file execIndexing.c.

References Assert, CEOUC_LIVELOCK_PREVENTING_WAIT, CEOUC_NOWAIT, CEOUC_WAIT, check_exclusion_or_unique_constraint(), ExprContext::ecxt_scantuple, ExecPrepareQual(), ExecQual(), FormIndexDatum(), GetPerTupleExprContext, i, IndexInfo::ii_ExclusionOps, IndexInfo::ii_Predicate, IndexInfo::ii_PredicateState, IndexInfo::ii_ReadyForInserts, index_insert(), INDEX_MAX_KEYS, ItemPointerIsValid, lappend_oid(), list_member_oid(), NIL, RelationData::rd_index, RelationGetRelid, ResultRelInfo::ri_IndexRelationDescs, ResultRelInfo::ri_IndexRelationInfo, ResultRelInfo::ri_NumIndices, ResultRelInfo::ri_RelationDesc, TupleTableSlot::tts_tableOid, TupleTableSlot::tts_tid, UNIQUE_CHECK_NO, UNIQUE_CHECK_PARTIAL, UNIQUE_CHECK_YES, and values.

Referenced by CopyFrom(), CopyMultiInsertBufferFlush(), exec_rt_fetch(), ExecInsert(), ExecSimpleRelationInsert(), ExecSimpleRelationUpdate(), and ExecUpdate().

279 {
280  ItemPointer tupleid = &slot->tts_tid;
281  List *result = NIL;
282  int i;
283  int numIndices;
284  RelationPtr relationDescs;
285  Relation heapRelation;
286  IndexInfo **indexInfoArray;
287  ExprContext *econtext;
289  bool isnull[INDEX_MAX_KEYS];
290 
291  Assert(ItemPointerIsValid(tupleid));
292 
293  /*
294  * Get information from the result relation info structure.
295  */
296  numIndices = resultRelInfo->ri_NumIndices;
297  relationDescs = resultRelInfo->ri_IndexRelationDescs;
298  indexInfoArray = resultRelInfo->ri_IndexRelationInfo;
299  heapRelation = resultRelInfo->ri_RelationDesc;
300 
301  /* Sanity check: slot must belong to the same rel as the resultRelInfo. */
302  Assert(slot->tts_tableOid == RelationGetRelid(heapRelation));
303 
304  /*
305  * We will use the EState's per-tuple context for evaluating predicates
306  * and index expressions (creating it if it's not already there).
307  */
308  econtext = GetPerTupleExprContext(estate);
309 
310  /* Arrange for econtext's scan tuple to be the tuple under test */
311  econtext->ecxt_scantuple = slot;
312 
313  /*
314  * for each index, form and insert the index tuple
315  */
316  for (i = 0; i < numIndices; i++)
317  {
318  Relation indexRelation = relationDescs[i];
319  IndexInfo *indexInfo;
320  bool applyNoDupErr;
321  IndexUniqueCheck checkUnique;
322  bool satisfiesConstraint;
323 
324  if (indexRelation == NULL)
325  continue;
326 
327  indexInfo = indexInfoArray[i];
328 
329  /* If the index is marked as read-only, ignore it */
330  if (!indexInfo->ii_ReadyForInserts)
331  continue;
332 
333  /* Check for partial index */
334  if (indexInfo->ii_Predicate != NIL)
335  {
336  ExprState *predicate;
337 
338  /*
339  * If predicate state not set up yet, create it (in the estate's
340  * per-query context)
341  */
342  predicate = indexInfo->ii_PredicateState;
343  if (predicate == NULL)
344  {
345  predicate = ExecPrepareQual(indexInfo->ii_Predicate, estate);
346  indexInfo->ii_PredicateState = predicate;
347  }
348 
349  /* Skip this index-update if the predicate isn't satisfied */
350  if (!ExecQual(predicate, econtext))
351  continue;
352  }
353 
354  /*
355  * FormIndexDatum fills in its values and isnull parameters with the
356  * appropriate values for the column(s) of the index.
357  */
358  FormIndexDatum(indexInfo,
359  slot,
360  estate,
361  values,
362  isnull);
363 
364  /* Check whether to apply noDupErr to this index */
365  applyNoDupErr = noDupErr &&
366  (arbiterIndexes == NIL ||
367  list_member_oid(arbiterIndexes,
368  indexRelation->rd_index->indexrelid));
369 
370  /*
371  * The index AM does the actual insertion, plus uniqueness checking.
372  *
373  * For an immediate-mode unique index, we just tell the index AM to
374  * throw error if not unique.
375  *
376  * For a deferrable unique index, we tell the index AM to just detect
377  * possible non-uniqueness, and we add the index OID to the result
378  * list if further checking is needed.
379  *
380  * For a speculative insertion (used by INSERT ... ON CONFLICT), do
381  * the same as for a deferrable unique index.
382  */
383  if (!indexRelation->rd_index->indisunique)
384  checkUnique = UNIQUE_CHECK_NO;
385  else if (applyNoDupErr)
386  checkUnique = UNIQUE_CHECK_PARTIAL;
387  else if (indexRelation->rd_index->indimmediate)
388  checkUnique = UNIQUE_CHECK_YES;
389  else
390  checkUnique = UNIQUE_CHECK_PARTIAL;
391 
392  satisfiesConstraint =
393  index_insert(indexRelation, /* index relation */
394  values, /* array of index Datums */
395  isnull, /* null flags */
396  tupleid, /* tid of heap tuple */
397  heapRelation, /* heap relation */
398  checkUnique, /* type of uniqueness check to do */
399  indexInfo); /* index AM may need this */
400 
401  /*
402  * If the index has an associated exclusion constraint, check that.
403  * This is simpler than the process for uniqueness checks since we
404  * always insert first and then check. If the constraint is deferred,
405  * we check now anyway, but don't throw error on violation or wait for
406  * a conclusive outcome from a concurrent insertion; instead we'll
407  * queue a recheck event. Similarly, noDupErr callers (speculative
408  * inserters) will recheck later, and wait for a conclusive outcome
409  * then.
410  *
411  * An index for an exclusion constraint can't also be UNIQUE (not an
412  * essential property, we just don't allow it in the grammar), so no
413  * need to preserve the prior state of satisfiesConstraint.
414  */
415  if (indexInfo->ii_ExclusionOps != NULL)
416  {
417  bool violationOK;
418  CEOUC_WAIT_MODE waitMode;
419 
420  if (applyNoDupErr)
421  {
422  violationOK = true;
424  }
425  else if (!indexRelation->rd_index->indimmediate)
426  {
427  violationOK = true;
428  waitMode = CEOUC_NOWAIT;
429  }
430  else
431  {
432  violationOK = false;
433  waitMode = CEOUC_WAIT;
434  }
435 
436  satisfiesConstraint =
438  indexRelation, indexInfo,
439  tupleid, values, isnull,
440  estate, false,
441  waitMode, violationOK, NULL);
442  }
443 
444  if ((checkUnique == UNIQUE_CHECK_PARTIAL ||
445  indexInfo->ii_ExclusionOps != NULL) &&
446  !satisfiesConstraint)
447  {
448  /*
449  * The tuple potentially violates the uniqueness or exclusion
450  * constraint, so make a note of the index so that we can re-check
451  * it later. Speculative inserters are told if there was a
452  * speculative conflict, since that always requires a restart.
453  */
454  result = lappend_oid(result, RelationGetRelid(indexRelation));
455  if (indexRelation->rd_index->indimmediate && specConflict)
456  *specConflict = true;
457  }
458  }
459 
460  return result;
461 }
#define ItemPointerIsValid(pointer)
Definition: itemptr.h:82
void FormIndexDatum(IndexInfo *indexInfo, TupleTableSlot *slot, EState *estate, Datum *values, bool *isnull)
Definition: index.c:2585
int ri_NumIndices
Definition: execnodes.h:415
#define NIL
Definition: pg_list.h:65
Oid tts_tableOid
Definition: tuptable.h:131
Relation ri_RelationDesc
Definition: execnodes.h:412
List * ii_Predicate
Definition: execnodes.h:162
ExprState * ii_PredicateState
Definition: execnodes.h:163
static bool ExecQual(ExprState *state, ExprContext *econtext)
Definition: executor.h:372
List * lappend_oid(List *list, Oid datum)
Definition: list.c:357
static bool check_exclusion_or_unique_constraint(Relation heap, Relation index, IndexInfo *indexInfo, ItemPointer tupleid, Datum *values, bool *isnull, EState *estate, bool newIndex, CEOUC_WAIT_MODE waitMode, bool errorOK, ItemPointer conflictTid)
Definition: execIndexing.c:643
IndexUniqueCheck
Definition: genam.h:112
#define GetPerTupleExprContext(estate)
Definition: executor.h:509
Form_pg_index rd_index
Definition: rel.h:174
ExprState * ExecPrepareQual(List *qual, EState *estate)
Definition: execExpr.c:520
bool ii_ReadyForInserts
Definition: execnodes.h:172
uintptr_t Datum
Definition: postgres.h:367
bool list_member_oid(const List *list, Oid datum)
Definition: list.c:674
#define Assert(condition)
Definition: c.h:746
#define INDEX_MAX_KEYS
TupleTableSlot * ecxt_scantuple
Definition: execnodes.h:225
static Datum values[MAXATTR]
Definition: bootstrap.c:165
Oid * ii_ExclusionOps
Definition: execnodes.h:164
IndexInfo ** ri_IndexRelationInfo
Definition: execnodes.h:421
int i
CEOUC_WAIT_MODE
Definition: execIndexing.c:120
Definition: pg_list.h:50
ItemPointerData tts_tid
Definition: tuptable.h:130
#define RelationGetRelid(relation)
Definition: rel.h:456
RelationPtr ri_IndexRelationDescs
Definition: execnodes.h:418
bool index_insert(Relation indexRelation, Datum *values, bool *isnull, ItemPointer heap_t_ctid, Relation heapRelation, IndexUniqueCheck checkUnique, IndexInfo *indexInfo)
Definition: indexam.c:176

◆ ExecOpenIndices()

void ExecOpenIndices ( ResultRelInfo resultRelInfo,
bool  speculative 
)

Definition at line 151 of file execIndexing.c.

References BuildIndexInfo(), BuildSpeculativeIndexInfo(), i, IndexInfo::ii_Unique, index_open(), lfirst_oid, list_free(), list_length(), palloc(), RelationGetForm, RelationGetIndexList(), ResultRelInfo::ri_IndexRelationDescs, ResultRelInfo::ri_IndexRelationInfo, ResultRelInfo::ri_NumIndices, ResultRelInfo::ri_RelationDesc, and RowExclusiveLock.

Referenced by apply_handle_delete_internal(), apply_handle_insert_internal(), apply_handle_tuple_routing(), apply_handle_update_internal(), CatalogOpenIndexes(), CopyFrom(), exec_rt_fetch(), ExecInitModifyTable(), and ExecInitPartitionInfo().

152 {
153  Relation resultRelation = resultRelInfo->ri_RelationDesc;
154  List *indexoidlist;
155  ListCell *l;
156  int len,
157  i;
158  RelationPtr relationDescs;
159  IndexInfo **indexInfoArray;
160 
161  resultRelInfo->ri_NumIndices = 0;
162 
163  /* fast path if no indexes */
164  if (!RelationGetForm(resultRelation)->relhasindex)
165  return;
166 
167  /*
168  * Get cached list of index OIDs
169  */
170  indexoidlist = RelationGetIndexList(resultRelation);
171  len = list_length(indexoidlist);
172  if (len == 0)
173  return;
174 
175  /*
176  * allocate space for result arrays
177  */
178  relationDescs = (RelationPtr) palloc(len * sizeof(Relation));
179  indexInfoArray = (IndexInfo **) palloc(len * sizeof(IndexInfo *));
180 
181  resultRelInfo->ri_NumIndices = len;
182  resultRelInfo->ri_IndexRelationDescs = relationDescs;
183  resultRelInfo->ri_IndexRelationInfo = indexInfoArray;
184 
185  /*
186  * For each index, open the index relation and save pg_index info. We
187  * acquire RowExclusiveLock, signifying we will update the index.
188  *
189  * Note: we do this even if the index is not indisready; it's not worth
190  * the trouble to optimize for the case where it isn't.
191  */
192  i = 0;
193  foreach(l, indexoidlist)
194  {
195  Oid indexOid = lfirst_oid(l);
196  Relation indexDesc;
197  IndexInfo *ii;
198 
199  indexDesc = index_open(indexOid, RowExclusiveLock);
200 
201  /* extract index key information from the index's pg_index info */
202  ii = BuildIndexInfo(indexDesc);
203 
204  /*
205  * If the indexes are to be used for speculative insertion, add extra
206  * information required by unique index entries.
207  */
208  if (speculative && ii->ii_Unique)
209  BuildSpeculativeIndexInfo(indexDesc, ii);
210 
211  relationDescs[i] = indexDesc;
212  indexInfoArray[i] = ii;
213  i++;
214  }
215 
216  list_free(indexoidlist);
217 }
int ri_NumIndices
Definition: execnodes.h:415
Relation ri_RelationDesc
Definition: execnodes.h:412
#define RelationGetForm(relation)
Definition: rel.h:450
IndexInfo * BuildIndexInfo(Relation index)
Definition: index.c:2301
unsigned int Oid
Definition: postgres_ext.h:31
#define RowExclusiveLock
Definition: lockdefs.h:38
Relation * RelationPtr
Definition: relcache.h:35
bool ii_Unique
Definition: execnodes.h:171
static int list_length(const List *l)
Definition: pg_list.h:149
List * RelationGetIndexList(Relation relation)
Definition: relcache.c:4514
void * palloc(Size size)
Definition: mcxt.c:950
void list_free(List *list)
Definition: list.c:1376
IndexInfo ** ri_IndexRelationInfo
Definition: execnodes.h:421
int i
void BuildSpeculativeIndexInfo(Relation index, IndexInfo *ii)
Definition: index.c:2525
Definition: pg_list.h:50
Relation index_open(Oid relationId, LOCKMODE lockmode)
Definition: indexam.c:132
RelationPtr ri_IndexRelationDescs
Definition: execnodes.h:418
#define lfirst_oid(lc)
Definition: pg_list.h:171

◆ index_recheck_constraint()

static bool index_recheck_constraint ( Relation  index,
Oid constr_procs,
Datum existing_values,
bool existing_isnull,
Datum new_values 
)
static

Definition at line 880 of file execIndexing.c.

References DatumGetBool, i, IndexRelationGetNumberOfKeyAttributes, OidFunctionCall2Coll(), and RelationData::rd_indcollation.

Referenced by check_exclusion_or_unique_constraint().

883 {
884  int indnkeyatts = IndexRelationGetNumberOfKeyAttributes(index);
885  int i;
886 
887  for (i = 0; i < indnkeyatts; i++)
888  {
889  /* Assume the exclusion operators are strict */
890  if (existing_isnull[i])
891  return false;
892 
893  if (!DatumGetBool(OidFunctionCall2Coll(constr_procs[i],
894  index->rd_indcollation[i],
895  existing_values[i],
896  new_values[i])))
897  return false;
898  }
899 
900  return true;
901 }
Oid * rd_indcollation
Definition: rel.h:199
#define DatumGetBool(X)
Definition: postgres.h:393
#define IndexRelationGetNumberOfKeyAttributes(relation)
Definition: rel.h:475
Datum OidFunctionCall2Coll(Oid functionId, Oid collation, Datum arg1, Datum arg2)
Definition: fmgr.c:1424
int i