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 violationOK, ItemPointer conflictTid)
 
static bool index_recheck_constraint (Relation index, Oid *constr_procs, Datum *existing_values, bool *existing_isnull, Datum *new_values)
 
static bool index_unchanged_by_update (ResultRelInfo *resultRelInfo, EState *estate, IndexInfo *indexInfo, Relation indexRelation)
 
static bool index_expression_changed_walker (Node *node, Bitmapset *allUpdatedCols)
 
void ExecOpenIndices (ResultRelInfo *resultRelInfo, bool speculative)
 
void ExecCloseIndices (ResultRelInfo *resultRelInfo)
 
ListExecInsertIndexTuples (ResultRelInfo *resultRelInfo, TupleTableSlot *slot, EState *estate, bool update, bool noDupErr, bool *specConflict, List *arbiterIndexes, bool onlySummarizing)
 
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.

121 {
122  CEOUC_WAIT,
123  CEOUC_NOWAIT,
CEOUC_WAIT_MODE
Definition: execIndexing.c:121
@ CEOUC_NOWAIT
Definition: execIndexing.c:123
@ CEOUC_WAIT
Definition: execIndexing.c:122
@ CEOUC_LIVELOCK_PREVENTING_WAIT
Definition: execIndexing.c:124

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 910 of file execIndexing.c.

915 {
916  (void) check_exclusion_or_unique_constraint(heap, index, indexInfo, tupleid,
917  values, isnull,
918  estate, newIndex,
919  CEOUC_WAIT, false, NULL);
920 }
static Datum values[MAXATTR]
Definition: bootstrap.c:156
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 violationOK, ItemPointer conflictTid)
Definition: execIndexing.c:684
Definition: type.h:95

References CEOUC_WAIT, check_exclusion_or_unique_constraint(), and values.

Referenced by IndexCheckExclusion().

◆ 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  violationOK,
ItemPointer  conflictTid 
)
static

Definition at line 684 of file execIndexing.c.

692 {
693  Oid *constr_procs;
694  uint16 *constr_strats;
695  Oid *index_collations = index->rd_indcollation;
696  int indnkeyatts = IndexRelationGetNumberOfKeyAttributes(index);
697  IndexScanDesc index_scan;
698  ScanKeyData scankeys[INDEX_MAX_KEYS];
699  SnapshotData DirtySnapshot;
700  int i;
701  bool conflict;
702  bool found_self;
703  ExprContext *econtext;
704  TupleTableSlot *existing_slot;
705  TupleTableSlot *save_scantuple;
706 
707  if (indexInfo->ii_ExclusionOps)
708  {
709  constr_procs = indexInfo->ii_ExclusionProcs;
710  constr_strats = indexInfo->ii_ExclusionStrats;
711  }
712  else
713  {
714  constr_procs = indexInfo->ii_UniqueProcs;
715  constr_strats = indexInfo->ii_UniqueStrats;
716  }
717 
718  /*
719  * If any of the input values are NULL, and the index uses the default
720  * nulls-are-distinct mode, the constraint check is assumed to pass (i.e.,
721  * we assume the operators are strict). Otherwise, we interpret the
722  * constraint as specifying IS NULL for each column whose input value is
723  * NULL.
724  */
725  if (!indexInfo->ii_NullsNotDistinct)
726  {
727  for (i = 0; i < indnkeyatts; i++)
728  {
729  if (isnull[i])
730  return true;
731  }
732  }
733 
734  /*
735  * Search the tuples that are in the index for any violations, including
736  * tuples that aren't visible yet.
737  */
738  InitDirtySnapshot(DirtySnapshot);
739 
740  for (i = 0; i < indnkeyatts; i++)
741  {
742  ScanKeyEntryInitialize(&scankeys[i],
743  isnull[i] ? SK_ISNULL | SK_SEARCHNULL : 0,
744  i + 1,
745  constr_strats[i],
746  InvalidOid,
747  index_collations[i],
748  constr_procs[i],
749  values[i]);
750  }
751 
752  /*
753  * Need a TupleTableSlot to put existing tuples in.
754  *
755  * To use FormIndexDatum, we have to make the econtext's scantuple point
756  * to this slot. Be sure to save and restore caller's value for
757  * scantuple.
758  */
759  existing_slot = table_slot_create(heap, NULL);
760 
761  econtext = GetPerTupleExprContext(estate);
762  save_scantuple = econtext->ecxt_scantuple;
763  econtext->ecxt_scantuple = existing_slot;
764 
765  /*
766  * May have to restart scan from this point if a potential conflict is
767  * found.
768  */
769 retry:
770  conflict = false;
771  found_self = false;
772  index_scan = index_beginscan(heap, index, &DirtySnapshot, indnkeyatts, 0);
773  index_rescan(index_scan, scankeys, indnkeyatts, NULL, 0);
774 
775  while (index_getnext_slot(index_scan, ForwardScanDirection, existing_slot))
776  {
777  TransactionId xwait;
778  XLTW_Oper reason_wait;
779  Datum existing_values[INDEX_MAX_KEYS];
780  bool existing_isnull[INDEX_MAX_KEYS];
781  char *error_new;
782  char *error_existing;
783 
784  /*
785  * Ignore the entry for the tuple we're trying to check.
786  */
787  if (ItemPointerIsValid(tupleid) &&
788  ItemPointerEquals(tupleid, &existing_slot->tts_tid))
789  {
790  if (found_self) /* should not happen */
791  elog(ERROR, "found self tuple multiple times in index \"%s\"",
793  found_self = true;
794  continue;
795  }
796 
797  /*
798  * Extract the index column values and isnull flags from the existing
799  * tuple.
800  */
801  FormIndexDatum(indexInfo, existing_slot, estate,
802  existing_values, existing_isnull);
803 
804  /* If lossy indexscan, must recheck the condition */
805  if (index_scan->xs_recheck)
806  {
808  constr_procs,
809  existing_values,
810  existing_isnull,
811  values))
812  continue; /* tuple doesn't actually match, so no
813  * conflict */
814  }
815 
816  /*
817  * At this point we have either a conflict or a potential conflict.
818  *
819  * If an in-progress transaction is affecting the visibility of this
820  * tuple, we need to wait for it to complete and then recheck (unless
821  * the caller requested not to). For simplicity we do rechecking by
822  * just restarting the whole scan --- this case probably doesn't
823  * happen often enough to be worth trying harder, and anyway we don't
824  * want to hold any index internal locks while waiting.
825  */
826  xwait = TransactionIdIsValid(DirtySnapshot.xmin) ?
827  DirtySnapshot.xmin : DirtySnapshot.xmax;
828 
829  if (TransactionIdIsValid(xwait) &&
830  (waitMode == CEOUC_WAIT ||
831  (waitMode == CEOUC_LIVELOCK_PREVENTING_WAIT &&
832  DirtySnapshot.speculativeToken &&
834  {
835  reason_wait = indexInfo->ii_ExclusionOps ?
837  index_endscan(index_scan);
838  if (DirtySnapshot.speculativeToken)
839  SpeculativeInsertionWait(DirtySnapshot.xmin,
840  DirtySnapshot.speculativeToken);
841  else
842  XactLockTableWait(xwait, heap,
843  &existing_slot->tts_tid, reason_wait);
844  goto retry;
845  }
846 
847  /*
848  * We have a definite conflict (or a potential one, but the caller
849  * didn't want to wait). Return it to caller, or report it.
850  */
851  if (violationOK)
852  {
853  conflict = true;
854  if (conflictTid)
855  *conflictTid = existing_slot->tts_tid;
856  break;
857  }
858 
859  error_new = BuildIndexValueDescription(index, values, isnull);
860  error_existing = BuildIndexValueDescription(index, existing_values,
861  existing_isnull);
862  if (newIndex)
863  ereport(ERROR,
864  (errcode(ERRCODE_EXCLUSION_VIOLATION),
865  errmsg("could not create exclusion constraint \"%s\"",
867  error_new && error_existing ?
868  errdetail("Key %s conflicts with key %s.",
869  error_new, error_existing) :
870  errdetail("Key conflicts exist."),
871  errtableconstraint(heap,
873  else
874  ereport(ERROR,
875  (errcode(ERRCODE_EXCLUSION_VIOLATION),
876  errmsg("conflicting key value violates exclusion constraint \"%s\"",
878  error_new && error_existing ?
879  errdetail("Key %s conflicts with existing key %s.",
880  error_new, error_existing) :
881  errdetail("Key conflicts with existing key."),
882  errtableconstraint(heap,
884  }
885 
886  index_endscan(index_scan);
887 
888  /*
889  * Ordinarily, at this point the search should have found the originally
890  * inserted tuple (if any), unless we exited the loop early because of
891  * conflict. However, it is possible to define exclusion constraints for
892  * which that wouldn't be true --- for instance, if the operator is <>. So
893  * we no longer complain if found_self is still false.
894  */
895 
896  econtext->ecxt_scantuple = save_scantuple;
897 
898  ExecDropSingleTupleTableSlot(existing_slot);
899 
900  return !conflict;
901 }
unsigned short uint16
Definition: c.h:489
uint32 TransactionId
Definition: c.h:636
int errdetail(const char *fmt,...)
Definition: elog.c:1202
int errcode(int sqlerrcode)
Definition: elog.c:858
int errmsg(const char *fmt,...)
Definition: elog.c:1069
#define ERROR
Definition: elog.h:39
#define ereport(elevel,...)
Definition: elog.h:149
static bool index_recheck_constraint(Relation index, Oid *constr_procs, Datum *existing_values, bool *existing_isnull, Datum *new_values)
Definition: execIndexing.c:927
void ExecDropSingleTupleTableSlot(TupleTableSlot *slot)
Definition: execTuples.c:1255
#define GetPerTupleExprContext(estate)
Definition: executor.h:549
char * BuildIndexValueDescription(Relation indexRelation, Datum *values, bool *isnull)
Definition: genam.c:177
void FormIndexDatum(IndexInfo *indexInfo, TupleTableSlot *slot, EState *estate, Datum *values, bool *isnull)
Definition: index.c:2721
bool index_getnext_slot(IndexScanDesc scan, ScanDirection direction, TupleTableSlot *slot)
Definition: indexam.c:624
IndexScanDesc index_beginscan(Relation heapRelation, Relation indexRelation, Snapshot snapshot, int nkeys, int norderbys)
Definition: indexam.c:205
void index_endscan(IndexScanDesc scan)
Definition: indexam.c:327
void index_rescan(IndexScanDesc scan, ScanKey keys, int nkeys, ScanKey orderbys, int norderbys)
Definition: indexam.c:301
int i
Definition: isn.c:73
bool ItemPointerEquals(ItemPointer pointer1, ItemPointer pointer2)
Definition: itemptr.c:35
static bool ItemPointerIsValid(const ItemPointerData *pointer)
Definition: itemptr.h:83
void XactLockTableWait(TransactionId xid, Relation rel, ItemPointer ctid, XLTW_Oper oper)
Definition: lmgr.c:668
void SpeculativeInsertionWait(TransactionId xid, uint32 token)
Definition: lmgr.c:825
XLTW_Oper
Definition: lmgr.h:25
@ XLTW_InsertIndex
Definition: lmgr.h:31
@ XLTW_RecheckExclusionConstr
Definition: lmgr.h:34
#define INDEX_MAX_KEYS
uintptr_t Datum
Definition: postgres.h:64
#define InvalidOid
Definition: postgres_ext.h:36
unsigned int Oid
Definition: postgres_ext.h:31
#define RelationGetRelationName(relation)
Definition: rel.h:538
#define IndexRelationGetNumberOfKeyAttributes(relation)
Definition: rel.h:523
int errtableconstraint(Relation rel, const char *conname)
Definition: relcache.c:5960
void ScanKeyEntryInitialize(ScanKey entry, int flags, AttrNumber attributeNumber, StrategyNumber strategy, Oid subtype, Oid collation, RegProcedure procedure, Datum argument)
Definition: scankey.c:32
@ ForwardScanDirection
Definition: sdir.h:28
#define SK_SEARCHNULL
Definition: skey.h:121
#define SK_ISNULL
Definition: skey.h:115
#define InitDirtySnapshot(snapshotdata)
Definition: snapmgr.h:74
TupleTableSlot * ecxt_scantuple
Definition: execnodes.h:249
uint16 * ii_ExclusionStrats
Definition: execnodes.h:186
Oid * ii_ExclusionOps
Definition: execnodes.h:184
bool ii_NullsNotDistinct
Definition: execnodes.h:192
uint16 * ii_UniqueStrats
Definition: execnodes.h:189
Oid * ii_ExclusionProcs
Definition: execnodes.h:185
Oid * ii_UniqueProcs
Definition: execnodes.h:188
TransactionId xmin
Definition: snapshot.h:157
TransactionId xmax
Definition: snapshot.h:158
uint32 speculativeToken
Definition: snapshot.h:193
ItemPointerData tts_tid
Definition: tuptable.h:130
TupleTableSlot * table_slot_create(Relation relation, List **reglist)
Definition: tableam.c:91
bool TransactionIdPrecedes(TransactionId id1, TransactionId id2)
Definition: transam.c:280
#define TransactionIdIsValid(xid)
Definition: transam.h:41
TransactionId GetCurrentTransactionId(void)
Definition: xact.c:445

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_NullsNotDistinct, 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(), RelationGetRelationName, ScanKeyEntryInitialize(), SK_ISNULL, SK_SEARCHNULL, SpeculativeInsertionWait(), SnapshotData::speculativeToken, table_slot_create(), TransactionIdIsValid, TransactionIdPrecedes(), TupleTableSlot::tts_tid, values, XactLockTableWait(), XLTW_InsertIndex, XLTW_RecheckExclusionConstr, SnapshotData::xmax, SnapshotData::xmin, and IndexScanDescData::xs_recheck.

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

◆ ExecCheckIndexConstraints()

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

Definition at line 522 of file execIndexing.c.

525 {
526  int i;
527  int numIndices;
528  RelationPtr relationDescs;
529  Relation heapRelation;
530  IndexInfo **indexInfoArray;
531  ExprContext *econtext;
533  bool isnull[INDEX_MAX_KEYS];
534  ItemPointerData invalidItemPtr;
535  bool checkedIndex = false;
536 
537  ItemPointerSetInvalid(conflictTid);
538  ItemPointerSetInvalid(&invalidItemPtr);
539 
540  /*
541  * Get information from the result relation info structure.
542  */
543  numIndices = resultRelInfo->ri_NumIndices;
544  relationDescs = resultRelInfo->ri_IndexRelationDescs;
545  indexInfoArray = resultRelInfo->ri_IndexRelationInfo;
546  heapRelation = resultRelInfo->ri_RelationDesc;
547 
548  /*
549  * We will use the EState's per-tuple context for evaluating predicates
550  * and index expressions (creating it if it's not already there).
551  */
552  econtext = GetPerTupleExprContext(estate);
553 
554  /* Arrange for econtext's scan tuple to be the tuple under test */
555  econtext->ecxt_scantuple = slot;
556 
557  /*
558  * For each index, form index tuple and check if it satisfies the
559  * constraint.
560  */
561  for (i = 0; i < numIndices; i++)
562  {
563  Relation indexRelation = relationDescs[i];
564  IndexInfo *indexInfo;
565  bool satisfiesConstraint;
566 
567  if (indexRelation == NULL)
568  continue;
569 
570  indexInfo = indexInfoArray[i];
571 
572  if (!indexInfo->ii_Unique && !indexInfo->ii_ExclusionOps)
573  continue;
574 
575  /* If the index is marked as read-only, ignore it */
576  if (!indexInfo->ii_ReadyForInserts)
577  continue;
578 
579  /* When specific arbiter indexes requested, only examine them */
580  if (arbiterIndexes != NIL &&
581  !list_member_oid(arbiterIndexes,
582  indexRelation->rd_index->indexrelid))
583  continue;
584 
585  if (!indexRelation->rd_index->indimmediate)
586  ereport(ERROR,
587  (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
588  errmsg("ON CONFLICT does not support deferrable unique constraints/exclusion constraints as arbiters"),
589  errtableconstraint(heapRelation,
590  RelationGetRelationName(indexRelation))));
591 
592  checkedIndex = true;
593 
594  /* Check for partial index */
595  if (indexInfo->ii_Predicate != NIL)
596  {
597  ExprState *predicate;
598 
599  /*
600  * If predicate state not set up yet, create it (in the estate's
601  * per-query context)
602  */
603  predicate = indexInfo->ii_PredicateState;
604  if (predicate == NULL)
605  {
606  predicate = ExecPrepareQual(indexInfo->ii_Predicate, estate);
607  indexInfo->ii_PredicateState = predicate;
608  }
609 
610  /* Skip this index-update if the predicate isn't satisfied */
611  if (!ExecQual(predicate, econtext))
612  continue;
613  }
614 
615  /*
616  * FormIndexDatum fills in its values and isnull parameters with the
617  * appropriate values for the column(s) of the index.
618  */
619  FormIndexDatum(indexInfo,
620  slot,
621  estate,
622  values,
623  isnull);
624 
625  satisfiesConstraint =
626  check_exclusion_or_unique_constraint(heapRelation, indexRelation,
627  indexInfo, &invalidItemPtr,
628  values, isnull, estate, false,
629  CEOUC_WAIT, true,
630  conflictTid);
631  if (!satisfiesConstraint)
632  return false;
633  }
634 
635  if (arbiterIndexes != NIL && !checkedIndex)
636  elog(ERROR, "unexpected failure to find arbiter index");
637 
638  return true;
639 }
ExprState * ExecPrepareQual(List *qual, EState *estate)
Definition: execExpr.c:763
static bool ExecQual(ExprState *state, ExprContext *econtext)
Definition: executor.h:412
static void ItemPointerSetInvalid(ItemPointerData *pointer)
Definition: itemptr.h:184
bool list_member_oid(const List *list, Oid datum)
Definition: list.c:721
#define NIL
Definition: pg_list.h:68
bool ii_Unique
Definition: execnodes.h:191
ExprState * ii_PredicateState
Definition: execnodes.h:183
bool ii_ReadyForInserts
Definition: execnodes.h:193
List * ii_Predicate
Definition: execnodes.h:182
Form_pg_index rd_index
Definition: rel.h:191
int ri_NumIndices
Definition: execnodes.h:453
Relation ri_RelationDesc
Definition: execnodes.h:450
RelationPtr ri_IndexRelationDescs
Definition: execnodes.h:456
IndexInfo ** ri_IndexRelationInfo
Definition: execnodes.h:459

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 ExecInsert().

◆ ExecCloseIndices()

void ExecCloseIndices ( ResultRelInfo resultRelInfo)

Definition at line 231 of file execIndexing.c.

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

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(), ExecCleanupTupleRouting(), and ExecCloseResultRelations().

◆ ExecInsertIndexTuples()

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

Definition at line 293 of file execIndexing.c.

301 {
302  ItemPointer tupleid = &slot->tts_tid;
303  List *result = NIL;
304  int i;
305  int numIndices;
306  RelationPtr relationDescs;
307  Relation heapRelation;
308  IndexInfo **indexInfoArray;
309  ExprContext *econtext;
311  bool isnull[INDEX_MAX_KEYS];
312 
313  Assert(ItemPointerIsValid(tupleid));
314 
315  /*
316  * Get information from the result relation info structure.
317  */
318  numIndices = resultRelInfo->ri_NumIndices;
319  relationDescs = resultRelInfo->ri_IndexRelationDescs;
320  indexInfoArray = resultRelInfo->ri_IndexRelationInfo;
321  heapRelation = resultRelInfo->ri_RelationDesc;
322 
323  /* Sanity check: slot must belong to the same rel as the resultRelInfo. */
324  Assert(slot->tts_tableOid == RelationGetRelid(heapRelation));
325 
326  /*
327  * We will use the EState's per-tuple context for evaluating predicates
328  * and index expressions (creating it if it's not already there).
329  */
330  econtext = GetPerTupleExprContext(estate);
331 
332  /* Arrange for econtext's scan tuple to be the tuple under test */
333  econtext->ecxt_scantuple = slot;
334 
335  /*
336  * for each index, form and insert the index tuple
337  */
338  for (i = 0; i < numIndices; i++)
339  {
340  Relation indexRelation = relationDescs[i];
341  IndexInfo *indexInfo;
342  bool applyNoDupErr;
343  IndexUniqueCheck checkUnique;
344  bool indexUnchanged;
345  bool satisfiesConstraint;
346 
347  if (indexRelation == NULL)
348  continue;
349 
350  indexInfo = indexInfoArray[i];
351 
352  /* If the index is marked as read-only, ignore it */
353  if (!indexInfo->ii_ReadyForInserts)
354  continue;
355 
356  /*
357  * Skip processing of non-summarizing indexes if we only update
358  * summarizing indexes
359  */
360  if (onlySummarizing && !indexInfo->ii_Summarizing)
361  continue;
362 
363  /* Check for partial index */
364  if (indexInfo->ii_Predicate != NIL)
365  {
366  ExprState *predicate;
367 
368  /*
369  * If predicate state not set up yet, create it (in the estate's
370  * per-query context)
371  */
372  predicate = indexInfo->ii_PredicateState;
373  if (predicate == NULL)
374  {
375  predicate = ExecPrepareQual(indexInfo->ii_Predicate, estate);
376  indexInfo->ii_PredicateState = predicate;
377  }
378 
379  /* Skip this index-update if the predicate isn't satisfied */
380  if (!ExecQual(predicate, econtext))
381  continue;
382  }
383 
384  /*
385  * FormIndexDatum fills in its values and isnull parameters with the
386  * appropriate values for the column(s) of the index.
387  */
388  FormIndexDatum(indexInfo,
389  slot,
390  estate,
391  values,
392  isnull);
393 
394  /* Check whether to apply noDupErr to this index */
395  applyNoDupErr = noDupErr &&
396  (arbiterIndexes == NIL ||
397  list_member_oid(arbiterIndexes,
398  indexRelation->rd_index->indexrelid));
399 
400  /*
401  * The index AM does the actual insertion, plus uniqueness checking.
402  *
403  * For an immediate-mode unique index, we just tell the index AM to
404  * throw error if not unique.
405  *
406  * For a deferrable unique index, we tell the index AM to just detect
407  * possible non-uniqueness, and we add the index OID to the result
408  * list if further checking is needed.
409  *
410  * For a speculative insertion (used by INSERT ... ON CONFLICT), do
411  * the same as for a deferrable unique index.
412  */
413  if (!indexRelation->rd_index->indisunique)
414  checkUnique = UNIQUE_CHECK_NO;
415  else if (applyNoDupErr)
416  checkUnique = UNIQUE_CHECK_PARTIAL;
417  else if (indexRelation->rd_index->indimmediate)
418  checkUnique = UNIQUE_CHECK_YES;
419  else
420  checkUnique = UNIQUE_CHECK_PARTIAL;
421 
422  /*
423  * There's definitely going to be an index_insert() call for this
424  * index. If we're being called as part of an UPDATE statement,
425  * consider if the 'indexUnchanged' = true hint should be passed.
426  */
427  indexUnchanged = update && index_unchanged_by_update(resultRelInfo,
428  estate,
429  indexInfo,
430  indexRelation);
431 
432  satisfiesConstraint =
433  index_insert(indexRelation, /* index relation */
434  values, /* array of index Datums */
435  isnull, /* null flags */
436  tupleid, /* tid of heap tuple */
437  heapRelation, /* heap relation */
438  checkUnique, /* type of uniqueness check to do */
439  indexUnchanged, /* UPDATE without logical change? */
440  indexInfo); /* index AM may need this */
441 
442  /*
443  * If the index has an associated exclusion constraint, check that.
444  * This is simpler than the process for uniqueness checks since we
445  * always insert first and then check. If the constraint is deferred,
446  * we check now anyway, but don't throw error on violation or wait for
447  * a conclusive outcome from a concurrent insertion; instead we'll
448  * queue a recheck event. Similarly, noDupErr callers (speculative
449  * inserters) will recheck later, and wait for a conclusive outcome
450  * then.
451  *
452  * An index for an exclusion constraint can't also be UNIQUE (not an
453  * essential property, we just don't allow it in the grammar), so no
454  * need to preserve the prior state of satisfiesConstraint.
455  */
456  if (indexInfo->ii_ExclusionOps != NULL)
457  {
458  bool violationOK;
459  CEOUC_WAIT_MODE waitMode;
460 
461  if (applyNoDupErr)
462  {
463  violationOK = true;
465  }
466  else if (!indexRelation->rd_index->indimmediate)
467  {
468  violationOK = true;
469  waitMode = CEOUC_NOWAIT;
470  }
471  else
472  {
473  violationOK = false;
474  waitMode = CEOUC_WAIT;
475  }
476 
477  satisfiesConstraint =
479  indexRelation, indexInfo,
480  tupleid, values, isnull,
481  estate, false,
482  waitMode, violationOK, NULL);
483  }
484 
485  if ((checkUnique == UNIQUE_CHECK_PARTIAL ||
486  indexInfo->ii_ExclusionOps != NULL) &&
487  !satisfiesConstraint)
488  {
489  /*
490  * The tuple potentially violates the uniqueness or exclusion
491  * constraint, so make a note of the index so that we can re-check
492  * it later. Speculative inserters are told if there was a
493  * speculative conflict, since that always requires a restart.
494  */
495  result = lappend_oid(result, RelationGetRelid(indexRelation));
496  if (indexRelation->rd_index->indimmediate && specConflict)
497  *specConflict = true;
498  }
499  }
500 
501  return result;
502 }
static bool index_unchanged_by_update(ResultRelInfo *resultRelInfo, EState *estate, IndexInfo *indexInfo, Relation indexRelation)
Definition: execIndexing.c:958
IndexUniqueCheck
Definition: genam.h:116
@ UNIQUE_CHECK_NO
Definition: genam.h:117
@ UNIQUE_CHECK_PARTIAL
Definition: genam.h:119
@ UNIQUE_CHECK_YES
Definition: genam.h:118
bool index_insert(Relation indexRelation, Datum *values, bool *isnull, ItemPointer heap_t_ctid, Relation heapRelation, IndexUniqueCheck checkUnique, bool indexUnchanged, IndexInfo *indexInfo)
Definition: indexam.c:176
Assert(fmt[strlen(fmt) - 1] !='\n')
List * lappend_oid(List *list, Oid datum)
Definition: list.c:374
#define RelationGetRelid(relation)
Definition: rel.h:504
bool ii_Summarizing
Definition: execnodes.h:198
Definition: pg_list.h:54
Oid tts_tableOid
Definition: tuptable.h:131

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, IndexInfo::ii_Summarizing, index_insert(), INDEX_MAX_KEYS, index_unchanged_by_update(), 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(), ExecInsert(), ExecSimpleRelationInsert(), ExecSimpleRelationUpdate(), and ExecUpdateEpilogue().

◆ ExecOpenIndices()

void ExecOpenIndices ( ResultRelInfo resultRelInfo,
bool  speculative 
)

Definition at line 156 of file execIndexing.c.

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

References BuildIndexInfo(), BuildSpeculativeIndexInfo(), i, IndexInfo::ii_Unique, index_open(), len, 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(), ExecInitPartitionInfo(), ExecInsert(), and ExecUpdatePrologue().

◆ index_expression_changed_walker()

static bool index_expression_changed_walker ( Node node,
Bitmapset allUpdatedCols 
)
static

Definition at line 1072 of file execIndexing.c.

1073 {
1074  if (node == NULL)
1075  return false;
1076 
1077  if (IsA(node, Var))
1078  {
1079  Var *var = (Var *) node;
1080 
1082  allUpdatedCols))
1083  {
1084  /* Var was updated -- indicates that we should not hint */
1085  return true;
1086  }
1087 
1088  /* Still haven't found a reason to not pass the hint */
1089  return false;
1090  }
1091 
1093  (void *) allUpdatedCols);
1094 }
bool bms_is_member(int x, const Bitmapset *a)
Definition: bitmapset.c:444
static bool index_expression_changed_walker(Node *node, Bitmapset *allUpdatedCols)
#define expression_tree_walker(n, w, c)
Definition: nodeFuncs.h:151
#define IsA(nodeptr, _type_)
Definition: nodes.h:179
Definition: primnodes.h:226
AttrNumber varattno
Definition: primnodes.h:238
#define FirstLowInvalidHeapAttributeNumber
Definition: sysattr.h:27

References bms_is_member(), expression_tree_walker, FirstLowInvalidHeapAttributeNumber, IsA, and Var::varattno.

Referenced by index_unchanged_by_update().

◆ 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 927 of file execIndexing.c.

930 {
931  int indnkeyatts = IndexRelationGetNumberOfKeyAttributes(index);
932  int i;
933 
934  for (i = 0; i < indnkeyatts; i++)
935  {
936  /* Assume the exclusion operators are strict */
937  if (existing_isnull[i])
938  return false;
939 
940  if (!DatumGetBool(OidFunctionCall2Coll(constr_procs[i],
941  index->rd_indcollation[i],
942  existing_values[i],
943  new_values[i])))
944  return false;
945  }
946 
947  return true;
948 }
Datum OidFunctionCall2Coll(Oid functionId, Oid collation, Datum arg1, Datum arg2)
Definition: fmgr.c:1392
static bool DatumGetBool(Datum X)
Definition: postgres.h:90

References DatumGetBool(), i, IndexRelationGetNumberOfKeyAttributes, and OidFunctionCall2Coll().

Referenced by check_exclusion_or_unique_constraint().

◆ index_unchanged_by_update()

static bool index_unchanged_by_update ( ResultRelInfo resultRelInfo,
EState estate,
IndexInfo indexInfo,
Relation  indexRelation 
)
static

Definition at line 958 of file execIndexing.c.

960 {
961  Bitmapset *updatedCols;
962  Bitmapset *extraUpdatedCols;
963  Bitmapset *allUpdatedCols;
964  bool hasexpression = false;
965  List *idxExprs;
966 
967  /*
968  * Check cache first
969  */
970  if (indexInfo->ii_CheckedUnchanged)
971  return indexInfo->ii_IndexUnchanged;
972  indexInfo->ii_CheckedUnchanged = true;
973 
974  /*
975  * Check for indexed attribute overlap with updated columns.
976  *
977  * Only do this for key columns. A change to a non-key column within an
978  * INCLUDE index should not be counted here. Non-key column values are
979  * opaque payload state to the index AM, a little like an extra table TID.
980  *
981  * Note that row-level BEFORE triggers won't affect our behavior, since
982  * they don't affect the updatedCols bitmaps generally. It doesn't seem
983  * worth the trouble of checking which attributes were changed directly.
984  */
985  updatedCols = ExecGetUpdatedCols(resultRelInfo, estate);
986  extraUpdatedCols = ExecGetExtraUpdatedCols(resultRelInfo, estate);
987  for (int attr = 0; attr < indexInfo->ii_NumIndexKeyAttrs; attr++)
988  {
989  int keycol = indexInfo->ii_IndexAttrNumbers[attr];
990 
991  if (keycol <= 0)
992  {
993  /*
994  * Skip expressions for now, but remember to deal with them later
995  * on
996  */
997  hasexpression = true;
998  continue;
999  }
1000 
1002  updatedCols) ||
1004  extraUpdatedCols))
1005  {
1006  /* Changed key column -- don't hint for this index */
1007  indexInfo->ii_IndexUnchanged = false;
1008  return false;
1009  }
1010  }
1011 
1012  /*
1013  * When we get this far and index has no expressions, return true so that
1014  * index_insert() call will go on to pass 'indexUnchanged' = true hint.
1015  *
1016  * The _absence_ of an indexed key attribute that overlaps with updated
1017  * attributes (in addition to the total absence of indexed expressions)
1018  * shows that the index as a whole is logically unchanged by UPDATE.
1019  */
1020  if (!hasexpression)
1021  {
1022  indexInfo->ii_IndexUnchanged = true;
1023  return true;
1024  }
1025 
1026  /*
1027  * Need to pass only one bms to expression_tree_walker helper function.
1028  * Avoid allocating memory in common case where there are no extra cols.
1029  */
1030  if (!extraUpdatedCols)
1031  allUpdatedCols = updatedCols;
1032  else
1033  allUpdatedCols = bms_union(updatedCols, extraUpdatedCols);
1034 
1035  /*
1036  * We have to work slightly harder in the event of indexed expressions,
1037  * but the principle is the same as before: try to find columns (Vars,
1038  * actually) that overlap with known-updated columns.
1039  *
1040  * If we find any matching Vars, don't pass hint for index. Otherwise
1041  * pass hint.
1042  */
1043  idxExprs = RelationGetIndexExpressions(indexRelation);
1044  hasexpression = index_expression_changed_walker((Node *) idxExprs,
1045  allUpdatedCols);
1046  list_free(idxExprs);
1047  if (extraUpdatedCols)
1048  bms_free(allUpdatedCols);
1049 
1050  if (hasexpression)
1051  {
1052  indexInfo->ii_IndexUnchanged = false;
1053  return false;
1054  }
1055 
1056  /*
1057  * Deliberately don't consider index predicates. We should even give the
1058  * hint when result rel's "updated tuple" has no corresponding index
1059  * tuple, which is possible with a partial index (provided the usual
1060  * conditions are met).
1061  */
1062  indexInfo->ii_IndexUnchanged = true;
1063  return true;
1064 }
void bms_free(Bitmapset *a)
Definition: bitmapset.c:209
Bitmapset * bms_union(const Bitmapset *a, const Bitmapset *b)
Definition: bitmapset.c:226
Bitmapset * ExecGetUpdatedCols(ResultRelInfo *relinfo, EState *estate)
Definition: execUtils.c:1319
Bitmapset * ExecGetExtraUpdatedCols(ResultRelInfo *relinfo, EState *estate)
Definition: execUtils.c:1340
List * RelationGetIndexExpressions(Relation relation)
Definition: relcache.c:4973
bool ii_CheckedUnchanged
Definition: execnodes.h:194
int ii_NumIndexKeyAttrs
Definition: execnodes.h:178
bool ii_IndexUnchanged
Definition: execnodes.h:195
AttrNumber ii_IndexAttrNumbers[INDEX_MAX_KEYS]
Definition: execnodes.h:179
Definition: nodes.h:129

References bms_free(), bms_is_member(), bms_union(), ExecGetExtraUpdatedCols(), ExecGetUpdatedCols(), FirstLowInvalidHeapAttributeNumber, IndexInfo::ii_CheckedUnchanged, IndexInfo::ii_IndexAttrNumbers, IndexInfo::ii_IndexUnchanged, IndexInfo::ii_NumIndexKeyAttrs, index_expression_changed_walker(), list_free(), and RelationGetIndexExpressions().

Referenced by ExecInsertIndexTuples().