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

References CEOUC_WAIT, and check_exclusion_or_unique_constraint().

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

892 {
893  (void) check_exclusion_or_unique_constraint(heap, index, indexInfo, tupleid,
894  values, isnull,
895  estate, newIndex,
896  CEOUC_WAIT, false, NULL);
897 }
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:667
static Datum values[MAXATTR]
Definition: bootstrap.c:166

◆ 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 667 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().

675 {
676  Oid *constr_procs;
677  uint16 *constr_strats;
678  Oid *index_collations = index->rd_indcollation;
679  int indnkeyatts = IndexRelationGetNumberOfKeyAttributes(index);
680  IndexScanDesc index_scan;
681  ScanKeyData scankeys[INDEX_MAX_KEYS];
682  SnapshotData DirtySnapshot;
683  int i;
684  bool conflict;
685  bool found_self;
686  ExprContext *econtext;
687  TupleTableSlot *existing_slot;
688  TupleTableSlot *save_scantuple;
689 
690  if (indexInfo->ii_ExclusionOps)
691  {
692  constr_procs = indexInfo->ii_ExclusionProcs;
693  constr_strats = indexInfo->ii_ExclusionStrats;
694  }
695  else
696  {
697  constr_procs = indexInfo->ii_UniqueProcs;
698  constr_strats = indexInfo->ii_UniqueStrats;
699  }
700 
701  /*
702  * If any of the input values are NULL, the constraint check is assumed to
703  * pass (i.e., we assume the operators are strict).
704  */
705  for (i = 0; i < indnkeyatts; i++)
706  {
707  if (isnull[i])
708  return true;
709  }
710 
711  /*
712  * Search the tuples that are in the index for any violations, including
713  * tuples that aren't visible yet.
714  */
715  InitDirtySnapshot(DirtySnapshot);
716 
717  for (i = 0; i < indnkeyatts; i++)
718  {
719  ScanKeyEntryInitialize(&scankeys[i],
720  0,
721  i + 1,
722  constr_strats[i],
723  InvalidOid,
724  index_collations[i],
725  constr_procs[i],
726  values[i]);
727  }
728 
729  /*
730  * Need a TupleTableSlot to put existing tuples in.
731  *
732  * To use FormIndexDatum, we have to make the econtext's scantuple point
733  * to this slot. Be sure to save and restore caller's value for
734  * scantuple.
735  */
736  existing_slot = table_slot_create(heap, NULL);
737 
738  econtext = GetPerTupleExprContext(estate);
739  save_scantuple = econtext->ecxt_scantuple;
740  econtext->ecxt_scantuple = existing_slot;
741 
742  /*
743  * May have to restart scan from this point if a potential conflict is
744  * found.
745  */
746 retry:
747  conflict = false;
748  found_self = false;
749  index_scan = index_beginscan(heap, index, &DirtySnapshot, indnkeyatts, 0);
750  index_rescan(index_scan, scankeys, indnkeyatts, NULL, 0);
751 
752  while (index_getnext_slot(index_scan, ForwardScanDirection, existing_slot))
753  {
754  TransactionId xwait;
755  XLTW_Oper reason_wait;
756  Datum existing_values[INDEX_MAX_KEYS];
757  bool existing_isnull[INDEX_MAX_KEYS];
758  char *error_new;
759  char *error_existing;
760 
761  /*
762  * Ignore the entry for the tuple we're trying to check.
763  */
764  if (ItemPointerIsValid(tupleid) &&
765  ItemPointerEquals(tupleid, &existing_slot->tts_tid))
766  {
767  if (found_self) /* should not happen */
768  elog(ERROR, "found self tuple multiple times in index \"%s\"",
769  RelationGetRelationName(index));
770  found_self = true;
771  continue;
772  }
773 
774  /*
775  * Extract the index column values and isnull flags from the existing
776  * tuple.
777  */
778  FormIndexDatum(indexInfo, existing_slot, estate,
779  existing_values, existing_isnull);
780 
781  /* If lossy indexscan, must recheck the condition */
782  if (index_scan->xs_recheck)
783  {
784  if (!index_recheck_constraint(index,
785  constr_procs,
786  existing_values,
787  existing_isnull,
788  values))
789  continue; /* tuple doesn't actually match, so no
790  * conflict */
791  }
792 
793  /*
794  * At this point we have either a conflict or a potential conflict.
795  *
796  * If an in-progress transaction is affecting the visibility of this
797  * tuple, we need to wait for it to complete and then recheck (unless
798  * the caller requested not to). For simplicity we do rechecking by
799  * just restarting the whole scan --- this case probably doesn't
800  * happen often enough to be worth trying harder, and anyway we don't
801  * want to hold any index internal locks while waiting.
802  */
803  xwait = TransactionIdIsValid(DirtySnapshot.xmin) ?
804  DirtySnapshot.xmin : DirtySnapshot.xmax;
805 
806  if (TransactionIdIsValid(xwait) &&
807  (waitMode == CEOUC_WAIT ||
808  (waitMode == CEOUC_LIVELOCK_PREVENTING_WAIT &&
809  DirtySnapshot.speculativeToken &&
811  {
812  reason_wait = indexInfo->ii_ExclusionOps ?
814  index_endscan(index_scan);
815  if (DirtySnapshot.speculativeToken)
816  SpeculativeInsertionWait(DirtySnapshot.xmin,
817  DirtySnapshot.speculativeToken);
818  else
819  XactLockTableWait(xwait, heap,
820  &existing_slot->tts_tid, reason_wait);
821  goto retry;
822  }
823 
824  /*
825  * We have a definite conflict (or a potential one, but the caller
826  * didn't want to wait). Return it to caller, or report it.
827  */
828  if (violationOK)
829  {
830  conflict = true;
831  if (conflictTid)
832  *conflictTid = existing_slot->tts_tid;
833  break;
834  }
835 
836  error_new = BuildIndexValueDescription(index, values, isnull);
837  error_existing = BuildIndexValueDescription(index, existing_values,
838  existing_isnull);
839  if (newIndex)
840  ereport(ERROR,
841  (errcode(ERRCODE_EXCLUSION_VIOLATION),
842  errmsg("could not create exclusion constraint \"%s\"",
843  RelationGetRelationName(index)),
844  error_new && error_existing ?
845  errdetail("Key %s conflicts with key %s.",
846  error_new, error_existing) :
847  errdetail("Key conflicts exist."),
848  errtableconstraint(heap,
849  RelationGetRelationName(index))));
850  else
851  ereport(ERROR,
852  (errcode(ERRCODE_EXCLUSION_VIOLATION),
853  errmsg("conflicting key value violates exclusion constraint \"%s\"",
854  RelationGetRelationName(index)),
855  error_new && error_existing ?
856  errdetail("Key %s conflicts with existing key %s.",
857  error_new, error_existing) :
858  errdetail("Key conflicts with existing key."),
859  errtableconstraint(heap,
860  RelationGetRelationName(index))));
861  }
862 
863  index_endscan(index_scan);
864 
865  /*
866  * Ordinarily, at this point the search should have found the originally
867  * inserted tuple (if any), unless we exited the loop early because of
868  * conflict. However, it is possible to define exclusion constraints for
869  * which that wouldn't be true --- for instance, if the operator is <>. So
870  * we no longer complain if found_self is still false.
871  */
872 
873  econtext->ecxt_scantuple = save_scantuple;
874 
875  ExecDropSingleTupleTableSlot(existing_slot);
876 
877  return !conflict;
878 }
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:2660
uint16 * ii_UniqueStrats
Definition: execnodes.h:170
#define InitDirtySnapshot(snapshotdata)
Definition: snapmgr.h:74
uint32 TransactionId
Definition: c.h:587
void index_rescan(IndexScanDesc scan, ScanKey keys, int nkeys, ScanKey orderbys, int norderbys)
Definition: indexam.c:297
Oid * ii_ExclusionProcs
Definition: execnodes.h:166
int errcode(int sqlerrcode)
Definition: elog.c:698
unsigned int Oid
Definition: postgres_ext.h:31
#define GetPerTupleExprContext(estate)
Definition: executor.h:532
int errtableconstraint(Relation rel, const char *conname)
Definition: relcache.c:5682
unsigned short uint16
Definition: c.h:440
Oid * rd_indcollation
Definition: rel.h:212
static bool index_recheck_constraint(Relation index, Oid *constr_procs, Datum *existing_values, bool *existing_isnull, Datum *new_values)
Definition: execIndexing.c:904
#define ERROR
Definition: elog.h:46
void SpeculativeInsertionWait(TransactionId xid, uint32 token)
Definition: lmgr.c:797
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:1254
Oid * ii_UniqueProcs
Definition: execnodes.h:169
int errdetail(const char *fmt,...)
Definition: elog.c:1042
#define RelationGetRelationName(relation)
Definition: rel.h:503
TransactionId xmax
Definition: snapshot.h:158
TransactionId xmin
Definition: snapshot.h:157
#define IndexRelationGetNumberOfKeyAttributes(relation)
Definition: rel.h:488
void index_endscan(IndexScanDesc scan)
Definition: indexam.c:323
bool TransactionIdPrecedes(TransactionId id1, TransactionId id2)
Definition: transam.c:300
uintptr_t Datum
Definition: postgres.h:411
#define InvalidOid
Definition: postgres_ext.h:36
#define ereport(elevel,...)
Definition: elog.h:157
uint32 speculativeToken
Definition: snapshot.h:193
void XactLockTableWait(TransactionId xid, Relation rel, ItemPointer ctid, XLTW_Oper oper)
Definition: lmgr.c:640
#define INDEX_MAX_KEYS
bool index_getnext_slot(IndexScanDesc scan, ScanDirection direction, TupleTableSlot *slot)
Definition: indexam.c:616
TupleTableSlot * ecxt_scantuple
Definition: execnodes.h:226
bool ItemPointerEquals(ItemPointer pointer1, ItemPointer pointer2)
Definition: itemptr.c:29
static Datum values[MAXATTR]
Definition: bootstrap.c:166
XLTW_Oper
Definition: lmgr.h:24
Oid * ii_ExclusionOps
Definition: execnodes.h:165
int errmsg(const char *fmt,...)
Definition: elog.c:909
#define elog(elevel,...)
Definition: elog.h:232
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:167
ItemPointerData tts_tid
Definition: tuptable.h:130
IndexScanDesc index_beginscan(Relation heapRelation, Relation indexRelation, Snapshot snapshot, int nkeys, int norderbys)
Definition: indexam.c:205

◆ ExecCheckIndexConstraints()

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

Definition at line 505 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, ExprEvalStep::isnull, 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().

508 {
509  int i;
510  int numIndices;
511  RelationPtr relationDescs;
512  Relation heapRelation;
513  IndexInfo **indexInfoArray;
514  ExprContext *econtext;
516  bool isnull[INDEX_MAX_KEYS];
517  ItemPointerData invalidItemPtr;
518  bool checkedIndex = false;
519 
520  ItemPointerSetInvalid(conflictTid);
521  ItemPointerSetInvalid(&invalidItemPtr);
522 
523  /*
524  * Get information from the result relation info structure.
525  */
526  numIndices = resultRelInfo->ri_NumIndices;
527  relationDescs = resultRelInfo->ri_IndexRelationDescs;
528  indexInfoArray = resultRelInfo->ri_IndexRelationInfo;
529  heapRelation = resultRelInfo->ri_RelationDesc;
530 
531  /*
532  * We will use the EState's per-tuple context for evaluating predicates
533  * and index expressions (creating it if it's not already there).
534  */
535  econtext = GetPerTupleExprContext(estate);
536 
537  /* Arrange for econtext's scan tuple to be the tuple under test */
538  econtext->ecxt_scantuple = slot;
539 
540  /*
541  * For each index, form index tuple and check if it satisfies the
542  * constraint.
543  */
544  for (i = 0; i < numIndices; i++)
545  {
546  Relation indexRelation = relationDescs[i];
547  IndexInfo *indexInfo;
548  bool satisfiesConstraint;
549 
550  if (indexRelation == NULL)
551  continue;
552 
553  indexInfo = indexInfoArray[i];
554 
555  if (!indexInfo->ii_Unique && !indexInfo->ii_ExclusionOps)
556  continue;
557 
558  /* If the index is marked as read-only, ignore it */
559  if (!indexInfo->ii_ReadyForInserts)
560  continue;
561 
562  /* When specific arbiter indexes requested, only examine them */
563  if (arbiterIndexes != NIL &&
564  !list_member_oid(arbiterIndexes,
565  indexRelation->rd_index->indexrelid))
566  continue;
567 
568  if (!indexRelation->rd_index->indimmediate)
569  ereport(ERROR,
570  (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
571  errmsg("ON CONFLICT does not support deferrable unique constraints/exclusion constraints as arbiters"),
572  errtableconstraint(heapRelation,
573  RelationGetRelationName(indexRelation))));
574 
575  checkedIndex = true;
576 
577  /* Check for partial index */
578  if (indexInfo->ii_Predicate != NIL)
579  {
580  ExprState *predicate;
581 
582  /*
583  * If predicate state not set up yet, create it (in the estate's
584  * per-query context)
585  */
586  predicate = indexInfo->ii_PredicateState;
587  if (predicate == NULL)
588  {
589  predicate = ExecPrepareQual(indexInfo->ii_Predicate, estate);
590  indexInfo->ii_PredicateState = predicate;
591  }
592 
593  /* Skip this index-update if the predicate isn't satisfied */
594  if (!ExecQual(predicate, econtext))
595  continue;
596  }
597 
598  /*
599  * FormIndexDatum fills in its values and isnull parameters with the
600  * appropriate values for the column(s) of the index.
601  */
602  FormIndexDatum(indexInfo,
603  slot,
604  estate,
605  values,
606  isnull);
607 
608  satisfiesConstraint =
609  check_exclusion_or_unique_constraint(heapRelation, indexRelation,
610  indexInfo, &invalidItemPtr,
611  values, isnull, estate, false,
612  CEOUC_WAIT, true,
613  conflictTid);
614  if (!satisfiesConstraint)
615  return false;
616  }
617 
618  if (arbiterIndexes != NIL && !checkedIndex)
619  elog(ERROR, "unexpected failure to find arbiter index");
620 
621  return true;
622 }
void FormIndexDatum(IndexInfo *indexInfo, TupleTableSlot *slot, EState *estate, Datum *values, bool *isnull)
Definition: index.c:2660
int ri_NumIndices
Definition: execnodes.h:414
#define NIL
Definition: pg_list.h:65
Relation ri_RelationDesc
Definition: execnodes.h:411
List * ii_Predicate
Definition: execnodes.h:163
ExprState * ii_PredicateState
Definition: execnodes.h:164
int errcode(int sqlerrcode)
Definition: elog.c:698
static bool ExecQual(ExprState *state, ExprContext *econtext)
Definition: executor.h:395
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:667
#define GetPerTupleExprContext(estate)
Definition: executor.h:532
int errtableconstraint(Relation rel, const char *conname)
Definition: relcache.c:5682
Form_pg_index rd_index
Definition: rel.h:187
#define ERROR
Definition: elog.h:46
#define RelationGetRelationName(relation)
Definition: rel.h:503
ExprState * ExecPrepareQual(List *qual, EState *estate)
Definition: execExpr.c:720
bool ii_ReadyForInserts
Definition: execnodes.h:173
uintptr_t Datum
Definition: postgres.h:411
#define ereport(elevel,...)
Definition: elog.h:157
bool ii_Unique
Definition: execnodes.h:172
bool list_member_oid(const List *list, Oid datum)
Definition: list.c:689
#define INDEX_MAX_KEYS
TupleTableSlot * ecxt_scantuple
Definition: execnodes.h:226
static Datum values[MAXATTR]
Definition: bootstrap.c:166
#define ItemPointerSetInvalid(pointer)
Definition: itemptr.h:172
Oid * ii_ExclusionOps
Definition: execnodes.h:165
int errmsg(const char *fmt,...)
Definition: elog.c:909
#define elog(elevel,...)
Definition: elog.h:232
IndexInfo ** ri_IndexRelationInfo
Definition: execnodes.h:420
int i
RelationPtr ri_IndexRelationDescs
Definition: execnodes.h:417

◆ ExecCloseIndices()

void ExecCloseIndices ( ResultRelInfo resultRelInfo)

Definition at line 231 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().

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 }
int ri_NumIndices
Definition: execnodes.h:414
#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:417

◆ ExecInsertIndexTuples()

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

Definition at line 284 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, index_unchanged_by_update(), ExprEvalStep::isnull, 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().

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

◆ ExecOpenIndices()

void ExecOpenIndices ( ResultRelInfo resultRelInfo,
bool  speculative 
)

Definition at line 156 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(), ExecInitPartitionInfo(), ExecInsert(), and ExecUpdate().

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 }
int ri_NumIndices
Definition: execnodes.h:414
Relation ri_RelationDesc
Definition: execnodes.h:411
#define RelationGetForm(relation)
Definition: rel.h:463
IndexInfo * BuildIndexInfo(Relation index)
Definition: index.c:2376
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:172
static int list_length(const List *l)
Definition: pg_list.h:149
List * RelationGetIndexList(Relation relation)
Definition: relcache.c:4570
void * palloc(Size size)
Definition: mcxt.c:1062
void list_free(List *list)
Definition: list.c:1391
IndexInfo ** ri_IndexRelationInfo
Definition: execnodes.h:420
int i
void BuildSpeculativeIndexInfo(Relation index, IndexInfo *ii)
Definition: index.c:2600
Definition: pg_list.h:50
Relation index_open(Oid relationId, LOCKMODE lockmode)
Definition: indexam.c:132
RelationPtr ri_IndexRelationDescs
Definition: execnodes.h:417
#define lfirst_oid(lc)
Definition: pg_list.h:171

◆ index_expression_changed_walker()

static bool index_expression_changed_walker ( Node node,
Bitmapset allUpdatedCols 
)
static

Definition at line 1022 of file execIndexing.c.

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

Referenced by index_unchanged_by_update().

1023 {
1024  if (node == NULL)
1025  return false;
1026 
1027  if (IsA(node, Var))
1028  {
1029  Var *var = (Var *) node;
1030 
1032  allUpdatedCols))
1033  {
1034  /* Var was updated -- indicates that we should not hint */
1035  return true;
1036  }
1037 
1038  /* Still haven't found a reason to not pass the hint */
1039  return false;
1040  }
1041 
1043  (void *) allUpdatedCols);
1044 }
#define IsA(nodeptr, _type_)
Definition: nodes.h:590
AttrNumber varattno
Definition: primnodes.h:191
#define FirstLowInvalidHeapAttributeNumber
Definition: sysattr.h:27
Definition: primnodes.h:186
bool expression_tree_walker(Node *node, bool(*walker)(), void *context)
Definition: nodeFuncs.c:1904
static bool index_expression_changed_walker(Node *node, Bitmapset *allUpdatedCols)
bool bms_is_member(int x, const Bitmapset *a)
Definition: bitmapset.c:427

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

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

Referenced by check_exclusion_or_unique_constraint().

907 {
908  int indnkeyatts = IndexRelationGetNumberOfKeyAttributes(index);
909  int i;
910 
911  for (i = 0; i < indnkeyatts; i++)
912  {
913  /* Assume the exclusion operators are strict */
914  if (existing_isnull[i])
915  return false;
916 
917  if (!DatumGetBool(OidFunctionCall2Coll(constr_procs[i],
918  index->rd_indcollation[i],
919  existing_values[i],
920  new_values[i])))
921  return false;
922  }
923 
924  return true;
925 }
Oid * rd_indcollation
Definition: rel.h:212
#define DatumGetBool(X)
Definition: postgres.h:437
#define IndexRelationGetNumberOfKeyAttributes(relation)
Definition: rel.h:488
Datum OidFunctionCall2Coll(Oid functionId, Oid collation, Datum arg1, Datum arg2)
Definition: fmgr.c:1420
int i

◆ index_unchanged_by_update()

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

Definition at line 935 of file execIndexing.c.

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

Referenced by ExecInsertIndexTuples().

937 {
938  Bitmapset *updatedCols = ExecGetUpdatedCols(resultRelInfo, estate);
939  Bitmapset *extraUpdatedCols = ExecGetExtraUpdatedCols(resultRelInfo, estate);
940  Bitmapset *allUpdatedCols;
941  bool hasexpression = false;
942  List *idxExprs;
943 
944  /*
945  * Check for indexed attribute overlap with updated columns.
946  *
947  * Only do this for key columns. A change to a non-key column within an
948  * INCLUDE index should not be counted here. Non-key column values are
949  * opaque payload state to the index AM, a little like an extra table TID.
950  */
951  for (int attr = 0; attr < indexInfo->ii_NumIndexKeyAttrs; attr++)
952  {
953  int keycol = indexInfo->ii_IndexAttrNumbers[attr];
954 
955  if (keycol <= 0)
956  {
957  /*
958  * Skip expressions for now, but remember to deal with them later
959  * on
960  */
961  hasexpression = true;
962  continue;
963  }
964 
966  updatedCols) ||
968  extraUpdatedCols))
969  {
970  /* Changed key column -- don't hint for this index */
971  return false;
972  }
973  }
974 
975  /*
976  * When we get this far and index has no expressions, return true so that
977  * index_insert() call will go on to pass 'indexUnchanged' = true hint.
978  *
979  * The _absence_ of an indexed key attribute that overlaps with updated
980  * attributes (in addition to the total absence of indexed expressions)
981  * shows that the index as a whole is logically unchanged by UPDATE.
982  */
983  if (!hasexpression)
984  return true;
985 
986  /*
987  * Need to pass only one bms to expression_tree_walker helper function.
988  * Avoid allocating memory in common case where there are no extra cols.
989  */
990  if (!extraUpdatedCols)
991  allUpdatedCols = updatedCols;
992  else
993  allUpdatedCols = bms_union(updatedCols, extraUpdatedCols);
994 
995  /*
996  * We have to work slightly harder in the event of indexed expressions,
997  * but the principle is the same as before: try to find columns (Vars,
998  * actually) that overlap with known-updated columns.
999  *
1000  * If we find any matching Vars, don't pass hint for index. Otherwise
1001  * pass hint.
1002  */
1003  idxExprs = RelationGetIndexExpressions(indexRelation);
1004  hasexpression = index_expression_changed_walker((Node *) idxExprs,
1005  allUpdatedCols);
1006  list_free(idxExprs);
1007  if (extraUpdatedCols)
1008  bms_free(allUpdatedCols);
1009 
1010  if (hasexpression)
1011  return false;
1012 
1013  return true;
1014 }
Bitmapset * ExecGetExtraUpdatedCols(ResultRelInfo *relinfo, EState *estate)
Definition: execUtils.c:1321
Bitmapset * ExecGetUpdatedCols(ResultRelInfo *relinfo, EState *estate)
Definition: execUtils.c:1295
Definition: nodes.h:539
#define FirstLowInvalidHeapAttributeNumber
Definition: sysattr.h:27
int ii_NumIndexKeyAttrs
Definition: execnodes.h:159
List * RelationGetIndexExpressions(Relation relation)
Definition: relcache.c:4804
void bms_free(Bitmapset *a)
Definition: bitmapset.c:208
Bitmapset * bms_union(const Bitmapset *a, const Bitmapset *b)
Definition: bitmapset.c:225
static bool index_expression_changed_walker(Node *node, Bitmapset *allUpdatedCols)
void list_free(List *list)
Definition: list.c:1391
AttrNumber ii_IndexAttrNumbers[INDEX_MAX_KEYS]
Definition: execnodes.h:160
Definition: pg_list.h:50
bool bms_is_member(int x, const Bitmapset *a)
Definition: bitmapset.c:427