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

References CEOUC_WAIT, and check_exclusion_or_unique_constraint().

Referenced by IndexCheckExclusion(), and unique_key_recheck().

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

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

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

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

Definition at line 224 of file execIndexing.c.

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

Referenced by apply_handle_delete(), apply_handle_insert(), apply_handle_update(), CatalogCloseIndexes(), CopyFrom(), ExecCleanUpTriggerState(), 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:357
#define RowExclusiveLock
Definition: lockdefs.h:38
void index_close(Relation relation, LOCKMODE lockmode)
Definition: indexam.c:176
int i
RelationPtr ri_IndexRelationDescs
Definition: execnodes.h:360
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, ExecPrepareQual(), 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, 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  ExprState *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 == NULL)
338  {
339  predicate = ExecPrepareQual(indexInfo->ii_Predicate, estate);
340  indexInfo->ii_PredicateState = predicate;
341  }
342 
343  /* Skip this index-update if the predicate isn't satisfied */
344  if (!ExecQual(predicate, econtext))
345  continue;
346  }
347 
348  /*
349  * FormIndexDatum fills in its values and isnull parameters with the
350  * appropriate values for the column(s) of the index.
351  */
352  FormIndexDatum(indexInfo,
353  slot,
354  estate,
355  values,
356  isnull);
357 
358  /* Check whether to apply noDupErr to this index */
359  applyNoDupErr = noDupErr &&
360  (arbiterIndexes == NIL ||
361  list_member_oid(arbiterIndexes,
362  indexRelation->rd_index->indexrelid));
363 
364  /*
365  * The index AM does the actual insertion, plus uniqueness checking.
366  *
367  * For an immediate-mode unique index, we just tell the index AM to
368  * throw error if not unique.
369  *
370  * For a deferrable unique index, we tell the index AM to just detect
371  * possible non-uniqueness, and we add the index OID to the result
372  * list if further checking is needed.
373  *
374  * For a speculative insertion (used by INSERT ... ON CONFLICT), do
375  * the same as for a deferrable unique index.
376  */
377  if (!indexRelation->rd_index->indisunique)
378  checkUnique = UNIQUE_CHECK_NO;
379  else if (applyNoDupErr)
380  checkUnique = UNIQUE_CHECK_PARTIAL;
381  else if (indexRelation->rd_index->indimmediate)
382  checkUnique = UNIQUE_CHECK_YES;
383  else
384  checkUnique = UNIQUE_CHECK_PARTIAL;
385 
386  satisfiesConstraint =
387  index_insert(indexRelation, /* index relation */
388  values, /* array of index Datums */
389  isnull, /* null flags */
390  tupleid, /* tid of heap tuple */
391  heapRelation, /* heap relation */
392  checkUnique, /* type of uniqueness check to do */
393  indexInfo); /* index AM may need this */
394 
395  /*
396  * If the index has an associated exclusion constraint, check that.
397  * This is simpler than the process for uniqueness checks since we
398  * always insert first and then check. If the constraint is deferred,
399  * we check now anyway, but don't throw error on violation or wait for
400  * a conclusive outcome from a concurrent insertion; instead we'll
401  * queue a recheck event. Similarly, noDupErr callers (speculative
402  * inserters) will recheck later, and wait for a conclusive outcome
403  * then.
404  *
405  * An index for an exclusion constraint can't also be UNIQUE (not an
406  * essential property, we just don't allow it in the grammar), so no
407  * need to preserve the prior state of satisfiesConstraint.
408  */
409  if (indexInfo->ii_ExclusionOps != NULL)
410  {
411  bool violationOK;
412  CEOUC_WAIT_MODE waitMode;
413 
414  if (applyNoDupErr)
415  {
416  violationOK = true;
418  }
419  else if (!indexRelation->rd_index->indimmediate)
420  {
421  violationOK = true;
422  waitMode = CEOUC_NOWAIT;
423  }
424  else
425  {
426  violationOK = false;
427  waitMode = CEOUC_WAIT;
428  }
429 
430  satisfiesConstraint =
432  indexRelation, indexInfo,
433  tupleid, values, isnull,
434  estate, false,
435  waitMode, violationOK, NULL);
436  }
437 
438  if ((checkUnique == UNIQUE_CHECK_PARTIAL ||
439  indexInfo->ii_ExclusionOps != NULL) &&
440  !satisfiesConstraint)
441  {
442  /*
443  * The tuple potentially violates the uniqueness or exclusion
444  * constraint, so make a note of the index so that we can re-check
445  * it later. Speculative inserters are told if there was a
446  * speculative conflict, since that always requires a restart.
447  */
448  result = lappend_oid(result, RelationGetRelid(indexRelation));
449  if (indexRelation->rd_index->indimmediate && specConflict)
450  *specConflict = true;
451  }
452  }
453 
454  return result;
455 }
void FormIndexDatum(IndexInfo *indexInfo, TupleTableSlot *slot, EState *estate, Datum *values, bool *isnull)
Definition: index.c:1771
int ri_NumIndices
Definition: execnodes.h:357
#define NIL
Definition: pg_list.h:69
Relation ri_RelationDesc
Definition: execnodes.h:354
List * ii_Predicate
Definition: execnodes.h:138
ExprState * ii_PredicateState
Definition: execnodes.h:139
static bool ExecQual(ExprState *state, ExprContext *econtext)
Definition: executor.h:366
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:639
IndexUniqueCheck
Definition: genam.h:111
#define GetPerTupleExprContext(estate)
Definition: executor.h:477
Form_pg_index rd_index
Definition: rel.h:159
ExprState * ExecPrepareQual(List *qual, EState *estate)
Definition: execExpr.c:465
bool ii_ReadyForInserts
Definition: execnodes.h:147
uintptr_t Datum
Definition: postgres.h:372
bool list_member_oid(const List *list, Oid datum)
Definition: list.c:505
#define INDEX_MAX_KEYS
TupleTableSlot * ecxt_scantuple
Definition: execnodes.h:197
static Datum values[MAXATTR]
Definition: bootstrap.c:164
Oid * ii_ExclusionOps
Definition: execnodes.h:140
IndexInfo ** ri_IndexRelationInfo
Definition: execnodes.h:363
int i
CEOUC_WAIT_MODE
Definition: execIndexing.c:118
Definition: pg_list.h:45
#define RelationGetRelid(relation)
Definition: rel.h:416
RelationPtr ri_IndexRelationDescs
Definition: execnodes.h:360
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:443
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:357
Relation ri_RelationDesc
Definition: execnodes.h:354
#define RelationGetForm(relation)
Definition: rel.h:410
IndexInfo * BuildIndexInfo(Relation index)
Definition: index.c:1642
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:146
static int list_length(const List *l)
Definition: pg_list.h:89
List * RelationGetIndexList(Relation relation)
Definition: relcache.c:4357
void * palloc(Size size)
Definition: mcxt.c:848
void list_free(List *list)
Definition: list.c:1133
IndexInfo ** ri_IndexRelationInfo
Definition: execnodes.h:363
int i
void BuildSpeculativeIndexInfo(Relation index, IndexInfo *ii)
Definition: index.c:1713
Definition: pg_list.h:45
Relation index_open(Oid relationId, LOCKMODE lockmode)
Definition: indexam.c:151
RelationPtr ri_IndexRelationDescs
Definition: execnodes.h:360
#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 880 of file execIndexing.c.

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

Referenced by check_exclusion_or_unique_constraint().

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