PostgreSQL Source Code git master
All Data Structures Namespaces Files Functions Variables Typedefs Enumerations Enumerator Macros Pages
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 950 of file execIndexing.c.

955{
956 (void) check_exclusion_or_unique_constraint(heap, index, indexInfo, tupleid,
957 values, isnull,
958 estate, newIndex,
959 CEOUC_WAIT, false, NULL);
960}
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:698
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 698 of file execIndexing.c.

706{
707 Oid *constr_procs;
708 uint16 *constr_strats;
709 Oid *index_collations = index->rd_indcollation;
711 IndexScanDesc index_scan;
712 ScanKeyData scankeys[INDEX_MAX_KEYS];
713 SnapshotData DirtySnapshot;
714 int i;
715 bool conflict;
716 bool found_self;
717 ExprContext *econtext;
718 TupleTableSlot *existing_slot;
719 TupleTableSlot *save_scantuple;
720
721 if (indexInfo->ii_ExclusionOps)
722 {
723 constr_procs = indexInfo->ii_ExclusionProcs;
724 constr_strats = indexInfo->ii_ExclusionStrats;
725 }
726 else
727 {
728 constr_procs = indexInfo->ii_UniqueProcs;
729 constr_strats = indexInfo->ii_UniqueStrats;
730 }
731
732 /*
733 * If this is a WITHOUT OVERLAPS constraint, we must also forbid empty
734 * ranges/multiranges. This must happen before we look for NULLs below, or
735 * a UNIQUE constraint could insert an empty range along with a NULL
736 * scalar part.
737 */
738 if (indexInfo->ii_WithoutOverlaps)
739 {
740 /*
741 * Look up the type from the heap tuple, but check the Datum from the
742 * index tuple.
743 */
744 AttrNumber attno = indexInfo->ii_IndexAttrNumbers[indnkeyatts - 1];
745
746 if (!isnull[indnkeyatts - 1])
747 {
748 TupleDesc tupdesc = RelationGetDescr(heap);
749 Form_pg_attribute att = TupleDescAttr(tupdesc, attno - 1);
750 TypeCacheEntry *typcache = lookup_type_cache(att->atttypid, 0);
751
752 ExecWithoutOverlapsNotEmpty(heap, att->attname,
753 values[indnkeyatts - 1],
754 typcache->typtype, att->atttypid);
755 }
756 }
757
758 /*
759 * If any of the input values are NULL, and the index uses the default
760 * nulls-are-distinct mode, the constraint check is assumed to pass (i.e.,
761 * we assume the operators are strict). Otherwise, we interpret the
762 * constraint as specifying IS NULL for each column whose input value is
763 * NULL.
764 */
765 if (!indexInfo->ii_NullsNotDistinct)
766 {
767 for (i = 0; i < indnkeyatts; i++)
768 {
769 if (isnull[i])
770 return true;
771 }
772 }
773
774 /*
775 * Search the tuples that are in the index for any violations, including
776 * tuples that aren't visible yet.
777 */
778 InitDirtySnapshot(DirtySnapshot);
779
780 for (i = 0; i < indnkeyatts; i++)
781 {
782 ScanKeyEntryInitialize(&scankeys[i],
783 isnull[i] ? SK_ISNULL | SK_SEARCHNULL : 0,
784 i + 1,
785 constr_strats[i],
787 index_collations[i],
788 constr_procs[i],
789 values[i]);
790 }
791
792 /*
793 * Need a TupleTableSlot to put existing tuples in.
794 *
795 * To use FormIndexDatum, we have to make the econtext's scantuple point
796 * to this slot. Be sure to save and restore caller's value for
797 * scantuple.
798 */
799 existing_slot = table_slot_create(heap, NULL);
800
801 econtext = GetPerTupleExprContext(estate);
802 save_scantuple = econtext->ecxt_scantuple;
803 econtext->ecxt_scantuple = existing_slot;
804
805 /*
806 * May have to restart scan from this point if a potential conflict is
807 * found.
808 */
809retry:
810 conflict = false;
811 found_self = false;
812 index_scan = index_beginscan(heap, index, &DirtySnapshot, indnkeyatts, 0);
813 index_rescan(index_scan, scankeys, indnkeyatts, NULL, 0);
814
815 while (index_getnext_slot(index_scan, ForwardScanDirection, existing_slot))
816 {
817 TransactionId xwait;
818 XLTW_Oper reason_wait;
819 Datum existing_values[INDEX_MAX_KEYS];
820 bool existing_isnull[INDEX_MAX_KEYS];
821 char *error_new;
822 char *error_existing;
823
824 /*
825 * Ignore the entry for the tuple we're trying to check.
826 */
827 if (ItemPointerIsValid(tupleid) &&
828 ItemPointerEquals(tupleid, &existing_slot->tts_tid))
829 {
830 if (found_self) /* should not happen */
831 elog(ERROR, "found self tuple multiple times in index \"%s\"",
833 found_self = true;
834 continue;
835 }
836
837 /*
838 * Extract the index column values and isnull flags from the existing
839 * tuple.
840 */
841 FormIndexDatum(indexInfo, existing_slot, estate,
842 existing_values, existing_isnull);
843
844 /* If lossy indexscan, must recheck the condition */
845 if (index_scan->xs_recheck)
846 {
848 constr_procs,
849 existing_values,
850 existing_isnull,
851 values))
852 continue; /* tuple doesn't actually match, so no
853 * conflict */
854 }
855
856 /*
857 * At this point we have either a conflict or a potential conflict.
858 *
859 * If an in-progress transaction is affecting the visibility of this
860 * tuple, we need to wait for it to complete and then recheck (unless
861 * the caller requested not to). For simplicity we do rechecking by
862 * just restarting the whole scan --- this case probably doesn't
863 * happen often enough to be worth trying harder, and anyway we don't
864 * want to hold any index internal locks while waiting.
865 */
866 xwait = TransactionIdIsValid(DirtySnapshot.xmin) ?
867 DirtySnapshot.xmin : DirtySnapshot.xmax;
868
869 if (TransactionIdIsValid(xwait) &&
870 (waitMode == CEOUC_WAIT ||
871 (waitMode == CEOUC_LIVELOCK_PREVENTING_WAIT &&
872 DirtySnapshot.speculativeToken &&
874 {
875 reason_wait = indexInfo->ii_ExclusionOps ?
877 index_endscan(index_scan);
878 if (DirtySnapshot.speculativeToken)
879 SpeculativeInsertionWait(DirtySnapshot.xmin,
880 DirtySnapshot.speculativeToken);
881 else
882 XactLockTableWait(xwait, heap,
883 &existing_slot->tts_tid, reason_wait);
884 goto retry;
885 }
886
887 /*
888 * We have a definite conflict (or a potential one, but the caller
889 * didn't want to wait). Return it to caller, or report it.
890 */
891 if (violationOK)
892 {
893 conflict = true;
894 if (conflictTid)
895 *conflictTid = existing_slot->tts_tid;
896 break;
897 }
898
899 error_new = BuildIndexValueDescription(index, values, isnull);
900 error_existing = BuildIndexValueDescription(index, existing_values,
901 existing_isnull);
902 if (newIndex)
904 (errcode(ERRCODE_EXCLUSION_VIOLATION),
905 errmsg("could not create exclusion constraint \"%s\"",
907 error_new && error_existing ?
908 errdetail("Key %s conflicts with key %s.",
909 error_new, error_existing) :
910 errdetail("Key conflicts exist."),
913 else
915 (errcode(ERRCODE_EXCLUSION_VIOLATION),
916 errmsg("conflicting key value violates exclusion constraint \"%s\"",
918 error_new && error_existing ?
919 errdetail("Key %s conflicts with existing key %s.",
920 error_new, error_existing) :
921 errdetail("Key conflicts with existing key."),
924 }
925
926 index_endscan(index_scan);
927
928 /*
929 * Ordinarily, at this point the search should have found the originally
930 * inserted tuple (if any), unless we exited the loop early because of
931 * conflict. However, it is possible to define exclusion constraints for
932 * which that wouldn't be true --- for instance, if the operator is <>. So
933 * we no longer complain if found_self is still false.
934 */
935
936 econtext->ecxt_scantuple = save_scantuple;
937
938 ExecDropSingleTupleTableSlot(existing_slot);
939
940 return !conflict;
941}
int16 AttrNumber
Definition: attnum.h:21
uint16_t uint16
Definition: c.h:484
uint32 TransactionId
Definition: c.h:606
int errdetail(const char *fmt,...)
Definition: elog.c:1203
int errcode(int sqlerrcode)
Definition: elog.c:853
int errmsg(const char *fmt,...)
Definition: elog.c:1070
#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:967
static void ExecWithoutOverlapsNotEmpty(Relation rel, NameData attname, Datum attval, char typtype, Oid atttypid)
void ExecDropSingleTupleTableSlot(TupleTableSlot *slot)
Definition: execTuples.c:1441
#define GetPerTupleExprContext(estate)
Definition: executor.h:563
char * BuildIndexValueDescription(Relation indexRelation, const Datum *values, const bool *isnull)
Definition: genam.c:177
void FormIndexDatum(IndexInfo *indexInfo, TupleTableSlot *slot, EState *estate, Datum *values, bool *isnull)
Definition: index.c:2727
bool index_getnext_slot(IndexScanDesc scan, ScanDirection direction, TupleTableSlot *slot)
Definition: indexam.c:675
IndexScanDesc index_beginscan(Relation heapRelation, Relation indexRelation, Snapshot snapshot, int nkeys, int norderbys)
Definition: indexam.c:256
void index_endscan(IndexScanDesc scan)
Definition: indexam.c:378
void index_rescan(IndexScanDesc scan, ScanKey keys, int nkeys, ScanKey orderbys, int norderbys)
Definition: indexam.c:352
int i
Definition: isn.c:72
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:656
void SpeculativeInsertionWait(TransactionId xid, uint32 token)
Definition: lmgr.c:813
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:200
#define INDEX_MAX_KEYS
uintptr_t Datum
Definition: postgres.h:64
#define InvalidOid
Definition: postgres_ext.h:36
unsigned int Oid
Definition: postgres_ext.h:31
#define RelationGetDescr(relation)
Definition: rel.h:531
#define RelationGetRelationName(relation)
Definition: rel.h:539
#define IndexRelationGetNumberOfKeyAttributes(relation)
Definition: rel.h:524
int errtableconstraint(Relation rel, const char *conname)
Definition: relcache.c:6022
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:258
uint16 * ii_ExclusionStrats
Definition: execnodes.h:195
Oid * ii_ExclusionOps
Definition: execnodes.h:193
bool ii_NullsNotDistinct
Definition: execnodes.h:200
uint16 * ii_UniqueStrats
Definition: execnodes.h:198
bool ii_WithoutOverlaps
Definition: execnodes.h:207
Oid * ii_ExclusionProcs
Definition: execnodes.h:194
AttrNumber ii_IndexAttrNumbers[INDEX_MAX_KEYS]
Definition: execnodes.h:188
Oid * ii_UniqueProcs
Definition: execnodes.h:197
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:91
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:152
TypeCacheEntry * lookup_type_cache(Oid type_id, int flags)
Definition: typcache.c:386
TransactionId GetCurrentTransactionId(void)
Definition: xact.c:453

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

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

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

237{
238 int i;
239 int numIndices;
240 RelationPtr indexDescs;
241 IndexInfo **indexInfos;
242
243 numIndices = resultRelInfo->ri_NumIndices;
244 indexDescs = resultRelInfo->ri_IndexRelationDescs;
245 indexInfos = resultRelInfo->ri_IndexRelationInfo;
246
247 for (i = 0; i < numIndices; i++)
248 {
249 if (indexDescs[i] == NULL)
250 continue; /* shouldn't happen? */
251
252 /* Give the index a chance to do some post-insert cleanup */
253 index_insert_cleanup(indexDescs[i], indexInfos[i]);
254
255 /* Drop lock acquired by ExecOpenIndices */
256 index_close(indexDescs[i], RowExclusiveLock);
257 }
258
259 /*
260 * XXX should free indexInfo array here too? Currently we assume that
261 * such stuff will be cleaned up automatically in FreeExecutorState.
262 */
263}
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 i, index_close(), index_insert_cleanup(), ResultRelInfo::ri_IndexRelationDescs, ResultRelInfo::ri_IndexRelationInfo, ResultRelInfo::ri_NumIndices, and RowExclusiveLock.

Referenced by apply_handle_delete_internal(), apply_handle_insert_internal(), apply_handle_tuple_routing(), apply_handle_update_internal(), CatalogCloseIndexes(), ExecCleanupTupleRouting(), and ExecCloseResultRelations().

◆ ExecInsertIndexTuples()

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

Definition at line 303 of file execIndexing.c.

311{
312 ItemPointer tupleid = &slot->tts_tid;
313 List *result = NIL;
314 int i;
315 int numIndices;
316 RelationPtr relationDescs;
317 Relation heapRelation;
318 IndexInfo **indexInfoArray;
319 ExprContext *econtext;
321 bool isnull[INDEX_MAX_KEYS];
322
323 Assert(ItemPointerIsValid(tupleid));
324
325 /*
326 * Get information from the result relation info structure.
327 */
328 numIndices = resultRelInfo->ri_NumIndices;
329 relationDescs = resultRelInfo->ri_IndexRelationDescs;
330 indexInfoArray = resultRelInfo->ri_IndexRelationInfo;
331 heapRelation = resultRelInfo->ri_RelationDesc;
332
333 /* Sanity check: slot must belong to the same rel as the resultRelInfo. */
334 Assert(slot->tts_tableOid == RelationGetRelid(heapRelation));
335
336 /*
337 * We will use the EState's per-tuple context for evaluating predicates
338 * and index expressions (creating it if it's not already there).
339 */
340 econtext = GetPerTupleExprContext(estate);
341
342 /* Arrange for econtext's scan tuple to be the tuple under test */
343 econtext->ecxt_scantuple = slot;
344
345 /*
346 * for each index, form and insert the index tuple
347 */
348 for (i = 0; i < numIndices; i++)
349 {
350 Relation indexRelation = relationDescs[i];
351 IndexInfo *indexInfo;
352 bool applyNoDupErr;
353 IndexUniqueCheck checkUnique;
354 bool indexUnchanged;
355 bool satisfiesConstraint;
356
357 if (indexRelation == NULL)
358 continue;
359
360 indexInfo = indexInfoArray[i];
361
362 /* If the index is marked as read-only, ignore it */
363 if (!indexInfo->ii_ReadyForInserts)
364 continue;
365
366 /*
367 * Skip processing of non-summarizing indexes if we only update
368 * summarizing indexes
369 */
370 if (onlySummarizing && !indexInfo->ii_Summarizing)
371 continue;
372
373 /* Check for partial index */
374 if (indexInfo->ii_Predicate != NIL)
375 {
376 ExprState *predicate;
377
378 /*
379 * If predicate state not set up yet, create it (in the estate's
380 * per-query context)
381 */
382 predicate = indexInfo->ii_PredicateState;
383 if (predicate == NULL)
384 {
385 predicate = ExecPrepareQual(indexInfo->ii_Predicate, estate);
386 indexInfo->ii_PredicateState = predicate;
387 }
388
389 /* Skip this index-update if the predicate isn't satisfied */
390 if (!ExecQual(predicate, econtext))
391 continue;
392 }
393
394 /*
395 * FormIndexDatum fills in its values and isnull parameters with the
396 * appropriate values for the column(s) of the index.
397 */
398 FormIndexDatum(indexInfo,
399 slot,
400 estate,
401 values,
402 isnull);
403
404 /* Check whether to apply noDupErr to this index */
405 applyNoDupErr = noDupErr &&
406 (arbiterIndexes == NIL ||
407 list_member_oid(arbiterIndexes,
408 indexRelation->rd_index->indexrelid));
409
410 /*
411 * The index AM does the actual insertion, plus uniqueness checking.
412 *
413 * For an immediate-mode unique index, we just tell the index AM to
414 * throw error if not unique.
415 *
416 * For a deferrable unique index, we tell the index AM to just detect
417 * possible non-uniqueness, and we add the index OID to the result
418 * list if further checking is needed.
419 *
420 * For a speculative insertion (used by INSERT ... ON CONFLICT), do
421 * the same as for a deferrable unique index.
422 */
423 if (!indexRelation->rd_index->indisunique)
424 checkUnique = UNIQUE_CHECK_NO;
425 else if (applyNoDupErr)
426 checkUnique = UNIQUE_CHECK_PARTIAL;
427 else if (indexRelation->rd_index->indimmediate)
428 checkUnique = UNIQUE_CHECK_YES;
429 else
430 checkUnique = UNIQUE_CHECK_PARTIAL;
431
432 /*
433 * There's definitely going to be an index_insert() call for this
434 * index. If we're being called as part of an UPDATE statement,
435 * consider if the 'indexUnchanged' = true hint should be passed.
436 */
437 indexUnchanged = update && index_unchanged_by_update(resultRelInfo,
438 estate,
439 indexInfo,
440 indexRelation);
441
442 satisfiesConstraint =
443 index_insert(indexRelation, /* index relation */
444 values, /* array of index Datums */
445 isnull, /* null flags */
446 tupleid, /* tid of heap tuple */
447 heapRelation, /* heap relation */
448 checkUnique, /* type of uniqueness check to do */
449 indexUnchanged, /* UPDATE without logical change? */
450 indexInfo); /* index AM may need this */
451
452 /*
453 * If the index has an associated exclusion constraint, check that.
454 * This is simpler than the process for uniqueness checks since we
455 * always insert first and then check. If the constraint is deferred,
456 * we check now anyway, but don't throw error on violation or wait for
457 * a conclusive outcome from a concurrent insertion; instead we'll
458 * queue a recheck event. Similarly, noDupErr callers (speculative
459 * inserters) will recheck later, and wait for a conclusive outcome
460 * then.
461 *
462 * An index for an exclusion constraint can't also be UNIQUE (not an
463 * essential property, we just don't allow it in the grammar), so no
464 * need to preserve the prior state of satisfiesConstraint.
465 */
466 if (indexInfo->ii_ExclusionOps != NULL)
467 {
468 bool violationOK;
469 CEOUC_WAIT_MODE waitMode;
470
471 if (applyNoDupErr)
472 {
473 violationOK = true;
475 }
476 else if (!indexRelation->rd_index->indimmediate)
477 {
478 violationOK = true;
479 waitMode = CEOUC_NOWAIT;
480 }
481 else
482 {
483 violationOK = false;
484 waitMode = CEOUC_WAIT;
485 }
486
487 satisfiesConstraint =
489 indexRelation, indexInfo,
490 tupleid, values, isnull,
491 estate, false,
492 waitMode, violationOK, NULL);
493 }
494
495 if ((checkUnique == UNIQUE_CHECK_PARTIAL ||
496 indexInfo->ii_ExclusionOps != NULL) &&
497 !satisfiesConstraint)
498 {
499 /*
500 * The tuple potentially violates the uniqueness or exclusion
501 * constraint, so make a note of the index so that we can re-check
502 * it later. Speculative inserters are told if there was a
503 * speculative conflict, since that always requires a restart.
504 */
505 result = lappend_oid(result, RelationGetRelid(indexRelation));
506 if (indexRelation->rd_index->indimmediate && specConflict)
507 *specConflict = true;
508 }
509 }
510
511 return result;
512}
#define Assert(condition)
Definition: c.h:812
static bool index_unchanged_by_update(ResultRelInfo *resultRelInfo, EState *estate, IndexInfo *indexInfo, Relation indexRelation)
Definition: execIndexing.c:998
IndexUniqueCheck
Definition: genam.h:118
@ UNIQUE_CHECK_NO
Definition: genam.h:119
@ UNIQUE_CHECK_PARTIAL
Definition: genam.h:121
@ UNIQUE_CHECK_YES
Definition: genam.h:120
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:505
bool ii_Summarizing
Definition: execnodes.h:206
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 /*
185 * allocate space for result arrays
186 */
187 relationDescs = (RelationPtr) palloc(len * sizeof(Relation));
188 indexInfoArray = (IndexInfo **) palloc(len * sizeof(IndexInfo *));
189
190 resultRelInfo->ri_NumIndices = len;
191 resultRelInfo->ri_IndexRelationDescs = relationDescs;
192 resultRelInfo->ri_IndexRelationInfo = indexInfoArray;
193
194 /*
195 * For each index, open the index relation and save pg_index info. We
196 * acquire RowExclusiveLock, signifying we will update the index.
197 *
198 * Note: we do this even if the index is not indisready; it's not worth
199 * the trouble to optimize for the case where it isn't.
200 */
201 i = 0;
202 foreach(l, indexoidlist)
203 {
204 Oid indexOid = lfirst_oid(l);
205 Relation indexDesc;
206 IndexInfo *ii;
207
208 indexDesc = index_open(indexOid, RowExclusiveLock);
209
210 /* extract index key information from the index's pg_index info */
211 ii = BuildIndexInfo(indexDesc);
212
213 /*
214 * If the indexes are to be used for speculative insertion or conflict
215 * detection in logical replication, add extra information required by
216 * unique index entries.
217 */
218 if (speculative && ii->ii_Unique && !indexDesc->rd_index->indisexclusion)
219 BuildSpeculativeIndexInfo(indexDesc, ii);
220
221 relationDescs[i] = indexDesc;
222 indexInfoArray[i] = ii;
223 i++;
224 }
225
226 list_free(indexoidlist);
227}
IndexInfo * BuildIndexInfo(Relation index)
Definition: index.c:2426
void BuildSpeculativeIndexInfo(Relation index, IndexInfo *ii)
Definition: index.c:2667
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:1317
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:499
List * RelationGetIndexList(Relation relation)
Definition: relcache.c:4755
Relation * RelationPtr
Definition: relcache.h:35

References 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_internal(), apply_handle_insert_internal(), apply_handle_tuple_routing(), 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 1141 of file execIndexing.c.

1142{
1143 bool isempty;
1144 RangeType *r;
1145 MultirangeType *mr;
1146
1147 switch (typtype)
1148 {
1149 case TYPTYPE_RANGE:
1150 r = DatumGetRangeTypeP(attval);
1151 isempty = RangeIsEmpty(r);
1152 break;
1153 case TYPTYPE_MULTIRANGE:
1154 mr = DatumGetMultirangeTypeP(attval);
1155 isempty = MultirangeIsEmpty(mr);
1156 break;
1157 default:
1158 elog(ERROR, "WITHOUT OVERLAPS column \"%s\" is not a range or multirange",
1159 NameStr(attname));
1160 }
1161
1162 /* Report a CHECK_VIOLATION */
1163 if (isempty)
1164 ereport(ERROR,
1165 (errcode(ERRCODE_CHECK_VIOLATION),
1166 errmsg("empty WITHOUT OVERLAPS value found in column \"%s\" in relation \"%s\"",
1168}
#define NameStr(name)
Definition: c.h:700
#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 1112 of file execIndexing.c.

1113{
1114 if (node == NULL)
1115 return false;
1116
1117 if (IsA(node, Var))
1118 {
1119 Var *var = (Var *) node;
1120
1122 allUpdatedCols))
1123 {
1124 /* Var was updated -- indicates that we should not hint */
1125 return true;
1126 }
1127
1128 /* Still haven't found a reason to not pass the hint */
1129 return false;
1130 }
1131
1133 allUpdatedCols);
1134}
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:158
Definition: primnodes.h:248
AttrNumber varattno
Definition: primnodes.h:260
#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 967 of file execIndexing.c.

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

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

Referenced by check_exclusion_or_unique_constraint().

◆ index_unchanged_by_update()

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

Definition at line 998 of file execIndexing.c.

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

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

Referenced by ExecInsertIndexTuples().