PostgreSQL Source Code  git master
 All Data Structures Namespaces Files Functions Variables Typedefs Enumerations Enumerator Macros
execIndexing.c File Reference
#include "postgres.h"
#include "access/relscan.h"
#include "access/xact.h"
#include "catalog/index.h"
#include "executor/executor.h"
#include "nodes/nodeFuncs.h"
#include "storage/lmgr.h"
#include "utils/tqual.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 (TupleTableSlot *slot, ItemPointer tupleid, EState *estate, bool noDupErr, bool *specConflict, List *arbiterIndexes)
 
bool ExecCheckIndexConstraints (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

Enumerator
CEOUC_WAIT 
CEOUC_NOWAIT 
CEOUC_LIVELOCK_PREVENTING_WAIT 

Definition at line 118 of file execIndexing.c.

Function Documentation

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

Definition at line 867 of file execIndexing.c.

References CEOUC_WAIT, check_exclusion_or_unique_constraint(), and NULL.

Referenced by IndexCheckExclusion(), and unique_key_recheck().

872 {
873  (void) check_exclusion_or_unique_constraint(heap, index, indexInfo, tupleid,
874  values, isnull,
875  estate, newIndex,
876  CEOUC_WAIT, false, NULL);
877 }
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 NULL
Definition: c.h:226
static Datum values[MAXATTR]
Definition: bootstrap.c:162
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(), ExecStoreTuple(), 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(), INDEX_MAX_KEYS, index_recheck_constraint(), index_rescan(), InitDirtySnapshot, InvalidBuffer, InvalidOid, ItemPointerEquals(), ItemPointerIsValid, MakeSingleTupleTableSlot(), NULL, RelationData::rd_indcollation, RelationData::rd_index, RelationGetDescr, RelationGetRelationName, ScanKeyEntryInitialize(), SpeculativeInsertionWait(), SnapshotData::speculativeToken, HeapTupleHeaderData::t_ctid, HeapTupleData::t_data, HeapTupleData::t_self, TransactionIdIsValid, TransactionIdPrecedes(), 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 index_natts = index->rd_index->indnatts;
656  IndexScanDesc index_scan;
657  HeapTuple tup;
658  ScanKeyData scankeys[INDEX_MAX_KEYS];
659  SnapshotData DirtySnapshot;
660  int i;
661  bool conflict;
662  bool found_self;
663  ExprContext *econtext;
664  TupleTableSlot *existing_slot;
665  TupleTableSlot *save_scantuple;
666 
667  if (indexInfo->ii_ExclusionOps)
668  {
669  constr_procs = indexInfo->ii_ExclusionProcs;
670  constr_strats = indexInfo->ii_ExclusionStrats;
671  }
672  else
673  {
674  constr_procs = indexInfo->ii_UniqueProcs;
675  constr_strats = indexInfo->ii_UniqueStrats;
676  }
677 
678  /*
679  * If any of the input values are NULL, the constraint check is assumed to
680  * pass (i.e., we assume the operators are strict).
681  */
682  for (i = 0; i < index_natts; i++)
683  {
684  if (isnull[i])
685  return true;
686  }
687 
688  /*
689  * Search the tuples that are in the index for any violations, including
690  * tuples that aren't visible yet.
691  */
692  InitDirtySnapshot(DirtySnapshot);
693 
694  for (i = 0; i < index_natts; i++)
695  {
696  ScanKeyEntryInitialize(&scankeys[i],
697  0,
698  i + 1,
699  constr_strats[i],
700  InvalidOid,
701  index_collations[i],
702  constr_procs[i],
703  values[i]);
704  }
705 
706  /*
707  * Need a TupleTableSlot to put existing tuples in.
708  *
709  * To use FormIndexDatum, we have to make the econtext's scantuple point
710  * to this slot. Be sure to save and restore caller's value for
711  * scantuple.
712  */
713  existing_slot = MakeSingleTupleTableSlot(RelationGetDescr(heap));
714 
715  econtext = GetPerTupleExprContext(estate);
716  save_scantuple = econtext->ecxt_scantuple;
717  econtext->ecxt_scantuple = existing_slot;
718 
719  /*
720  * May have to restart scan from this point if a potential conflict is
721  * found.
722  */
723 retry:
724  conflict = false;
725  found_self = false;
726  index_scan = index_beginscan(heap, index, &DirtySnapshot, index_natts, 0);
727  index_rescan(index_scan, scankeys, index_natts, NULL, 0);
728 
729  while ((tup = index_getnext(index_scan,
731  {
732  TransactionId xwait;
733  ItemPointerData ctid_wait;
734  XLTW_Oper reason_wait;
735  Datum existing_values[INDEX_MAX_KEYS];
736  bool existing_isnull[INDEX_MAX_KEYS];
737  char *error_new;
738  char *error_existing;
739 
740  /*
741  * Ignore the entry for the tuple we're trying to check.
742  */
743  if (ItemPointerIsValid(tupleid) &&
744  ItemPointerEquals(tupleid, &tup->t_self))
745  {
746  if (found_self) /* should not happen */
747  elog(ERROR, "found self tuple multiple times in index \"%s\"",
748  RelationGetRelationName(index));
749  found_self = true;
750  continue;
751  }
752 
753  /*
754  * Extract the index column values and isnull flags from the existing
755  * tuple.
756  */
757  ExecStoreTuple(tup, existing_slot, InvalidBuffer, false);
758  FormIndexDatum(indexInfo, existing_slot, estate,
759  existing_values, existing_isnull);
760 
761  /* If lossy indexscan, must recheck the condition */
762  if (index_scan->xs_recheck)
763  {
764  if (!index_recheck_constraint(index,
765  constr_procs,
766  existing_values,
767  existing_isnull,
768  values))
769  continue; /* tuple doesn't actually match, so no
770  * conflict */
771  }
772 
773  /*
774  * At this point we have either a conflict or a potential conflict.
775  *
776  * If an in-progress transaction is affecting the visibility of this
777  * tuple, we need to wait for it to complete and then recheck (unless
778  * the caller requested not to). For simplicity we do rechecking by
779  * just restarting the whole scan --- this case probably doesn't
780  * happen often enough to be worth trying harder, and anyway we don't
781  * want to hold any index internal locks while waiting.
782  */
783  xwait = TransactionIdIsValid(DirtySnapshot.xmin) ?
784  DirtySnapshot.xmin : DirtySnapshot.xmax;
785 
786  if (TransactionIdIsValid(xwait) &&
787  (waitMode == CEOUC_WAIT ||
788  (waitMode == CEOUC_LIVELOCK_PREVENTING_WAIT &&
789  DirtySnapshot.speculativeToken &&
791  {
792  ctid_wait = tup->t_data->t_ctid;
793  reason_wait = indexInfo->ii_ExclusionOps ?
795  index_endscan(index_scan);
796  if (DirtySnapshot.speculativeToken)
797  SpeculativeInsertionWait(DirtySnapshot.xmin,
798  DirtySnapshot.speculativeToken);
799  else
800  XactLockTableWait(xwait, heap, &ctid_wait, reason_wait);
801  goto retry;
802  }
803 
804  /*
805  * We have a definite conflict (or a potential one, but the caller
806  * didn't want to wait). Return it to caller, or report it.
807  */
808  if (violationOK)
809  {
810  conflict = true;
811  if (conflictTid)
812  *conflictTid = tup->t_self;
813  break;
814  }
815 
816  error_new = BuildIndexValueDescription(index, values, isnull);
817  error_existing = BuildIndexValueDescription(index, existing_values,
818  existing_isnull);
819  if (newIndex)
820  ereport(ERROR,
821  (errcode(ERRCODE_EXCLUSION_VIOLATION),
822  errmsg("could not create exclusion constraint \"%s\"",
823  RelationGetRelationName(index)),
824  error_new && error_existing ?
825  errdetail("Key %s conflicts with key %s.",
826  error_new, error_existing) :
827  errdetail("Key conflicts exist."),
828  errtableconstraint(heap,
829  RelationGetRelationName(index))));
830  else
831  ereport(ERROR,
832  (errcode(ERRCODE_EXCLUSION_VIOLATION),
833  errmsg("conflicting key value violates exclusion constraint \"%s\"",
834  RelationGetRelationName(index)),
835  error_new && error_existing ?
836  errdetail("Key %s conflicts with existing key %s.",
837  error_new, error_existing) :
838  errdetail("Key conflicts with existing key."),
839  errtableconstraint(heap,
840  RelationGetRelationName(index))));
841  }
842 
843  index_endscan(index_scan);
844 
845  /*
846  * Ordinarily, at this point the search should have found the originally
847  * inserted tuple (if any), unless we exited the loop early because of
848  * conflict. However, it is possible to define exclusion constraints for
849  * which that wouldn't be true --- for instance, if the operator is <>. So
850  * we no longer complain if found_self is still false.
851  */
852 
853  econtext->ecxt_scantuple = save_scantuple;
854 
855  ExecDropSingleTupleTableSlot(existing_slot);
856 
857  return !conflict;
858 }
#define ItemPointerIsValid(pointer)
Definition: itemptr.h:59
void FormIndexDatum(IndexInfo *indexInfo, TupleTableSlot *slot, EState *estate, Datum *values, bool *isnull)
Definition: index.c:1764
TupleTableSlot * ExecStoreTuple(HeapTuple tuple, TupleTableSlot *slot, Buffer buffer, bool shouldFree)
Definition: execTuples.c:320
uint16 * ii_UniqueStrats
Definition: execnodes.h:76
uint32 TransactionId
Definition: c.h:394
#define RelationGetDescr(relation)
Definition: rel.h:425
#define InvalidBuffer
Definition: buf.h:25
void index_rescan(IndexScanDesc scan, ScanKey keys, int nkeys, ScanKey orderbys, int norderbys)
Definition: indexam.c:310
Oid * ii_ExclusionProcs
Definition: execnodes.h:72
int errcode(int sqlerrcode)
Definition: elog.c:575
unsigned int Oid
Definition: postgres_ext.h:31
HeapTupleHeader t_data
Definition: htup.h:67
#define GetPerTupleExprContext(estate)
Definition: executor.h:338
int errtableconstraint(Relation rel, const char *conname)
Definition: relcache.c:5209
Form_pg_index rd_index
Definition: rel.h:155
unsigned short uint16
Definition: c.h:264
Oid * rd_indcollation
Definition: rel.h:189
static bool index_recheck_constraint(Relation index, Oid *constr_procs, Datum *existing_values, bool *existing_isnull, Datum *new_values)
Definition: execIndexing.c:884
#define ERROR
Definition: elog.h:43
#define InitDirtySnapshot(snapshotdata)
Definition: tqual.h:100
ItemPointerData t_ctid
Definition: htup_details.h:150
ItemPointerData t_self
Definition: htup.h:65
void SpeculativeInsertionWait(TransactionId xid, uint32 token)
Definition: lmgr.c:685
TransactionId GetCurrentTransactionId(void)
Definition: xact.c:416
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:216
Oid * ii_UniqueProcs
Definition: execnodes.h:75
int errdetail(const char *fmt,...)
Definition: elog.c:873
#define RelationGetRelationName(relation)
Definition: rel.h:433
TransactionId xmax
Definition: snapshot.h:67
TransactionId xmin
Definition: snapshot.h:66
TupleTableSlot * MakeSingleTupleTableSlot(TupleDesc tupdesc)
Definition: execTuples.c:199
void index_endscan(IndexScanDesc scan)
Definition: indexam.c:340
#define ereport(elevel, rest)
Definition: elog.h:122
bool TransactionIdPrecedes(TransactionId id1, TransactionId id2)
Definition: transam.c:300
uintptr_t Datum
Definition: postgres.h:374
#define InvalidOid
Definition: postgres_ext.h:36
uint32 speculativeToken
Definition: snapshot.h:102
void XactLockTableWait(TransactionId xid, Relation rel, ItemPointer ctid, XLTW_Oper oper)
Definition: lmgr.c:554
#define NULL
Definition: c.h:226
#define INDEX_MAX_KEYS
TupleTableSlot * ecxt_scantuple
Definition: execnodes.h:128
bool ItemPointerEquals(ItemPointer pointer1, ItemPointer pointer2)
Definition: itemptr.c:29
static Datum values[MAXATTR]
Definition: bootstrap.c:162
XLTW_Oper
Definition: lmgr.h:24
Oid * ii_ExclusionOps
Definition: execnodes.h:71
int errmsg(const char *fmt,...)
Definition: elog.c:797
int i
#define elog
Definition: elog.h:219
char * BuildIndexValueDescription(Relation indexRelation, Datum *values, bool *isnull)
Definition: genam.c:171
#define TransactionIdIsValid(xid)
Definition: transam.h:41
uint16 * ii_ExclusionStrats
Definition: execnodes.h:73
HeapTuple index_getnext(IndexScanDesc scan, ScanDirection direction)
Definition: indexam.c:659
IndexScanDesc index_beginscan(Relation heapRelation, Relation indexRelation, Snapshot snapshot, int nkeys, int norderbys)
Definition: indexam.c:221
bool ExecCheckIndexConstraints ( TupleTableSlot slot,
EState estate,
ItemPointer  conflictTid,
List arbiterIndexes 
)

Definition at line 477 of file execIndexing.c.

References CEOUC_WAIT, check_exclusion_or_unique_constraint(), ExprContext::ecxt_scantuple, elog, ereport, errcode(), errmsg(), ERROR, errtableconstraint(), EState::es_result_relation_info, ExecPrepareExpr(), 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, NULL, RelationData::rd_index, RelationGetRelationName, ResultRelInfo::ri_IndexRelationDescs, ResultRelInfo::ri_IndexRelationInfo, ResultRelInfo::ri_NumIndices, ResultRelInfo::ri_RelationDesc, and values.

Referenced by ExecInsert().

480 {
481  ResultRelInfo *resultRelInfo;
482  int i;
483  int numIndices;
484  RelationPtr relationDescs;
485  Relation heapRelation;
486  IndexInfo **indexInfoArray;
487  ExprContext *econtext;
489  bool isnull[INDEX_MAX_KEYS];
490  ItemPointerData invalidItemPtr;
491  bool checkedIndex = false;
492 
493  ItemPointerSetInvalid(conflictTid);
494  ItemPointerSetInvalid(&invalidItemPtr);
495 
496  /*
497  * Get information from the result relation info structure.
498  */
499  resultRelInfo = estate->es_result_relation_info;
500  numIndices = resultRelInfo->ri_NumIndices;
501  relationDescs = resultRelInfo->ri_IndexRelationDescs;
502  indexInfoArray = resultRelInfo->ri_IndexRelationInfo;
503  heapRelation = resultRelInfo->ri_RelationDesc;
504 
505  /*
506  * We will use the EState's per-tuple context for evaluating predicates
507  * and index expressions (creating it if it's not already there).
508  */
509  econtext = GetPerTupleExprContext(estate);
510 
511  /* Arrange for econtext's scan tuple to be the tuple under test */
512  econtext->ecxt_scantuple = slot;
513 
514  /*
515  * For each index, form index tuple and check if it satisfies the
516  * constraint.
517  */
518  for (i = 0; i < numIndices; i++)
519  {
520  Relation indexRelation = relationDescs[i];
521  IndexInfo *indexInfo;
522  bool satisfiesConstraint;
523 
524  if (indexRelation == NULL)
525  continue;
526 
527  indexInfo = indexInfoArray[i];
528 
529  if (!indexInfo->ii_Unique && !indexInfo->ii_ExclusionOps)
530  continue;
531 
532  /* If the index is marked as read-only, ignore it */
533  if (!indexInfo->ii_ReadyForInserts)
534  continue;
535 
536  /* When specific arbiter indexes requested, only examine them */
537  if (arbiterIndexes != NIL &&
538  !list_member_oid(arbiterIndexes,
539  indexRelation->rd_index->indexrelid))
540  continue;
541 
542  if (!indexRelation->rd_index->indimmediate)
543  ereport(ERROR,
544  (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
545  errmsg("ON CONFLICT does not support deferrable unique constraints/exclusion constraints as arbiters"),
546  errtableconstraint(heapRelation,
547  RelationGetRelationName(indexRelation))));
548 
549  checkedIndex = true;
550 
551  /* Check for partial index */
552  if (indexInfo->ii_Predicate != NIL)
553  {
554  List *predicate;
555 
556  /*
557  * If predicate state not set up yet, create it (in the estate's
558  * per-query context)
559  */
560  predicate = indexInfo->ii_PredicateState;
561  if (predicate == NIL)
562  {
563  predicate = (List *)
564  ExecPrepareExpr((Expr *) indexInfo->ii_Predicate,
565  estate);
566  indexInfo->ii_PredicateState = predicate;
567  }
568 
569  /* Skip this index-update if the predicate isn't satisfied */
570  if (!ExecQual(predicate, econtext, false))
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:1764
int ri_NumIndices
Definition: execnodes.h:336
#define NIL
Definition: pg_list.h:69
Relation ri_RelationDesc
Definition: execnodes.h:335
ExprState * ExecPrepareExpr(Expr *node, EState *estate)
Definition: execQual.c:5004
List * ii_Predicate
Definition: execnodes.h:69
int errcode(int sqlerrcode)
Definition: elog.c:575
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:338
int errtableconstraint(Relation rel, const char *conname)
Definition: relcache.c:5209
Form_pg_index rd_index
Definition: rel.h:155
#define ERROR
Definition: elog.h:43
List * ii_PredicateState
Definition: execnodes.h:70
bool ExecQual(List *qual, ExprContext *econtext, bool resultForNull)
Definition: execQual.c:5055
#define RelationGetRelationName(relation)
Definition: rel.h:433
bool ii_ReadyForInserts
Definition: execnodes.h:78
#define ereport(elevel, rest)
Definition: elog.h:122
uintptr_t Datum
Definition: postgres.h:374
bool ii_Unique
Definition: execnodes.h:77
bool list_member_oid(const List *list, Oid datum)
Definition: list.c:505
#define NULL
Definition: c.h:226
#define INDEX_MAX_KEYS
TupleTableSlot * ecxt_scantuple
Definition: execnodes.h:128
static Datum values[MAXATTR]
Definition: bootstrap.c:162
#define ItemPointerSetInvalid(pointer)
Definition: itemptr.h:131
Oid * ii_ExclusionOps
Definition: execnodes.h:71
int errmsg(const char *fmt,...)
Definition: elog.c:797
IndexInfo ** ri_IndexRelationInfo
Definition: execnodes.h:338
int i
#define elog
Definition: elog.h:219
Definition: pg_list.h:45
RelationPtr ri_IndexRelationDescs
Definition: execnodes.h:337
ResultRelInfo * es_result_relation_info
Definition: execnodes.h:384
void ExecCloseIndices ( ResultRelInfo resultRelInfo)

Definition at line 224 of file execIndexing.c.

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

Referenced by afterTriggerInvokeEvents(), apply_handle_delete(), apply_handle_insert(), apply_handle_update(), CatalogCloseIndexes(), CopyFrom(), EvalPlanQualEnd(), ExecEndModifyTable(), and ExecEndPlan().

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

Definition at line 271 of file execIndexing.c.

References CEOUC_LIVELOCK_PREVENTING_WAIT, CEOUC_NOWAIT, CEOUC_WAIT, check_exclusion_or_unique_constraint(), ExprContext::ecxt_scantuple, EState::es_result_relation_info, ExecPrepareExpr(), ExecQual(), FormIndexDatum(), GetPerTupleExprContext, i, IndexInfo::ii_ExclusionOps, IndexInfo::ii_Predicate, IndexInfo::ii_PredicateState, IndexInfo::ii_ReadyForInserts, index_insert(), INDEX_MAX_KEYS, lappend_oid(), list_member_oid(), NIL, NULL, RelationData::rd_index, RelationGetRelid, ResultRelInfo::ri_IndexRelationDescs, ResultRelInfo::ri_IndexRelationInfo, ResultRelInfo::ri_NumIndices, ResultRelInfo::ri_RelationDesc, UNIQUE_CHECK_NO, UNIQUE_CHECK_PARTIAL, UNIQUE_CHECK_YES, and values.

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

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

Definition at line 149 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(), apply_handle_insert(), apply_handle_update(), CatalogOpenIndexes(), CopyFrom(), ExecInitModifyTable(), and ExecSetupPartitionTupleRouting().

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

Definition at line 884 of file execIndexing.c.

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

Referenced by check_exclusion_or_unique_constraint().

887 {
888  int index_natts = index->rd_index->indnatts;
889  int i;
890 
891  for (i = 0; i < index_natts; i++)
892  {
893  /* Assume the exclusion operators are strict */
894  if (existing_isnull[i])
895  return false;
896 
897  if (!DatumGetBool(OidFunctionCall2Coll(constr_procs[i],
898  index->rd_indcollation[i],
899  existing_values[i],
900  new_values[i])))
901  return false;
902  }
903 
904  return true;
905 }
Form_pg_index rd_index
Definition: rel.h:155
Oid * rd_indcollation
Definition: rel.h:189
#define DatumGetBool(X)
Definition: postgres.h:401
Datum OidFunctionCall2Coll(Oid functionId, Oid collation, Datum arg1, Datum arg2)
Definition: fmgr.c:1601
int i