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/multirangetypes.h"
#include "utils/rangetypes.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, const Datum *values, const bool *isnull, EState *estate, bool newIndex, CEOUC_WAIT_MODE waitMode, bool violationOK, ItemPointer conflictTid)
 
static bool index_recheck_constraint (Relation index, const Oid *constr_procs, const Datum *existing_values, const bool *existing_isnull, const 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)
 
static void ExecWithoutOverlapsNotEmpty (Relation rel, NameData attname, Datum attval, char typtype, Oid atttypid)
 
void ExecOpenIndices (ResultRelInfo *resultRelInfo, bool speculative)
 
void ExecCloseIndices (ResultRelInfo *resultRelInfo)
 
ListExecInsertIndexTuples (ResultRelInfo *resultRelInfo, TupleTableSlot *slot, EState *estate, bool update, bool noDupErr, bool *specConflict, List *arbiterIndexes, bool onlySummarizing)
 
bool ExecCheckIndexConstraints (ResultRelInfo *resultRelInfo, TupleTableSlot *slot, EState *estate, ItemPointer conflictTid, ItemPointer tupleid, List *arbiterIndexes)
 
void check_exclusion_constraint (Relation heap, Relation index, IndexInfo *indexInfo, ItemPointer tupleid, const Datum *values, const bool *isnull, EState *estate, bool newIndex)
 

Enumeration Type Documentation

◆ CEOUC_WAIT_MODE

Enumerator
CEOUC_WAIT 
CEOUC_NOWAIT 
CEOUC_LIVELOCK_PREVENTING_WAIT 

Definition at line 122 of file execIndexing.c.

123{
CEOUC_WAIT_MODE
Definition: execIndexing.c:123
@ CEOUC_NOWAIT
Definition: execIndexing.c:125
@ CEOUC_WAIT
Definition: execIndexing.c:124
@ CEOUC_LIVELOCK_PREVENTING_WAIT
Definition: execIndexing.c:126

Function Documentation

◆ check_exclusion_constraint()

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

Definition at line 956 of file execIndexing.c.

961{
962 (void) check_exclusion_or_unique_constraint(heap, index, indexInfo, tupleid,
963 values, isnull,
964 estate, newIndex,
965 CEOUC_WAIT, false, NULL);
966}
static Datum values[MAXATTR]
Definition: bootstrap.c:151
static bool check_exclusion_or_unique_constraint(Relation heap, Relation index, IndexInfo *indexInfo, ItemPointer tupleid, const Datum *values, const bool *isnull, EState *estate, bool newIndex, CEOUC_WAIT_MODE waitMode, bool violationOK, ItemPointer conflictTid)
Definition: execIndexing.c:704
Definition: type.h:96

References CEOUC_WAIT, check_exclusion_or_unique_constraint(), and values.

Referenced by IndexCheckExclusion().

◆ check_exclusion_or_unique_constraint()

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

Definition at line 704 of file execIndexing.c.

712{
713 Oid *constr_procs;
714 uint16 *constr_strats;
715 Oid *index_collations = index->rd_indcollation;
717 IndexScanDesc index_scan;
718 ScanKeyData scankeys[INDEX_MAX_KEYS];
719 SnapshotData DirtySnapshot;
720 int i;
721 bool conflict;
722 bool found_self;
723 ExprContext *econtext;
724 TupleTableSlot *existing_slot;
725 TupleTableSlot *save_scantuple;
726
727 if (indexInfo->ii_ExclusionOps)
728 {
729 constr_procs = indexInfo->ii_ExclusionProcs;
730 constr_strats = indexInfo->ii_ExclusionStrats;
731 }
732 else
733 {
734 constr_procs = indexInfo->ii_UniqueProcs;
735 constr_strats = indexInfo->ii_UniqueStrats;
736 }
737
738 /*
739 * If this is a WITHOUT OVERLAPS constraint, we must also forbid empty
740 * ranges/multiranges. This must happen before we look for NULLs below, or
741 * a UNIQUE constraint could insert an empty range along with a NULL
742 * scalar part.
743 */
744 if (indexInfo->ii_WithoutOverlaps)
745 {
746 /*
747 * Look up the type from the heap tuple, but check the Datum from the
748 * index tuple.
749 */
750 AttrNumber attno = indexInfo->ii_IndexAttrNumbers[indnkeyatts - 1];
751
752 if (!isnull[indnkeyatts - 1])
753 {
754 TupleDesc tupdesc = RelationGetDescr(heap);
755 Form_pg_attribute att = TupleDescAttr(tupdesc, attno - 1);
756 TypeCacheEntry *typcache = lookup_type_cache(att->atttypid, 0);
757
758 ExecWithoutOverlapsNotEmpty(heap, att->attname,
759 values[indnkeyatts - 1],
760 typcache->typtype, att->atttypid);
761 }
762 }
763
764 /*
765 * If any of the input values are NULL, and the index uses the default
766 * nulls-are-distinct mode, the constraint check is assumed to pass (i.e.,
767 * we assume the operators are strict). Otherwise, we interpret the
768 * constraint as specifying IS NULL for each column whose input value is
769 * NULL.
770 */
771 if (!indexInfo->ii_NullsNotDistinct)
772 {
773 for (i = 0; i < indnkeyatts; i++)
774 {
775 if (isnull[i])
776 return true;
777 }
778 }
779
780 /*
781 * Search the tuples that are in the index for any violations, including
782 * tuples that aren't visible yet.
783 */
784 InitDirtySnapshot(DirtySnapshot);
785
786 for (i = 0; i < indnkeyatts; i++)
787 {
788 ScanKeyEntryInitialize(&scankeys[i],
789 isnull[i] ? SK_ISNULL | SK_SEARCHNULL : 0,
790 i + 1,
791 constr_strats[i],
793 index_collations[i],
794 constr_procs[i],
795 values[i]);
796 }
797
798 /*
799 * Need a TupleTableSlot to put existing tuples in.
800 *
801 * To use FormIndexDatum, we have to make the econtext's scantuple point
802 * to this slot. Be sure to save and restore caller's value for
803 * scantuple.
804 */
805 existing_slot = table_slot_create(heap, NULL);
806
807 econtext = GetPerTupleExprContext(estate);
808 save_scantuple = econtext->ecxt_scantuple;
809 econtext->ecxt_scantuple = existing_slot;
810
811 /*
812 * May have to restart scan from this point if a potential conflict is
813 * found.
814 */
815retry:
816 conflict = false;
817 found_self = false;
818 index_scan = index_beginscan(heap, index, &DirtySnapshot, NULL, indnkeyatts, 0);
819 index_rescan(index_scan, scankeys, indnkeyatts, NULL, 0);
820
821 while (index_getnext_slot(index_scan, ForwardScanDirection, existing_slot))
822 {
823 TransactionId xwait;
824 XLTW_Oper reason_wait;
825 Datum existing_values[INDEX_MAX_KEYS];
826 bool existing_isnull[INDEX_MAX_KEYS];
827 char *error_new;
828 char *error_existing;
829
830 /*
831 * Ignore the entry for the tuple we're trying to check.
832 */
833 if (ItemPointerIsValid(tupleid) &&
834 ItemPointerEquals(tupleid, &existing_slot->tts_tid))
835 {
836 if (found_self) /* should not happen */
837 elog(ERROR, "found self tuple multiple times in index \"%s\"",
839 found_self = true;
840 continue;
841 }
842
843 /*
844 * Extract the index column values and isnull flags from the existing
845 * tuple.
846 */
847 FormIndexDatum(indexInfo, existing_slot, estate,
848 existing_values, existing_isnull);
849
850 /* If lossy indexscan, must recheck the condition */
851 if (index_scan->xs_recheck)
852 {
854 constr_procs,
855 existing_values,
856 existing_isnull,
857 values))
858 continue; /* tuple doesn't actually match, so no
859 * conflict */
860 }
861
862 /*
863 * At this point we have either a conflict or a potential conflict.
864 *
865 * If an in-progress transaction is affecting the visibility of this
866 * tuple, we need to wait for it to complete and then recheck (unless
867 * the caller requested not to). For simplicity we do rechecking by
868 * just restarting the whole scan --- this case probably doesn't
869 * happen often enough to be worth trying harder, and anyway we don't
870 * want to hold any index internal locks while waiting.
871 */
872 xwait = TransactionIdIsValid(DirtySnapshot.xmin) ?
873 DirtySnapshot.xmin : DirtySnapshot.xmax;
874
875 if (TransactionIdIsValid(xwait) &&
876 (waitMode == CEOUC_WAIT ||
877 (waitMode == CEOUC_LIVELOCK_PREVENTING_WAIT &&
878 DirtySnapshot.speculativeToken &&
880 {
881 reason_wait = indexInfo->ii_ExclusionOps ?
883 index_endscan(index_scan);
884 if (DirtySnapshot.speculativeToken)
885 SpeculativeInsertionWait(DirtySnapshot.xmin,
886 DirtySnapshot.speculativeToken);
887 else
888 XactLockTableWait(xwait, heap,
889 &existing_slot->tts_tid, reason_wait);
890 goto retry;
891 }
892
893 /*
894 * We have a definite conflict (or a potential one, but the caller
895 * didn't want to wait). Return it to caller, or report it.
896 */
897 if (violationOK)
898 {
899 conflict = true;
900 if (conflictTid)
901 *conflictTid = existing_slot->tts_tid;
902 break;
903 }
904
905 error_new = BuildIndexValueDescription(index, values, isnull);
906 error_existing = BuildIndexValueDescription(index, existing_values,
907 existing_isnull);
908 if (newIndex)
910 (errcode(ERRCODE_EXCLUSION_VIOLATION),
911 errmsg("could not create exclusion constraint \"%s\"",
913 error_new && error_existing ?
914 errdetail("Key %s conflicts with key %s.",
915 error_new, error_existing) :
916 errdetail("Key conflicts exist."),
919 else
921 (errcode(ERRCODE_EXCLUSION_VIOLATION),
922 errmsg("conflicting key value violates exclusion constraint \"%s\"",
924 error_new && error_existing ?
925 errdetail("Key %s conflicts with existing key %s.",
926 error_new, error_existing) :
927 errdetail("Key conflicts with existing key."),
930 }
931
932 index_endscan(index_scan);
933
934 /*
935 * Ordinarily, at this point the search should have found the originally
936 * inserted tuple (if any), unless we exited the loop early because of
937 * conflict. However, it is possible to define exclusion constraints for
938 * which that wouldn't be true --- for instance, if the operator is <>. So
939 * we no longer complain if found_self is still false.
940 */
941
942 econtext->ecxt_scantuple = save_scantuple;
943
944 ExecDropSingleTupleTableSlot(existing_slot);
945
946 return !conflict;
947}
int16 AttrNumber
Definition: attnum.h:21
uint16_t uint16
Definition: c.h:501
uint32 TransactionId
Definition: c.h:623
int errdetail(const char *fmt,...)
Definition: elog.c:1204
int errcode(int sqlerrcode)
Definition: elog.c:854
int errmsg(const char *fmt,...)
Definition: elog.c:1071
#define ERROR
Definition: elog.h:39
#define elog(elevel,...)
Definition: elog.h:225
#define ereport(elevel,...)
Definition: elog.h:149
static bool index_recheck_constraint(Relation index, const Oid *constr_procs, const Datum *existing_values, const bool *existing_isnull, const Datum *new_values)
Definition: execIndexing.c:973
static void ExecWithoutOverlapsNotEmpty(Relation rel, NameData attname, Datum attval, char typtype, Oid atttypid)
void ExecDropSingleTupleTableSlot(TupleTableSlot *slot)
Definition: execTuples.c:1443
#define GetPerTupleExprContext(estate)
Definition: executor.h:678
char * BuildIndexValueDescription(Relation indexRelation, const Datum *values, const bool *isnull)
Definition: genam.c:178
void FormIndexDatum(IndexInfo *indexInfo, TupleTableSlot *slot, EState *estate, Datum *values, bool *isnull)
Definition: index.c:2730
bool index_getnext_slot(IndexScanDesc scan, ScanDirection direction, TupleTableSlot *slot)
Definition: indexam.c:720
IndexScanDesc index_beginscan(Relation heapRelation, Relation indexRelation, Snapshot snapshot, IndexScanInstrumentation *instrument, int nkeys, int norderbys)
Definition: indexam.c:256
void index_endscan(IndexScanDesc scan)
Definition: indexam.c:382
void index_rescan(IndexScanDesc scan, ScanKey keys, int nkeys, ScanKey orderbys, int norderbys)
Definition: indexam.c:356
int i
Definition: isn.c:77
bool ItemPointerEquals(ItemPointer pointer1, ItemPointer pointer2)
Definition: itemptr.c:35
static bool ItemPointerIsValid(const ItemPointerData *pointer)
Definition: itemptr.h:83
void XactLockTableWait(TransactionId xid, Relation rel, ItemPointer ctid, XLTW_Oper oper)
Definition: lmgr.c:663
void SpeculativeInsertionWait(TransactionId xid, uint32 token)
Definition: lmgr.c:822
XLTW_Oper
Definition: lmgr.h:25
@ XLTW_InsertIndex
Definition: lmgr.h:31
@ XLTW_RecheckExclusionConstr
Definition: lmgr.h:34
FormData_pg_attribute * Form_pg_attribute
Definition: pg_attribute.h:202
#define INDEX_MAX_KEYS
uintptr_t Datum
Definition: postgres.h:69
#define InvalidOid
Definition: postgres_ext.h:35
unsigned int Oid
Definition: postgres_ext.h:30
#define RelationGetDescr(relation)
Definition: rel.h:542
#define RelationGetRelationName(relation)
Definition: rel.h:550
#define IndexRelationGetNumberOfKeyAttributes(relation)
Definition: rel.h:535
int errtableconstraint(Relation rel, const char *conname)
Definition: relcache.c:6100
void ScanKeyEntryInitialize(ScanKey entry, int flags, AttrNumber attributeNumber, StrategyNumber strategy, Oid subtype, Oid collation, RegProcedure procedure, Datum argument)
Definition: scankey.c:32
@ ForwardScanDirection
Definition: sdir.h:28
#define SK_SEARCHNULL
Definition: skey.h:121
#define SK_ISNULL
Definition: skey.h:115
#define InitDirtySnapshot(snapshotdata)
Definition: snapmgr.h:42
TupleTableSlot * ecxt_scantuple
Definition: execnodes.h:268
uint16 * ii_ExclusionStrats
Definition: execnodes.h:205
Oid * ii_ExclusionOps
Definition: execnodes.h:203
bool ii_NullsNotDistinct
Definition: execnodes.h:210
uint16 * ii_UniqueStrats
Definition: execnodes.h:208
bool ii_WithoutOverlaps
Definition: execnodes.h:217
Oid * ii_ExclusionProcs
Definition: execnodes.h:204
AttrNumber ii_IndexAttrNumbers[INDEX_MAX_KEYS]
Definition: execnodes.h:198
Oid * ii_UniqueProcs
Definition: execnodes.h:207
TransactionId xmin
Definition: snapshot.h:153
TransactionId xmax
Definition: snapshot.h:154
uint32 speculativeToken
Definition: snapshot.h:189
ItemPointerData tts_tid
Definition: tuptable.h:129
char typtype
Definition: typcache.h:43
TupleTableSlot * table_slot_create(Relation relation, List **reglist)
Definition: tableam.c:92
bool TransactionIdPrecedes(TransactionId id1, TransactionId id2)
Definition: transam.c:280
#define TransactionIdIsValid(xid)
Definition: transam.h:41
static FormData_pg_attribute * TupleDescAttr(TupleDesc tupdesc, int i)
Definition: tupdesc.h:160
TypeCacheEntry * lookup_type_cache(Oid type_id, int flags)
Definition: typcache.c:386
TransactionId GetCurrentTransactionId(void)
Definition: xact.c:454

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

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

◆ ExecCheckIndexConstraints()

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

Definition at line 542 of file execIndexing.c.

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

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

Referenced by ExecInsert(), and FindConflictTuple().

◆ ExecCloseIndices()

void ExecCloseIndices ( ResultRelInfo resultRelInfo)

Definition at line 238 of file execIndexing.c.

239{
240 int i;
241 int numIndices;
242 RelationPtr indexDescs;
243 IndexInfo **indexInfos;
244
245 numIndices = resultRelInfo->ri_NumIndices;
246 indexDescs = resultRelInfo->ri_IndexRelationDescs;
247 indexInfos = resultRelInfo->ri_IndexRelationInfo;
248
249 for (i = 0; i < numIndices; i++)
250 {
251 /* This Assert will fail if ExecCloseIndices is called twice */
252 Assert(indexDescs[i] != NULL);
253
254 /* Give the index a chance to do some post-insert cleanup */
255 index_insert_cleanup(indexDescs[i], indexInfos[i]);
256
257 /* Drop lock acquired by ExecOpenIndices */
258 index_close(indexDescs[i], RowExclusiveLock);
259
260 /* Mark the index as closed */
261 indexDescs[i] = NULL;
262 }
263
264 /*
265 * We don't attempt to free the IndexInfo data structures or the arrays,
266 * instead assuming that such stuff will be cleaned up automatically in
267 * FreeExecutorState.
268 */
269}
Assert(PointerIsAligned(start, uint64))
void index_insert_cleanup(Relation indexRelation, IndexInfo *indexInfo)
Definition: indexam.c:241
void index_close(Relation relation, LOCKMODE lockmode)
Definition: indexam.c:177
#define RowExclusiveLock
Definition: lockdefs.h:38

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

Referenced by apply_handle_delete(), apply_handle_insert(), apply_handle_update_internal(), CatalogCloseIndexes(), ExecCleanupTupleRouting(), and ExecCloseResultRelations().

◆ ExecInsertIndexTuples()

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

Definition at line 309 of file execIndexing.c.

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

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

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

◆ ExecOpenIndices()

void ExecOpenIndices ( ResultRelInfo resultRelInfo,
bool  speculative 
)

Definition at line 160 of file execIndexing.c.

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

References Assert(), BuildIndexInfo(), BuildSpeculativeIndexInfo(), i, IndexInfo::ii_Unique, index_open(), len, lfirst_oid, list_free(), list_length(), palloc(), RelationData::rd_index, 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_internal(), CatalogOpenIndexes(), CopyFrom(), ExecInitPartitionInfo(), ExecInsert(), and ExecUpdatePrologue().

◆ ExecWithoutOverlapsNotEmpty()

static void ExecWithoutOverlapsNotEmpty ( Relation  rel,
NameData  attname,
Datum  attval,
char  typtype,
Oid  atttypid 
)
static

Definition at line 1147 of file execIndexing.c.

1148{
1149 bool isempty;
1150 RangeType *r;
1151 MultirangeType *mr;
1152
1153 switch (typtype)
1154 {
1155 case TYPTYPE_RANGE:
1156 r = DatumGetRangeTypeP(attval);
1157 isempty = RangeIsEmpty(r);
1158 break;
1159 case TYPTYPE_MULTIRANGE:
1160 mr = DatumGetMultirangeTypeP(attval);
1161 isempty = MultirangeIsEmpty(mr);
1162 break;
1163 default:
1164 elog(ERROR, "WITHOUT OVERLAPS column \"%s\" is not a range or multirange",
1165 NameStr(attname));
1166 }
1167
1168 /* Report a CHECK_VIOLATION */
1169 if (isempty)
1170 ereport(ERROR,
1171 (errcode(ERRCODE_CHECK_VIOLATION),
1172 errmsg("empty WITHOUT OVERLAPS value found in column \"%s\" in relation \"%s\"",
1174}
#define NameStr(name)
Definition: c.h:717
#define MultirangeIsEmpty(mr)
static MultirangeType * DatumGetMultirangeTypeP(Datum X)
NameData attname
Definition: pg_attribute.h:41
static RangeType * DatumGetRangeTypeP(Datum X)
Definition: rangetypes.h:73
#define RangeIsEmpty(r)
Definition: rangetypes.h:55

References attname, DatumGetMultirangeTypeP(), DatumGetRangeTypeP(), elog, ereport, errcode(), errmsg(), ERROR, MultirangeIsEmpty, NameStr, RangeIsEmpty, and RelationGetRelationName.

Referenced by check_exclusion_or_unique_constraint().

◆ index_expression_changed_walker()

static bool index_expression_changed_walker ( Node node,
Bitmapset allUpdatedCols 
)
static

Definition at line 1118 of file execIndexing.c.

1119{
1120 if (node == NULL)
1121 return false;
1122
1123 if (IsA(node, Var))
1124 {
1125 Var *var = (Var *) node;
1126
1128 allUpdatedCols))
1129 {
1130 /* Var was updated -- indicates that we should not hint */
1131 return true;
1132 }
1133
1134 /* Still haven't found a reason to not pass the hint */
1135 return false;
1136 }
1137
1139 allUpdatedCols);
1140}
bool bms_is_member(int x, const Bitmapset *a)
Definition: bitmapset.c:510
static bool index_expression_changed_walker(Node *node, Bitmapset *allUpdatedCols)
#define expression_tree_walker(n, w, c)
Definition: nodeFuncs.h:153
#define IsA(nodeptr, _type_)
Definition: nodes.h:164
Definition: primnodes.h:262
AttrNumber varattno
Definition: primnodes.h:274
#define FirstLowInvalidHeapAttributeNumber
Definition: sysattr.h:27

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

Referenced by index_expression_changed_walker(), and index_unchanged_by_update().

◆ index_recheck_constraint()

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

Definition at line 973 of file execIndexing.c.

976{
978 int i;
979
980 for (i = 0; i < indnkeyatts; i++)
981 {
982 /* Assume the exclusion operators are strict */
983 if (existing_isnull[i])
984 return false;
985
986 if (!DatumGetBool(OidFunctionCall2Coll(constr_procs[i],
987 index->rd_indcollation[i],
988 existing_values[i],
989 new_values[i])))
990 return false;
991 }
992
993 return true;
994}
Datum OidFunctionCall2Coll(Oid functionId, Oid collation, Datum arg1, Datum arg2)
Definition: fmgr.c:1421
static bool DatumGetBool(Datum X)
Definition: postgres.h:95

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

Referenced by check_exclusion_or_unique_constraint().

◆ index_unchanged_by_update()

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

Definition at line 1004 of file execIndexing.c.

1006{
1007 Bitmapset *updatedCols;
1008 Bitmapset *extraUpdatedCols;
1009 Bitmapset *allUpdatedCols;
1010 bool hasexpression = false;
1011 List *idxExprs;
1012
1013 /*
1014 * Check cache first
1015 */
1016 if (indexInfo->ii_CheckedUnchanged)
1017 return indexInfo->ii_IndexUnchanged;
1018 indexInfo->ii_CheckedUnchanged = true;
1019
1020 /*
1021 * Check for indexed attribute overlap with updated columns.
1022 *
1023 * Only do this for key columns. A change to a non-key column within an
1024 * INCLUDE index should not be counted here. Non-key column values are
1025 * opaque payload state to the index AM, a little like an extra table TID.
1026 *
1027 * Note that row-level BEFORE triggers won't affect our behavior, since
1028 * they don't affect the updatedCols bitmaps generally. It doesn't seem
1029 * worth the trouble of checking which attributes were changed directly.
1030 */
1031 updatedCols = ExecGetUpdatedCols(resultRelInfo, estate);
1032 extraUpdatedCols = ExecGetExtraUpdatedCols(resultRelInfo, estate);
1033 for (int attr = 0; attr < indexInfo->ii_NumIndexKeyAttrs; attr++)
1034 {
1035 int keycol = indexInfo->ii_IndexAttrNumbers[attr];
1036
1037 if (keycol <= 0)
1038 {
1039 /*
1040 * Skip expressions for now, but remember to deal with them later
1041 * on
1042 */
1043 hasexpression = true;
1044 continue;
1045 }
1046
1048 updatedCols) ||
1050 extraUpdatedCols))
1051 {
1052 /* Changed key column -- don't hint for this index */
1053 indexInfo->ii_IndexUnchanged = false;
1054 return false;
1055 }
1056 }
1057
1058 /*
1059 * When we get this far and index has no expressions, return true so that
1060 * index_insert() call will go on to pass 'indexUnchanged' = true hint.
1061 *
1062 * The _absence_ of an indexed key attribute that overlaps with updated
1063 * attributes (in addition to the total absence of indexed expressions)
1064 * shows that the index as a whole is logically unchanged by UPDATE.
1065 */
1066 if (!hasexpression)
1067 {
1068 indexInfo->ii_IndexUnchanged = true;
1069 return true;
1070 }
1071
1072 /*
1073 * Need to pass only one bms to expression_tree_walker helper function.
1074 * Avoid allocating memory in common case where there are no extra cols.
1075 */
1076 if (!extraUpdatedCols)
1077 allUpdatedCols = updatedCols;
1078 else
1079 allUpdatedCols = bms_union(updatedCols, extraUpdatedCols);
1080
1081 /*
1082 * We have to work slightly harder in the event of indexed expressions,
1083 * but the principle is the same as before: try to find columns (Vars,
1084 * actually) that overlap with known-updated columns.
1085 *
1086 * If we find any matching Vars, don't pass hint for index. Otherwise
1087 * pass hint.
1088 */
1089 idxExprs = RelationGetIndexExpressions(indexRelation);
1090 hasexpression = index_expression_changed_walker((Node *) idxExprs,
1091 allUpdatedCols);
1092 list_free(idxExprs);
1093 if (extraUpdatedCols)
1094 bms_free(allUpdatedCols);
1095
1096 if (hasexpression)
1097 {
1098 indexInfo->ii_IndexUnchanged = false;
1099 return false;
1100 }
1101
1102 /*
1103 * Deliberately don't consider index predicates. We should even give the
1104 * hint when result rel's "updated tuple" has no corresponding index
1105 * tuple, which is possible with a partial index (provided the usual
1106 * conditions are met).
1107 */
1108 indexInfo->ii_IndexUnchanged = true;
1109 return true;
1110}
void bms_free(Bitmapset *a)
Definition: bitmapset.c:239
Bitmapset * bms_union(const Bitmapset *a, const Bitmapset *b)
Definition: bitmapset.c:251
Bitmapset * ExecGetExtraUpdatedCols(ResultRelInfo *relinfo, EState *estate)
Definition: execUtils.c:1404
Bitmapset * ExecGetUpdatedCols(ResultRelInfo *relinfo, EState *estate)
Definition: execUtils.c:1383
List * RelationGetIndexExpressions(Relation relation)
Definition: relcache.c:5094
bool ii_CheckedUnchanged
Definition: execnodes.h:212
int ii_NumIndexKeyAttrs
Definition: execnodes.h:197
bool ii_IndexUnchanged
Definition: execnodes.h:213
Definition: nodes.h:135

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

Referenced by ExecInsertIndexTuples().