From cad236149af2d2a4f5762334d0d96ba13443b022 Mon Sep 17 00:00:00 2001 From: Greg Burd Date: Sun, 26 Oct 2025 10:49:25 -0400 Subject: [PATCH v23 4/4] Enable HOT updates for expression and partial indexes Currently, PostgreSQL conservatively prevents HOT (Heap-Only Tuple) updates whenever any indexed column changes, even if the indexed portion of that column remains identical. This is overly restrictive for expression indexes (where f(column) might not change even when column changes) and partial indexes (where both old and new tuples might fall outside the predicate). Finally, index AMs play no role in deciding when they need a new index entry on update, the rules regarding that are based on binary equality and the HEAP's model for MVCC and related HOT optimization. Here we open that door a bit so as to enable more nuanced control over the process. This enables index AMs that require binary equality (as is the case for nbtree) to do that without disallowing type-specific equality checking for other indexes. This patch introduces several improvements to enable HOT updates in these cases: Add amcomparedatums() callback to IndexAmRoutine. This allows index access methods like GIN to provide custom logic for comparing datums by extracting and comparing index keys rather than comparing the raw datums. GIN indexes now implement gincomparedatums() which extracts keys from both datums and compares the resulting key sets. Also, as mentioned earlier nbtree implements this API and uses datumIsEqual() for equality so that the manner in which it deduplicates TIDs on page split doesn't have to change. This is not a required API, when not implemented the executor will compare TupleTableSlot datum for equality using type-specific operators and take into account collation so that an update from "Apple" to "APPLE" on a case insensitive index can now be HOT. ExecWhichIndexesRequireUpdates() is re-written to find the set of modified indexed attributes that trigger new index tuples on updated. For partial indexes, this checks whether both old and new tuples satisfy or fail the predicate. For expression indexes, this uses type-specific equality operators to compare computed values. For extraction-based indexes (GIN/RUM) that implement amcomparedatums() it uses that. Importantly, table access methods can still signal using TU_Update if all, none, or only summarizing indexes should be updated. While the executor layer now owns determining what has changed due to an update and is interested in only updating the minimum number of indexes possible, the table AM can override that while performing table_tuple_update(), which is what heap does. While this signal is very specific to how the heap implements MVCC and its HOT optimization, we'll leave replacing that for another day. This optimization trades off some new overhead for the potential for more updates to use the HOT optimized path and avoid index and heap bloat. This should significantly improve update performance for tables with expression indexes, partial indexes, and GIN/GiST indexes on complex data types like JSONB and tsvector, while maintaining correct index semantics. Minimal additional overhead due to type-specific equality checking should be washed out by the benefits of updating indexes fewer times. One notable trade-off is that there are more calls to FormIndexDatum() as a result. Caching these might reduce some of that overhead, but not all. This lead to the change in the frequency for expressions in the spec update test to output notice messages, but does not impact correctness. --- src/backend/access/brin/brin.c | 1 + src/backend/access/gin/ginutil.c | 92 +- src/backend/access/hash/hash.c | 44 + src/backend/access/heap/heapam.c | 10 +- src/backend/access/heap/heapam_handler.c | 6 +- src/backend/access/nbtree/nbtree.c | 1 + src/backend/access/table/tableam.c | 4 +- src/backend/bootstrap/bootstrap.c | 8 + src/backend/catalog/index.c | 54 + src/backend/catalog/indexing.c | 16 +- src/backend/catalog/toasting.c | 4 + src/backend/executor/execIndexing.c | 45 +- src/backend/executor/nodeModifyTable.c | 496 ++++- src/backend/nodes/makefuncs.c | 4 + src/include/access/amapi.h | 28 + src/include/access/gin.h | 3 + src/include/access/heapam.h | 6 +- src/include/access/nbtree.h | 4 + src/include/access/tableam.h | 8 +- src/include/catalog/index.h | 1 + src/include/executor/executor.h | 12 +- src/include/nodes/execnodes.h | 19 + .../expected/insert-conflict-specconflict.out | 20 + .../regress/expected/heap_hot_updates.out | 1922 +++++++++++++++++ src/test/regress/parallel_schedule | 6 + src/test/regress/sql/heap_hot_updates.sql | 1325 ++++++++++++ src/tools/pgindent/typedefs.list | 1 + 27 files changed, 4015 insertions(+), 125 deletions(-) create mode 100644 src/test/regress/expected/heap_hot_updates.out create mode 100644 src/test/regress/sql/heap_hot_updates.sql diff --git a/src/backend/access/brin/brin.c b/src/backend/access/brin/brin.c index cb3331921cb..36e639552e6 100644 --- a/src/backend/access/brin/brin.c +++ b/src/backend/access/brin/brin.c @@ -290,6 +290,7 @@ brinhandler(PG_FUNCTION_ARGS) amroutine->amproperty = NULL; amroutine->ambuildphasename = NULL; amroutine->amvalidate = brinvalidate; + amroutine->amcomparedatums = NULL; amroutine->amadjustmembers = NULL; amroutine->ambeginscan = brinbeginscan; amroutine->amrescan = brinrescan; diff --git a/src/backend/access/gin/ginutil.c b/src/backend/access/gin/ginutil.c index 78f7b7a2495..8e31ec21c1c 100644 --- a/src/backend/access/gin/ginutil.c +++ b/src/backend/access/gin/ginutil.c @@ -26,6 +26,7 @@ #include "storage/indexfsm.h" #include "utils/builtins.h" #include "utils/index_selfuncs.h" +#include "utils/memutils.h" #include "utils/rel.h" #include "utils/typcache.h" @@ -78,6 +79,7 @@ ginhandler(PG_FUNCTION_ARGS) amroutine->amproperty = NULL; amroutine->ambuildphasename = ginbuildphasename; amroutine->amvalidate = ginvalidate; + amroutine->amcomparedatums = gincomparedatums; amroutine->amadjustmembers = ginadjustmembers; amroutine->ambeginscan = ginbeginscan; amroutine->amrescan = ginrescan; @@ -477,13 +479,6 @@ cmpEntries(const void *a, const void *b, void *arg) return res; } - -/* - * Extract the index key values from an indexable item - * - * The resulting key values are sorted, and any duplicates are removed. - * This avoids generating redundant index entries. - */ Datum * ginExtractEntries(GinState *ginstate, OffsetNumber attnum, Datum value, bool isNull, @@ -729,3 +724,86 @@ ginbuildphasename(int64 phasenum) return NULL; } } + +/* + * gincomparedatums - Compare datums to determine if they produce identical keys + * + * This function extracts keys from both old_datum and new_datum using the + * opclass's extractValue function, then compares the extracted key arrays. + * Returns true if the key sets are identical (same keys, same counts). + * + * This enables HOT updates for GIN indexes when the indexed portions of a + * value haven't changed, even if the value itself has changed. + * + * Example: JSONB column with GIN index. If an update changes a non-indexed + * key in the JSONB document, the extracted keys are identical and we can + * do a HOT update. + */ +bool +gincomparedatums(Relation index, int attnum, + Datum old_datum, bool old_isnull, + Datum new_datum, bool new_isnull) +{ + GinState ginstate; + Datum *old_keys; + Datum *new_keys; + GinNullCategory *old_categories; + GinNullCategory *new_categories; + int32 old_nkeys; + int32 new_nkeys; + MemoryContext tmpcontext; + MemoryContext oldcontext; + bool result = true; + + /* Handle NULL cases */ + if (old_isnull != new_isnull) + return false; + if (old_isnull) + return true; + + /* Create temporary context for extraction work */ + tmpcontext = AllocSetContextCreate(CurrentMemoryContext, + "GIN datum comparison", + ALLOCSET_DEFAULT_SIZES); + oldcontext = MemoryContextSwitchTo(tmpcontext); + + initGinState(&ginstate, index); + + /* Extract keys from both datums using existing GIN infrastructure */ + old_keys = ginExtractEntries(&ginstate, attnum, old_datum, old_isnull, + &old_nkeys, &old_categories); + new_keys = ginExtractEntries(&ginstate, attnum, new_datum, new_isnull, + &new_nkeys, &new_categories); + + /* Different number of keys, definitely different */ + if (old_nkeys != new_nkeys) + { + result = false; + goto cleanup; + } + + /* + * Compare the sorted key arrays element-by-element. Since both arrays are + * already sorted by ginExtractEntries, we can do a simple O(n) + * comparison. + */ + for (int i = 0; i < old_nkeys; i++) + { + int cmp = ginCompareEntries(&ginstate, attnum, + old_keys[i], old_categories[i], + new_keys[i], new_categories[i]); + + if (cmp != 0) + { + result = false; + break; + } + } + +cleanup: + /* Clean up */ + MemoryContextSwitchTo(oldcontext); + MemoryContextDelete(tmpcontext); + + return result; +} diff --git a/src/backend/access/hash/hash.c b/src/backend/access/hash/hash.c index 53061c819fb..91371dfdacd 100644 --- a/src/backend/access/hash/hash.c +++ b/src/backend/access/hash/hash.c @@ -50,6 +50,10 @@ static void hashbuildCallback(Relation index, void *state); +static bool hashcomparedatums(Relation index, int attnum, + Datum old_datum, bool old_isnull, + Datum new_datum, bool new_isnull); + /* * Hash handler function: return IndexAmRoutine with access method parameters * and callbacks. @@ -98,6 +102,7 @@ hashhandler(PG_FUNCTION_ARGS) amroutine->amproperty = NULL; amroutine->ambuildphasename = NULL; amroutine->amvalidate = hashvalidate; + amroutine->amcomparedatums = hashcomparedatums; amroutine->amadjustmembers = hashadjustmembers; amroutine->ambeginscan = hashbeginscan; amroutine->amrescan = hashrescan; @@ -944,3 +949,42 @@ hashtranslatecmptype(CompareType cmptype, Oid opfamily) return HTEqualStrategyNumber; return InvalidStrategy; } + +/* + * hashcomparedatums - Compare datums to determine if they produce identical keys + * + * Returns true if the hash values are identical (index doesn't need update). + */ +bool +hashcomparedatums(Relation index, int attnum, + Datum old_datum, bool old_isnull, + Datum new_datum, bool new_isnull) +{ + uint32 old_hashkey; + uint32 new_hashkey; + + /* If both are NULL, they're equal */ + if (old_isnull && new_isnull) + return true; + + /* If NULL status differs, they're not equal */ + if (old_isnull != new_isnull) + return false; + + /* + * _hash_datum2hashkey() is used because we know this can't be a cross + * type comparison. + */ + old_hashkey = _hash_datum2hashkey(index, old_datum); + new_hashkey = _hash_datum2hashkey(index, new_datum); + + /* + * If hash keys are identical, the index entry would be the same. Return + * true to indicate no index update needed. + * + * Note: Hash collisions are rare but possible. If hash(x) == hash(y) but + * x != y, the hash index still treats them identically, so we correctly + * return true. + */ + return (old_hashkey == new_hashkey); +} diff --git a/src/backend/access/heap/heapam.c b/src/backend/access/heap/heapam.c index 1cdb72b3a7a..5b0ff13b13d 100644 --- a/src/backend/access/heap/heapam.c +++ b/src/backend/access/heap/heapam.c @@ -3268,7 +3268,7 @@ heap_update(Relation relation, HeapTupleData *oldtup, HeapTuple newtup, TM_FailureData *tmfd, LockTupleMode *lockmode, Buffer buffer, Page page, BlockNumber block, ItemId lp, Bitmapset *hot_attrs, Bitmapset *sum_attrs, Bitmapset *pk_attrs, - Bitmapset *rid_attrs, Bitmapset *mix_attrs, Buffer *vmbuffer, + Bitmapset *rid_attrs, const Bitmapset *mix_attrs, Buffer *vmbuffer, bool rep_id_key_required, TU_UpdateIndexes *update_indexes) { TM_Result result; @@ -4337,8 +4337,9 @@ HeapDetermineColumnsInfo(Relation relation, * This routine may be used to update a tuple when concurrent updates of the * target tuple are not expected (for example, because we have a lock on the * relation associated with the tuple). Any failure is reported via ereport(). + * Returns the set of modified indexed attributes. */ -void +Bitmapset * simple_heap_update(Relation relation, const ItemPointerData *otid, HeapTuple tuple, TU_UpdateIndexes *update_indexes) { @@ -4467,7 +4468,7 @@ simple_heap_update(Relation relation, const ItemPointerData *otid, HeapTuple tup elog(ERROR, "tuple concurrently deleted"); - return; + return NULL; } /* @@ -4500,7 +4501,6 @@ simple_heap_update(Relation relation, const ItemPointerData *otid, HeapTuple tup bms_free(sum_attrs); bms_free(pk_attrs); bms_free(rid_attrs); - bms_free(mix_attrs); bms_free(idx_attrs); switch (result) @@ -4526,6 +4526,8 @@ simple_heap_update(Relation relation, const ItemPointerData *otid, HeapTuple tup elog(ERROR, "unrecognized heap_update status: %u", result); break; } + + return mix_attrs; } diff --git a/src/backend/access/heap/heapam_handler.c b/src/backend/access/heap/heapam_handler.c index ef08e1d3e10..7527809ec08 100644 --- a/src/backend/access/heap/heapam_handler.c +++ b/src/backend/access/heap/heapam_handler.c @@ -319,7 +319,7 @@ heapam_tuple_update(Relation relation, ItemPointer otid, TupleTableSlot *slot, Snapshot crosscheck, bool wait, TM_FailureData *tmfd, LockTupleMode *lockmode, - Bitmapset *mix_attrs, + const Bitmapset *mix_attrs, TU_UpdateIndexes *update_indexes) { bool rep_id_key_required = false; @@ -407,10 +407,6 @@ heapam_tuple_update(Relation relation, ItemPointer otid, TupleTableSlot *slot, Assert(ItemIdIsNormal(lp)); - /* - * Partially construct the oldtup for HeapDetermineColumnsInfo to work and - * then pass that on to heap_update. - */ oldtup.t_tableOid = RelationGetRelid(relation); oldtup.t_data = (HeapTupleHeader) PageGetItem(page, lp); oldtup.t_len = ItemIdGetLength(lp); diff --git a/src/backend/access/nbtree/nbtree.c b/src/backend/access/nbtree/nbtree.c index fdff960c130..e435f0d5db4 100644 --- a/src/backend/access/nbtree/nbtree.c +++ b/src/backend/access/nbtree/nbtree.c @@ -155,6 +155,7 @@ bthandler(PG_FUNCTION_ARGS) amroutine->amproperty = btproperty; amroutine->ambuildphasename = btbuildphasename; amroutine->amvalidate = btvalidate; + amroutine->amcomparedatums = NULL; amroutine->amadjustmembers = btadjustmembers; amroutine->ambeginscan = btbeginscan; amroutine->amrescan = btrescan; diff --git a/src/backend/access/table/tableam.c b/src/backend/access/table/tableam.c index dadcf03ed24..ef7736bfa76 100644 --- a/src/backend/access/table/tableam.c +++ b/src/backend/access/table/tableam.c @@ -336,7 +336,7 @@ void simple_table_tuple_update(Relation rel, ItemPointer otid, TupleTableSlot *slot, Snapshot snapshot, - Bitmapset *modified_indexed_cols, + const Bitmapset *mix_attrs, TU_UpdateIndexes *update_indexes) { TM_Result result; @@ -348,7 +348,7 @@ simple_table_tuple_update(Relation rel, ItemPointer otid, snapshot, InvalidSnapshot, true /* wait for commit */ , &tmfd, &lockmode, - modified_indexed_cols, + mix_attrs, update_indexes); switch (result) diff --git a/src/backend/bootstrap/bootstrap.c b/src/backend/bootstrap/bootstrap.c index fc8638c1b61..329c110d0bf 100644 --- a/src/backend/bootstrap/bootstrap.c +++ b/src/backend/bootstrap/bootstrap.c @@ -961,10 +961,18 @@ index_register(Oid heap, newind->il_info->ii_Expressions = copyObject(indexInfo->ii_Expressions); newind->il_info->ii_ExpressionsState = NIL; + /* expression attrs will likely be null, but may as well copy it */ + newind->il_info->ii_ExpressionsAttrs = + copyObject(indexInfo->ii_ExpressionsAttrs); /* predicate will likely be null, but may as well copy it */ newind->il_info->ii_Predicate = copyObject(indexInfo->ii_Predicate); newind->il_info->ii_PredicateState = NULL; + /* predicate attrs will likely be null, but may as well copy it */ + newind->il_info->ii_PredicateAttrs = + copyObject(indexInfo->ii_PredicateAttrs); + newind->il_info->ii_CheckedPredicate = false; + newind->il_info->ii_PredicateSatisfied = false; /* no exclusion constraints at bootstrap time, so no need to copy */ Assert(indexInfo->ii_ExclusionOps == NULL); Assert(indexInfo->ii_ExclusionProcs == NULL); diff --git a/src/backend/catalog/index.c b/src/backend/catalog/index.c index 5d9db167e59..e88db7e919b 100644 --- a/src/backend/catalog/index.c +++ b/src/backend/catalog/index.c @@ -27,6 +27,7 @@ #include "access/heapam.h" #include "access/multixact.h" #include "access/relscan.h" +#include "access/sysattr.h" #include "access/tableam.h" #include "access/toast_compression.h" #include "access/transam.h" @@ -58,6 +59,7 @@ #include "commands/trigger.h" #include "executor/executor.h" #include "miscadmin.h" +#include "nodes/execnodes.h" #include "nodes/makefuncs.h" #include "nodes/nodeFuncs.h" #include "optimizer/optimizer.h" @@ -2414,6 +2416,58 @@ index_drop(Oid indexId, bool concurrent, bool concurrent_lock_mode) * ---------------------------------------------------------------- */ +/* ---------------- + * BuildUpdateIndexInfo + * + * For expression indexes updates may not change the indexed value allowing + * for a HOT update. Add information to the IndexInfo to allow for checking + * if the indexed value has changed. + * + * Do this processing here rather than in BuildIndexInfo() to not incur the + * overhead in the common non-expression cases. + * ---------------- + */ +void +BuildUpdateIndexInfo(ResultRelInfo *resultRelInfo) +{ + for (int j = 0; j < resultRelInfo->ri_NumIndices; j++) + { + int i; + int indnatts; + Bitmapset *attrs = NULL; + IndexInfo *ii = resultRelInfo->ri_IndexRelationInfo[j]; + + indnatts = ii->ii_NumIndexAttrs; + + /* Collect key attributes used by the index, key and including */ + for (i = 0; i < indnatts; i++) + { + AttrNumber attnum = ii->ii_IndexAttrNumbers[i]; + + if (attnum != 0) + attrs = bms_add_member(attrs, attnum - FirstLowInvalidHeapAttributeNumber); + } + + /* Collect attributes used in the expression */ + if (ii->ii_Expressions) + pull_varattnos((Node *) ii->ii_Expressions, + resultRelInfo->ri_RangeTableIndex, + &ii->ii_ExpressionsAttrs); + + /* Collect attributes used in the predicate */ + if (ii->ii_Predicate) + pull_varattnos((Node *) ii->ii_Predicate, + resultRelInfo->ri_RangeTableIndex, + &ii->ii_PredicateAttrs); + + /* Combine key, including, and expression attributes, but not predicate */ + ii->ii_IndexedAttrs = bms_union(attrs, ii->ii_ExpressionsAttrs); + + /* All indexes should index *something*! */ + Assert(!bms_is_empty(ii->ii_IndexedAttrs)); + } +} + /* ---------------- * BuildIndexInfo * Construct an IndexInfo record for an open index diff --git a/src/backend/catalog/indexing.c b/src/backend/catalog/indexing.c index 004c5121000..a361c215490 100644 --- a/src/backend/catalog/indexing.c +++ b/src/backend/catalog/indexing.c @@ -102,7 +102,7 @@ CatalogIndexInsert(CatalogIndexState indstate, HeapTuple heapTuple, * Get information from the state structure. Fall out if nothing to do. */ numIndexes = indstate->ri_NumIndices; - if (numIndexes == 0) + if (numIndexes == 0 || updateIndexes == TU_None) return; relationDescs = indstate->ri_IndexRelationDescs; indexInfoArray = indstate->ri_IndexRelationInfo; @@ -314,15 +314,18 @@ CatalogTupleUpdate(Relation heapRel, const ItemPointerData *otid, HeapTuple tup) { CatalogIndexState indstate; TU_UpdateIndexes updateIndexes = TU_All; + Bitmapset *updatedAttrs; CatalogTupleCheckConstraints(heapRel, tup); indstate = CatalogOpenIndexes(heapRel); - simple_heap_update(heapRel, otid, tup, &updateIndexes); - + updatedAttrs = simple_heap_update(heapRel, otid, tup, &updateIndexes); + ((ResultRelInfo *) indstate)->ri_ChangedIndexedCols = updatedAttrs; CatalogIndexInsert(indstate, tup, updateIndexes); + CatalogCloseIndexes(indstate); + bms_free(updatedAttrs); } /* @@ -338,12 +341,15 @@ CatalogTupleUpdateWithInfo(Relation heapRel, const ItemPointerData *otid, HeapTu CatalogIndexState indstate) { TU_UpdateIndexes updateIndexes = TU_All; + Bitmapset *updatedAttrs; CatalogTupleCheckConstraints(heapRel, tup); - simple_heap_update(heapRel, otid, tup, &updateIndexes); - + updatedAttrs = simple_heap_update(heapRel, otid, tup, &updateIndexes); + ((ResultRelInfo *) indstate)->ri_ChangedIndexedCols = updatedAttrs; CatalogIndexInsert(indstate, tup, updateIndexes); + ((ResultRelInfo *) indstate)->ri_ChangedIndexedCols = NULL; + bms_free(updatedAttrs); } /* diff --git a/src/backend/catalog/toasting.c b/src/backend/catalog/toasting.c index 5d819bda54a..c665aa744b3 100644 --- a/src/backend/catalog/toasting.c +++ b/src/backend/catalog/toasting.c @@ -292,8 +292,12 @@ create_toast_table(Relation rel, Oid toastOid, Oid toastIndexOid, indexInfo->ii_IndexAttrNumbers[1] = 2; indexInfo->ii_Expressions = NIL; indexInfo->ii_ExpressionsState = NIL; + indexInfo->ii_ExpressionsAttrs = NULL; indexInfo->ii_Predicate = NIL; indexInfo->ii_PredicateState = NULL; + indexInfo->ii_PredicateAttrs = NULL; + indexInfo->ii_CheckedPredicate = false; + indexInfo->ii_PredicateSatisfied = false; indexInfo->ii_ExclusionOps = NULL; indexInfo->ii_ExclusionProcs = NULL; indexInfo->ii_ExclusionStrats = NULL; diff --git a/src/backend/executor/execIndexing.c b/src/backend/executor/execIndexing.c index fb1bc3a480d..20968a814d6 100644 --- a/src/backend/executor/execIndexing.c +++ b/src/backend/executor/execIndexing.c @@ -109,11 +109,15 @@ #include "access/genam.h" #include "access/relscan.h" #include "access/tableam.h" +#include "access/sysattr.h" #include "access/xact.h" #include "catalog/index.h" #include "executor/executor.h" +#include "nodes/bitmapset.h" +#include "nodes/execnodes.h" #include "nodes/nodeFuncs.h" #include "storage/lmgr.h" +#include "utils/datum.h" #include "utils/multirangetypes.h" #include "utils/rangetypes.h" #include "utils/snapmgr.h" @@ -318,8 +322,8 @@ ExecInsertIndexTuples(ResultRelInfo *resultRelInfo, Relation heapRelation; IndexInfo **indexInfoArray; ExprContext *econtext; - Datum values[INDEX_MAX_KEYS]; - bool isnull[INDEX_MAX_KEYS]; + Datum loc_values[INDEX_MAX_KEYS]; + bool loc_isnull[INDEX_MAX_KEYS]; Assert(ItemPointerIsValid(tupleid)); @@ -343,13 +347,13 @@ ExecInsertIndexTuples(ResultRelInfo *resultRelInfo, /* Arrange for econtext's scan tuple to be the tuple under test */ econtext->ecxt_scantuple = slot; - /* - * for each index, form and insert the index tuple - */ + /* Insert into each index that needs updating */ for (i = 0; i < numIndices; i++) { Relation indexRelation = relationDescs[i]; IndexInfo *indexInfo; + Datum *values; + bool *isnull; bool applyNoDupErr; IndexUniqueCheck checkUnique; bool indexUnchanged; @@ -366,7 +370,7 @@ ExecInsertIndexTuples(ResultRelInfo *resultRelInfo, /* * Skip processing of non-summarizing indexes if we only update - * summarizing indexes + * summarizing indexes or if this index is unchanged. */ if (onlySummarizing && !indexInfo->ii_Summarizing) continue; @@ -387,8 +391,15 @@ ExecInsertIndexTuples(ResultRelInfo *resultRelInfo, indexInfo->ii_PredicateState = predicate; } + /* Check the index predicate if we haven't done so earlier on */ + if (!indexInfo->ii_CheckedPredicate) + { + indexInfo->ii_PredicateSatisfied = ExecQual(predicate, econtext); + indexInfo->ii_CheckedPredicate = true; + } + /* Skip this index-update if the predicate isn't satisfied */ - if (!ExecQual(predicate, econtext)) + if (!indexInfo->ii_PredicateSatisfied) continue; } @@ -396,11 +407,10 @@ ExecInsertIndexTuples(ResultRelInfo *resultRelInfo, * FormIndexDatum fills in its values and isnull parameters with the * appropriate values for the column(s) of the index. */ - FormIndexDatum(indexInfo, - slot, - estate, - values, - isnull); + FormIndexDatum(indexInfo, slot, estate, loc_values, loc_isnull); + + values = loc_values; + isnull = loc_isnull; /* Check whether to apply noDupErr to this index */ applyNoDupErr = noDupErr && @@ -435,7 +445,9 @@ ExecInsertIndexTuples(ResultRelInfo *resultRelInfo, * index. If we're being called as part of an UPDATE statement, * consider if the 'indexUnchanged' = true hint should be passed. */ - indexUnchanged = update && bms_is_empty(resultRelInfo->ri_ChangedIndexedCols); + indexUnchanged = update && + !bms_overlap(indexInfo->ii_IndexedAttrs, + resultRelInfo->ri_ChangedIndexedCols); satisfiesConstraint = index_insert(indexRelation, /* index relation */ @@ -604,7 +616,12 @@ ExecCheckIndexConstraints(ResultRelInfo *resultRelInfo, TupleTableSlot *slot, checkedIndex = true; /* Check for partial index */ - if (indexInfo->ii_Predicate != NIL) + if (indexInfo->ii_CheckedPredicate && !indexInfo->ii_PredicateSatisfied) + { + /* We've already checked and the predicate wasn't satisfied. */ + continue; + } + else if (indexInfo->ii_Predicate != NIL) { ExprState *predicate; diff --git a/src/backend/executor/nodeModifyTable.c b/src/backend/executor/nodeModifyTable.c index 34f86546fc9..ea50fcaf5dd 100644 --- a/src/backend/executor/nodeModifyTable.c +++ b/src/backend/executor/nodeModifyTable.c @@ -54,10 +54,13 @@ #include "postgres.h" #include "access/htup_details.h" +#include "access/attnum.h" +#include "access/sysattr.h" #include "access/tableam.h" #include "access/tupconvert.h" #include "access/tupdesc.h" #include "access/xact.h" +#include "catalog/index.h" #include "commands/trigger.h" #include "executor/execPartition.h" #include "executor/executor.h" @@ -75,6 +78,7 @@ #include "utils/float.h" #include "utils/lsyscache.h" #include "utils/rel.h" +#include "utils/relcache.h" #include "utils/snapmgr.h" @@ -245,6 +249,10 @@ tts_attr_equal(Oid typid, Oid collation, bool typbyval, int16 typlen, typentry = lookup_type_cache(typid, TYPECACHE_EQ_OPR | TYPECACHE_EQ_OPR_FINFO); + /* Use the type's collation if none provided */ + if (collation == -1) + collation = typentry->typcollation; + /* * If no equality operator is available, fall back to binary comparison. * This handles types that don't have proper equality operators defined. @@ -291,108 +299,415 @@ tts_attr_equal(Oid typid, Oid collation, bool typbyval, int16 typlen, } /* - * Determine which updated attributes actually changed values between old and - * new tuples and are referenced by indexes on the relation. + * ExecCheckIndexedAttrsForChanges + * + * Determine which indexes need updating by finding the set of modified + * indexed attributes. + * + * For expression indexes and indexes which implement the amcomparedatums() + * index AM API we'll need to form index datum and compare each attribute to + * see if any actually changed. + * + * For expression indexes the result of the expression might not change at all, + * this is common with JSONB columns, which require expression indexes. It is + * is commonplace to index one or more fields within a document and perform + * updates to the document while leaving the indexed fields unchanged. These + * updates don't necessitate index updates. + * + * Partial indexes won't trigger index updates when the old/new tuples are both + * outside of the predicate range. A transition into or out of the predicate + * does require an index update. + * + * Indexes that support index-only scans (IOS) should return the value that + * is the binary equavalent of what is in the table. For that reason we must + * use datumIsEqual() when deciding if an index update is required or not. + * + * All other indexes require testing old/new datum for equality, we now test + * with a type-specific equality operator and fall back to datumIsEqual() + * when that isn't possible. + * + * For a BTREE index (nbtree) their is an additional reason to use binary + * comparison for equality. TID deduplication on page split in nbtree uses + * binary comparison. + * + * The goal is for the executor to know, ahead of calling into the table AM to + * process the update and before calling into the index AM for inserting new + * index tuples, which attributes in the new TupleTableSlot, if any, truely + * necessitate a new index tuple. * - * Returns a Bitmapset of attribute offsets (0-based, adjusted by - * FirstLowInvalidHeapAttributeNumber) or NULL if no attributes changed. + * Returns a Bitmapset of attributes that intersects with indexes which require + * a new index tuple. */ Bitmapset * ExecCheckIndexedAttrsForChanges(ResultRelInfo *relinfo, - TupleTableSlot *tts_old, - TupleTableSlot *tts_new) + EState *estate, + TupleTableSlot *old_tts, + TupleTableSlot *new_tts) { Relation relation = relinfo->ri_RelationDesc; TupleDesc tupdesc = RelationGetDescr(relation); - Bitmapset *indexed_attrs; - Bitmapset *modified = NULL; - int attidx; + Bitmapset *mix_attrs = NULL; /* If no indexes, we're done */ if (relinfo->ri_NumIndices == 0) return NULL; /* - * Get the set of index key attributes. This includes summarizing, - * expression indexes and attributes mentioned in the predicate of a - * partition but not those in INCLUDING. + * NOTE: Expression and predicates that are observed to change will have + * all their attributes added into the m_attrs set knowing that some of + * those might not have changed. Take for instance an index on (a + b) + * followed by an index on (b) with an update that changes only the value + * of 'a'. We'll add both 'a' and 'b' to the m_attrs set then later when + * reviewing the second index add 'b' to the u_attrs (unchanged) set. In + * the end, we'll remove all the unchanged from the m_attrs and get our + * desired result. */ - indexed_attrs = RelationGetIndexAttrBitmap(relation, - INDEX_ATTR_BITMAP_INDEXED); - Assert(!bms_is_empty(indexed_attrs)); - /* - * NOTE: It is important to scan all indexed attributes in the tuples - * because ExecGetAllUpdatedCols won't include columns that may have been - * modified via heap_modify_tuple_by_col which is the case in - * tsvector_update_trigger. - */ - attidx = -1; - while ((attidx = bms_next_member(indexed_attrs, attidx)) >= 0) + /* Find the indexes that reference this attribute */ + for (int i = 0; i < relinfo->ri_NumIndices; i++) { - /* attidx is zero-based, attrnum is the normal attribute number */ - AttrNumber attrnum = attidx + FirstLowInvalidHeapAttributeNumber; - Form_pg_attribute attr; - bool oldnull, - newnull; - Datum oldval, - newval; + Relation index = relinfo->ri_IndexRelationDescs[i]; + IndexAmRoutine *amroutine = index->rd_indam; + IndexInfo *indexInfo = relinfo->ri_IndexRelationInfo[i]; + Bitmapset *m_attrs = NULL; /* (possibly) modified key attributes */ + Bitmapset *p_attrs = NULL; /* (possibly) modified predicate + * attributes */ + Bitmapset *u_attrs = NULL; /* unmodified attributes */ + Bitmapset *pre_attrs = indexInfo->ii_PredicateAttrs; + bool has_expressions = (indexInfo->ii_Expressions != NIL); + bool has_am_compare = (amroutine->amcomparedatums != NULL); + bool supports_ios = (amroutine->amcanreturn != NULL); + bool is_partial = (indexInfo->ii_Predicate != NIL); + TupleTableSlot *save_scantuple; + ExprContext *econtext = GetPerTupleExprContext(estate); + Datum old_values[INDEX_MAX_KEYS]; + bool old_isnull[INDEX_MAX_KEYS]; + Datum new_values[INDEX_MAX_KEYS]; + bool new_isnull[INDEX_MAX_KEYS]; + + /* If we've reviewed all the attributes on this index, move on */ + if (bms_is_subset(indexInfo->ii_IndexedAttrs, mix_attrs)) + continue; - /* - * If it's a whole-tuple reference, record as modified. It's not - * really worth supporting this case, since it could only succeed - * after a no-op update, which is hardly a case worth optimizing for. - */ - if (attrnum == 0) + /* Checking partial at this point isn't viable when we're serializable */ + if (is_partial && IsolationIsSerializable()) { - modified = bms_add_member(modified, attidx); - continue; + p_attrs = bms_add_members(p_attrs, pre_attrs); + } + /* Check partial index predicate */ + else if (is_partial) + { + ExprState *pstate; + bool old_qualifies, + new_qualifies; + + if (!indexInfo->ii_CheckedPredicate) + pstate = ExecPrepareQual(indexInfo->ii_Predicate, estate); + else + pstate = indexInfo->ii_PredicateState; + + save_scantuple = econtext->ecxt_scantuple; + + econtext->ecxt_scantuple = old_tts; + old_qualifies = ExecQual(pstate, econtext); + + econtext->ecxt_scantuple = new_tts; + new_qualifies = ExecQual(pstate, econtext); + + econtext->ecxt_scantuple = save_scantuple; + + indexInfo->ii_CheckedPredicate = true; + indexInfo->ii_PredicateState = pstate; + indexInfo->ii_PredicateSatisfied = new_qualifies; + + /* Both outside predicate, index doesn't need update */ + if (!old_qualifies && !new_qualifies) + continue; + + /* A transition means we need to update the index */ + if (old_qualifies != new_qualifies) + p_attrs = bms_copy(pre_attrs); + + /* + * When both are within the predicate we must update this index, + * but only if one of the index key attributes changed. + */ } /* - * Likewise, include in the modified set any system attribute other - * than tableOID; we cannot expect these to be consistent in a HOT - * chain, or even to be set correctly yet in the new tuple. + * Expression indexes, or an index that has a comparison function, + * requires us to form index datums and compare. We've done all we + * can to avoid this overhead, now it's time to bite the bullet and + * get it done. + * + * XXX: Caching the values/isnull might be a win and avoid one of the + * added calls to FormIndexDatum(). */ - if (attrnum < 0) + if (has_expressions || has_am_compare) { - if (attrnum != TableOidAttributeNumber) - modified = bms_add_member(modified, attidx); - continue; - } + save_scantuple = econtext->ecxt_scantuple; - /* Extract values from both slots */ - oldval = slot_getattr(tts_old, attrnum, &oldnull); - newval = slot_getattr(tts_new, attrnum, &newnull); + /* Evaluate expressions (if any) to get base datums */ + econtext->ecxt_scantuple = old_tts; + FormIndexDatum(indexInfo, old_tts, estate, old_values, old_isnull); - /* If one value is NULL and the other is not, they are not equal */ - if (oldnull != newnull) - { - modified = bms_add_member(modified, attidx); - continue; + econtext->ecxt_scantuple = new_tts; + FormIndexDatum(indexInfo, new_tts, estate, new_values, new_isnull); + + econtext->ecxt_scantuple = save_scantuple; + + /* Compare the index key datums for equality */ + for (int j = 0; j < indexInfo->ii_NumIndexKeyAttrs; j++) + { + AttrNumber rel_attrnum = indexInfo->ii_IndexAttrNumbers[j]; + int rel_attridx = rel_attrnum - FirstLowInvalidHeapAttributeNumber; + int nth_expr = 0; + bool values_equal = false; + + /* + * We can't skip attributes that we've already identified as + * triggering an index update because we may have added an + * attribute from an expression index that didn't change but + * the expression did and that unchanged attribute is + * referenced in a subsequent index where we will discover + * that fact. + */ + + /* A change to/from NULL, record this attribute */ + if (old_isnull[j] != new_isnull[j]) + { + /* Expressions will have rel_attrnum == 0 */ + if (rel_attrnum == 0) + m_attrs = bms_add_members(m_attrs, indexInfo->ii_ExpressionsAttrs); + else + m_attrs = bms_add_member(m_attrs, rel_attridx); + continue; + } + + /* Both NULL, no change */ + if (old_isnull[j]) + { + if (rel_attrnum != 0) + u_attrs = bms_add_member(u_attrs, rel_attridx); + + continue; + } + + /* + * Use index AM's comparison function if present when + * comparing the index datum formed when creating an index + * key. + */ + if (has_am_compare) + { + /* + * NOTE: For AM comparison, pass the 1-based index + * attribute number. The AM's compare function expects the + * same numbering as used internally by the AM. + */ + values_equal = amroutine->amcomparedatums(index, j + 1, + old_values[j], old_isnull[j], + new_values[j], new_isnull[j]); + } + else + { + /* Non-zero attribute means not an expression */ + if (rel_attrnum != 0) + { + if (supports_ios) + { + CompactAttribute *attr = TupleDescCompactAttr(tupdesc, rel_attrnum - 1); + + values_equal = datumIsEqual(old_values[j], + new_values[j], + attr->attbyval, + attr->attlen); + } + else + { + Form_pg_attribute attr = TupleDescAttr(tupdesc, rel_attrnum - 1); + + /* + * Compare using type-specific equality which at + * this point is the relation's type because + * FormIndexDatum() will populate the values/nulls + * but won't transform them into the final values + * destined for the index tuple, that's left to + * index_form_tuple() which we don't call (on + * purpose). + */ + values_equal = tts_attr_equal(attr->atttypid, + attr->attcollation, + attr->attbyval, + attr->attlen, + old_values[j], + new_values[j]); + } + } + else + { + /* + * An expression on an indexed attribute without + * custom AM comparison function. In this case, becase + * indexes will store the result of the expression's + * evaluation, we can test for equality using the + * expression's result type. This allows for JSONB + * and custom type equality tests, which may not be + * the same as binary equality, to be in effect. The + * result stored in the index and used in index-only + * scans will be valid as it is the expressions + * result, which shouldn't change given the same + * input. + * + * At this point the expression's type is what is + * required when testing for equality, not the index's + * type, because the value created by FormIndexDatum() + * is the expression's result. Later on in + * index_form_tuple() an index may transform the value + * when forming it's key (as is the case with HASH), + * but at this point the Datum is the expression's + * result type. + */ + Oid expr_type_oid; + int16 typlen; + bool typbyval; + Expr *expr = (Expr *) list_nth(indexInfo->ii_Expressions, nth_expr); + + Assert(expr != NULL); + + /* Get type OID from the expression */ + expr_type_oid = exprType((Node *) expr); + + /* Get type information from the OID */ + get_typlenbyval(expr_type_oid, &typlen, &typbyval); + + values_equal = tts_attr_equal(expr_type_oid, + -1, /* use TBD expr type */ + typbyval, + typlen, + old_values[j], + new_values[j]); + } + } + + if (!values_equal) + { + /* Expressions will have rel_attrnum == 0 */ + if (rel_attrnum == 0) + m_attrs = bms_add_members(m_attrs, indexInfo->ii_ExpressionsAttrs); + else + m_attrs = bms_add_member(m_attrs, rel_attridx); + } + else + { + if (rel_attrnum != 0) + u_attrs = bms_add_member(u_attrs, rel_attridx); + } + + if (rel_attrnum == 0) + nth_expr++; + } } + else + { + /* + * Here we know that we're reviewing an index that doesn't have a + * partial predicate, doesn't use expressions, and doesn't have a + * amcomparedatums() implementation. If this index supports IOS + * we need to use binary comparison, if not then type-specific + * will provide a more accurate result. + */ - /* If both are NULL, consider them equal */ - if (oldnull) - continue; + /* Compare the index key datums for equality */ + for (int j = 0; j < indexInfo->ii_NumIndexKeyAttrs; j++) + { + AttrNumber rel_attrnum; + int rel_attridx; + bool values_equal = false; + bool old_null, + new_null; + Datum old_val, + new_val; - /* Get attribute metadata */ - Assert(attrnum > 0 && attrnum <= tupdesc->natts); - attr = TupleDescAttr(tupdesc, attrnum - 1); - - /* Compare using type-specific equality operator */ - if (!tts_attr_equal(attr->atttypid, - attr->attcollation, - attr->attbyval, - attr->attlen, - oldval, - newval)) - modified = bms_add_member(modified, attidx); - } + rel_attrnum = indexInfo->ii_IndexAttrNumbers[j]; + rel_attridx = rel_attrnum - FirstLowInvalidHeapAttributeNumber; + + /* Zero would mean expression, something we don't expect here */ + Assert(rel_attrnum > 0 && rel_attrnum <= tupdesc->natts); + + /* Extract values from both slots for this attribute */ + old_val = slot_getattr(old_tts, rel_attrnum, &old_null); + new_val = slot_getattr(new_tts, rel_attrnum, &new_null); - bms_free(indexed_attrs); + /* + * If one value is NULL and the other is not, they are not + * equal + */ + if (old_null != new_null) + { + m_attrs = bms_add_member(m_attrs, rel_attridx); + continue; + } + + /* If both are NULL, consider them equal */ + if (old_null) + { + u_attrs = bms_add_member(u_attrs, rel_attridx); + continue; + } + + if (supports_ios) + { + CompactAttribute *attr = TupleDescCompactAttr(tupdesc, rel_attrnum - 1); + + values_equal = datumIsEqual(old_val, + new_val, + attr->attbyval, + attr->attlen); + } + else + { + Form_pg_attribute attr = TupleDescAttr(tupdesc, rel_attrnum - 1); + + /* + * Compare using type-specific equality which at this + * point is the relation's type because FormIndexDatum() + * will populate the values/nulls but won't transform them + * into the final values destined for the index tuple, + * that's left to index_form_tuple() which we don't call + * (on purpose). + */ + values_equal = tts_attr_equal(attr->atttypid, + attr->attcollation, + attr->attbyval, + attr->attlen, + old_val, + new_val); + } + + if (!values_equal) + m_attrs = bms_add_member(m_attrs, rel_attridx); + else + u_attrs = bms_add_member(u_attrs, rel_attridx); + } + } + + /* + * Here we know all the attributes we thought might be modified and + * all those we know haven't been. Take the difference and add it to + * the modified indexed attributes set. + */ + m_attrs = bms_del_members(m_attrs, u_attrs); + p_attrs = bms_del_members(p_attrs, u_attrs); + mix_attrs = bms_add_members(mix_attrs, m_attrs); + mix_attrs = bms_add_members(mix_attrs, p_attrs); + + bms_free(m_attrs); + bms_free(u_attrs); + bms_free(p_attrs); + } - return modified; + return mix_attrs; } /* @@ -2395,6 +2710,9 @@ ExecUpdateAct(ModifyTableContext *context, ResultRelInfo *resultRelInfo, bool partition_constraint_failed; TM_Result result; + /* The set of modified indexed attributes that trigger new index entries */ + Bitmapset *mix_attrs = NULL; + updateCxt->crossPartUpdate = false; /* @@ -2517,13 +2835,32 @@ lreplace: bms_free(resultRelInfo->ri_ChangedIndexedCols); resultRelInfo->ri_ChangedIndexedCols = NULL; - resultRelInfo->ri_ChangedIndexedCols = - ExecCheckIndexedAttrsForChanges(resultRelInfo, oldSlot, slot); + /* + * During updates we'll need a bit more information in IndexInfo but we've + * delayed adding it until here. We check to ensure that there are + * indexes, that something has changed that is indexed, and that the first + * index doesn't yet have ii_IndexedAttrs set as a way to ensure we only + * build this when needed and only once. We don't build this in + * ExecOpenIndicies() as it is unnecessary overhead when not performing an + * update. + */ + if (resultRelInfo->ri_NumIndices > 0 && + bms_is_empty(resultRelInfo->ri_IndexRelationInfo[0]->ii_IndexedAttrs)) + BuildUpdateIndexInfo(resultRelInfo); + + /* + * Next up we need to find out the set of indexed attributes that have + * changed in value and should trigger a new index tuple. We could start + * with the set of updated columns via ExecGetUpdatedCols(), but if we do + * we will overlook attributes directly modified by heap_modify_tuple() + * which are not known to ExecGetUpdatedCols(). + */ + mix_attrs = ExecCheckIndexedAttrsForChanges(resultRelInfo, estate, oldSlot, slot); /* - * replace the heap tuple + * Call into the table AM to update the heap tuple. * - * Note: if es_crosscheck_snapshot isn't InvalidSnapshot, we check that + * NOTE: if es_crosscheck_snapshot isn't InvalidSnapshot, we check that * the row to be updated is visible to that snapshot, and throw a * can't-serialize error if not. This is a special-case behavior needed * for referential integrity updates in transaction-snapshot mode @@ -2535,9 +2872,12 @@ lreplace: estate->es_crosscheck_snapshot, true /* wait for commit */ , &context->tmfd, &updateCxt->lockmode, - resultRelInfo->ri_ChangedIndexedCols, + mix_attrs, &updateCxt->updateIndexes); + Assert(bms_is_empty(resultRelInfo->ri_ChangedIndexedCols)); + resultRelInfo->ri_ChangedIndexedCols = mix_attrs; + return result; } @@ -2555,7 +2895,7 @@ ExecUpdateEpilogue(ModifyTableContext *context, UpdateContext *updateCxt, ModifyTableState *mtstate = context->mtstate; List *recheckIndexes = NIL; - /* insert index entries for tuple if necessary */ + /* Insert index entries for tuple if necessary */ if (resultRelInfo->ri_NumIndices > 0 && (updateCxt->updateIndexes != TU_None)) recheckIndexes = ExecInsertIndexTuples(resultRelInfo, slot, context->estate, diff --git a/src/backend/nodes/makefuncs.c b/src/backend/nodes/makefuncs.c index d69dc090aa4..e9a53b95caf 100644 --- a/src/backend/nodes/makefuncs.c +++ b/src/backend/nodes/makefuncs.c @@ -855,10 +855,14 @@ makeIndexInfo(int numattrs, int numkeyattrs, Oid amoid, List *expressions, /* expressions */ n->ii_Expressions = expressions; n->ii_ExpressionsState = NIL; + n->ii_ExpressionsAttrs = NULL; /* predicates */ n->ii_Predicate = predicates; n->ii_PredicateState = NULL; + n->ii_PredicateAttrs = NULL; + n->ii_CheckedPredicate = false; + n->ii_PredicateSatisfied = false; /* exclusion constraints */ n->ii_ExclusionOps = NULL; diff --git a/src/include/access/amapi.h b/src/include/access/amapi.h index 63dd41c1f21..9bdf73eda59 100644 --- a/src/include/access/amapi.h +++ b/src/include/access/amapi.h @@ -211,6 +211,33 @@ typedef void (*ammarkpos_function) (IndexScanDesc scan); /* restore marked scan position */ typedef void (*amrestrpos_function) (IndexScanDesc scan); +/* + * amcomparedatums - Compare datums to determine if index update is needed + * + * This function compares old_datum and new_datum to determine if they would + * produce different index entries. For extraction-based indexes (GIN, RUM), + * this should: + * 1. Extract keys from old_datum using the opclass's extractValue function + * 2. Extract keys from new_datum using the opclass's extractValue function + * 3. Compare the two sets of keys using appropriate equality operators + * 4. Return true if the sets are equal (no index update needed) + * + * The comparison should account for: + * - Different numbers of extracted keys + * - NULL values + * - Type-specific equality (not just binary equality) + * - Opclass parameters (e.g., path in bson_rum_single_path_ops) + * + * For the DocumentDB example with path='a', this would extract values at + * path 'a' from both old and new BSON documents and compare them using + * BSON's equality operator. + */ +/* identify if updated datums would produce one or more index entries */ +typedef bool (*amcomparedatums_function) (Relation indexRelation, + int attno, + Datum old_datum, bool old_isnull, + Datum new_datum, bool new_isnull); + /* * Callback function signatures - for parallel index scans. */ @@ -313,6 +340,7 @@ typedef struct IndexAmRoutine amendscan_function amendscan; ammarkpos_function ammarkpos; /* can be NULL */ amrestrpos_function amrestrpos; /* can be NULL */ + amcomparedatums_function amcomparedatums; /* can be NULL */ /* interface functions to support parallel index scans */ amestimateparallelscan_function amestimateparallelscan; /* can be NULL */ diff --git a/src/include/access/gin.h b/src/include/access/gin.h index 13ea91922ef..2f265f4816c 100644 --- a/src/include/access/gin.h +++ b/src/include/access/gin.h @@ -100,6 +100,9 @@ extern PGDLLIMPORT int gin_pending_list_limit; extern void ginGetStats(Relation index, GinStatsData *stats); extern void ginUpdateStats(Relation index, const GinStatsData *stats, bool is_build); +extern bool gincomparedatums(Relation index, int attnum, + Datum old_datum, bool old_isnull, + Datum new_datum, bool new_isnull); extern void _gin_parallel_build_main(dsm_segment *seg, shm_toc *toc); diff --git a/src/include/access/heapam.h b/src/include/access/heapam.h index 2f9a2b069cd..5783dbebff0 100644 --- a/src/include/access/heapam.h +++ b/src/include/access/heapam.h @@ -369,7 +369,7 @@ extern TM_Result heap_update(Relation relation, HeapTupleData *oldtup, TM_FailureData *tmfd, LockTupleMode *lockmode, Buffer buffer, Page page, BlockNumber block, ItemId lp, Bitmapset *hot_attrs, Bitmapset *sum_attrs, Bitmapset *pk_attrs, Bitmapset *rid_attrs, - Bitmapset *mix_attrs, Buffer *vmbuffer, + const Bitmapset *mix_attrs, Buffer *vmbuffer, bool rep_id_key_required, TU_UpdateIndexes *update_indexes); extern TM_Result heap_lock_tuple(Relation relation, HeapTuple tuple, CommandId cid, LockTupleMode mode, LockWaitPolicy wait_policy, @@ -404,8 +404,8 @@ extern bool heap_tuple_needs_eventual_freeze(HeapTupleHeader tuple); extern void simple_heap_insert(Relation relation, HeapTuple tup); extern void simple_heap_delete(Relation relation, const ItemPointerData *tid); -extern void simple_heap_update(Relation relation, const ItemPointerData *otid, - HeapTuple tup, TU_UpdateIndexes *update_indexes); +extern Bitmapset *simple_heap_update(Relation relation, const ItemPointerData *otid, + HeapTuple tup, TU_UpdateIndexes *update_indexes); extern TransactionId heap_index_delete_tuples(Relation rel, TM_IndexDeleteOp *delstate); diff --git a/src/include/access/nbtree.h b/src/include/access/nbtree.h index 16be5c7a9c1..42bd329eaad 100644 --- a/src/include/access/nbtree.h +++ b/src/include/access/nbtree.h @@ -1210,6 +1210,10 @@ extern int btgettreeheight(Relation rel); extern CompareType bttranslatestrategy(StrategyNumber strategy, Oid opfamily); extern StrategyNumber bttranslatecmptype(CompareType cmptype, Oid opfamily); +extern bool btcomparedatums(Relation index, int attnum, + Datum old_datum, bool old_isnull, + Datum new_datum, bool new_isnull); + /* * prototypes for internal functions in nbtree.c diff --git a/src/include/access/tableam.h b/src/include/access/tableam.h index 8a5931a3118..2b9206ff24a 100644 --- a/src/include/access/tableam.h +++ b/src/include/access/tableam.h @@ -549,7 +549,7 @@ typedef struct TableAmRoutine bool wait, TM_FailureData *tmfd, LockTupleMode *lockmode, - Bitmapset *updated_cols, + const Bitmapset *updated_cols, TU_UpdateIndexes *update_indexes); /* see table_tuple_lock() for reference about parameters */ @@ -1503,12 +1503,12 @@ static inline TM_Result table_tuple_update(Relation rel, ItemPointer otid, TupleTableSlot *slot, CommandId cid, Snapshot snapshot, Snapshot crosscheck, bool wait, TM_FailureData *tmfd, LockTupleMode *lockmode, - Bitmapset *updated_cols, TU_UpdateIndexes *update_indexes) + const Bitmapset *mix_cols, TU_UpdateIndexes *update_indexes) { return rel->rd_tableam->tuple_update(rel, otid, slot, cid, snapshot, crosscheck, wait, tmfd, lockmode, - updated_cols, update_indexes); + mix_cols, update_indexes); } /* @@ -2011,7 +2011,7 @@ extern void simple_table_tuple_delete(Relation rel, ItemPointer tid, Snapshot snapshot); extern void simple_table_tuple_update(Relation rel, ItemPointer otid, TupleTableSlot *slot, Snapshot snapshot, - Bitmapset *modified_indexe_attrs, + const Bitmapset *mix_attrs, TU_UpdateIndexes *update_indexes); diff --git a/src/include/catalog/index.h b/src/include/catalog/index.h index dda95e54903..8d364f8b30f 100644 --- a/src/include/catalog/index.h +++ b/src/include/catalog/index.h @@ -132,6 +132,7 @@ extern bool CompareIndexInfo(const IndexInfo *info1, const IndexInfo *info2, const AttrMap *attmap); extern void BuildSpeculativeIndexInfo(Relation index, IndexInfo *ii); +extern void BuildUpdateIndexInfo(ResultRelInfo *resultRelInfo); extern void FormIndexDatum(IndexInfo *indexInfo, TupleTableSlot *slot, diff --git a/src/include/executor/executor.h b/src/include/executor/executor.h index 993dc0e6ced..a19585ba065 100644 --- a/src/include/executor/executor.h +++ b/src/include/executor/executor.h @@ -739,6 +739,11 @@ extern Bitmapset *ExecGetAllUpdatedCols(ResultRelInfo *relinfo, EState *estate); */ extern void ExecOpenIndices(ResultRelInfo *resultRelInfo, bool speculative); extern void ExecCloseIndices(ResultRelInfo *resultRelInfo); +extern Bitmapset *ExecWhichIndexesRequireUpdates(ResultRelInfo *relinfo, + Bitmapset *mix_attrs, + EState *estate, + TupleTableSlot *old_tts, + TupleTableSlot *new_tts); extern List *ExecInsertIndexTuples(ResultRelInfo *resultRelInfo, TupleTableSlot *slot, EState *estate, bool update, @@ -800,9 +805,10 @@ extern ResultRelInfo *ExecLookupResultRelByOid(ModifyTableState *node, Oid resultoid, bool missing_ok, bool update_cache); -extern Bitmapset *ExecCheckIndexedAttrsForChanges(ResultRelInfo *resultRelInfo, - TupleTableSlot *tts_old, - TupleTableSlot *tts_new); +extern Bitmapset *ExecCheckIndexedAttrsForChanges(ResultRelInfo *relinfo, + EState *estate, + TupleTableSlot *old_tts, + TupleTableSlot *new_tts); extern bool tts_attr_equal(Oid typid, Oid collation, bool typbyval, int16 typlen, Datum value1, Datum value2); diff --git a/src/include/nodes/execnodes.h b/src/include/nodes/execnodes.h index 898368fb8cb..d8e88817206 100644 --- a/src/include/nodes/execnodes.h +++ b/src/include/nodes/execnodes.h @@ -174,15 +174,29 @@ typedef struct IndexInfo */ AttrNumber ii_IndexAttrNumbers[INDEX_MAX_KEYS]; + /* + * All key, expression, sumarizing, and partition attributes referenced by + * this index + */ + Bitmapset *ii_IndexedAttrs; + /* expr trees for expression entries, or NIL if none */ List *ii_Expressions; /* list of Expr */ /* exec state for expressions, or NIL if none */ List *ii_ExpressionsState; /* list of ExprState */ + /* attributes exclusively referenced by expression indexes */ + Bitmapset *ii_ExpressionsAttrs; /* partial-index predicate, or NIL if none */ List *ii_Predicate; /* list of Expr */ /* exec state for expressions, or NIL if none */ ExprState *ii_PredicateState; + /* attributes referenced by the predicate */ + Bitmapset *ii_PredicateAttrs; + /* partial index predicate determined yet? */ + bool ii_CheckedPredicate; + /* amupdate hint used to avoid rechecking predicate */ + bool ii_PredicateSatisfied; /* Per-column exclusion operators, or NULL if none */ Oid *ii_ExclusionOps; /* array with one entry per column */ @@ -494,6 +508,11 @@ typedef struct ResultRelInfo Bitmapset *ri_extraUpdatedCols; /* true if the above has been computed */ bool ri_extraUpdatedCols_valid; + + /* + * For UPDATE a Bitmapset of the attributes that are both indexed and have + * changed in value. + */ Bitmapset *ri_ChangedIndexedCols; /* Projection to generate new tuple in an INSERT/UPDATE */ diff --git a/src/test/isolation/expected/insert-conflict-specconflict.out b/src/test/isolation/expected/insert-conflict-specconflict.out index e34a821c403..54b3981918c 100644 --- a/src/test/isolation/expected/insert-conflict-specconflict.out +++ b/src/test/isolation/expected/insert-conflict-specconflict.out @@ -80,6 +80,10 @@ pg_advisory_unlock t (1 row) +s1: NOTICE: blurt_and_lock_123() called for k1 in session 1 +s1: NOTICE: acquiring advisory lock on 2 +s1: NOTICE: blurt_and_lock_123() called for k1 in session 1 +s1: NOTICE: acquiring advisory lock on 2 s1: NOTICE: blurt_and_lock_123() called for k1 in session 1 s1: NOTICE: acquiring advisory lock on 2 s1: NOTICE: blurt_and_lock_123() called for k1 in session 1 @@ -172,6 +176,10 @@ pg_advisory_unlock t (1 row) +s2: NOTICE: blurt_and_lock_123() called for k1 in session 2 +s2: NOTICE: acquiring advisory lock on 2 +s2: NOTICE: blurt_and_lock_123() called for k1 in session 2 +s2: NOTICE: acquiring advisory lock on 2 s2: NOTICE: blurt_and_lock_123() called for k1 in session 2 s2: NOTICE: acquiring advisory lock on 2 s2: NOTICE: blurt_and_lock_123() called for k1 in session 2 @@ -369,6 +377,10 @@ key|data step s1_commit: COMMIT; s2: NOTICE: blurt_and_lock_123() called for k1 in session 2 s2: NOTICE: acquiring advisory lock on 2 +s2: NOTICE: blurt_and_lock_123() called for k1 in session 2 +s2: NOTICE: acquiring advisory lock on 2 +s2: NOTICE: blurt_and_lock_123() called for k1 in session 2 +s2: NOTICE: acquiring advisory lock on 2 step s2_upsert: <... completed> step controller_show: SELECT * FROM upserttest; key|data @@ -530,6 +542,14 @@ isolation/insert-conflict-specconflict/s2|transactionid|ExclusiveLock|t step s2_commit: COMMIT; s1: NOTICE: blurt_and_lock_123() called for k1 in session 1 s1: NOTICE: acquiring advisory lock on 2 +s1: NOTICE: blurt_and_lock_123() called for k1 in session 1 +s1: NOTICE: acquiring advisory lock on 2 +s1: NOTICE: blurt_and_lock_123() called for k1 in session 1 +s1: NOTICE: acquiring advisory lock on 2 +s1: NOTICE: blurt_and_lock_4() called for k1 in session 1 +s1: NOTICE: acquiring advisory lock on 4 +s1: NOTICE: blurt_and_lock_4() called for k1 in session 1 +s1: NOTICE: acquiring advisory lock on 4 step s1_upsert: <... completed> step s1_noop: step controller_show: SELECT * FROM upserttest; diff --git a/src/test/regress/expected/heap_hot_updates.out b/src/test/regress/expected/heap_hot_updates.out new file mode 100644 index 00000000000..f6bd8b18af8 --- /dev/null +++ b/src/test/regress/expected/heap_hot_updates.out @@ -0,0 +1,1922 @@ +-- ================================================================ +-- Test Suite for Heap-only (HOT) Updates +-- ================================================================ +-- Setup: Create function to measure HOT updates +CREATE OR REPLACE FUNCTION check_hot_updates( + expected INT, + p_table_name TEXT DEFAULT 't', + p_schema_name TEXT DEFAULT current_schema() +) +RETURNS TABLE ( + table_name TEXT, + total_updates BIGINT, + hot_updates BIGINT, + hot_update_percentage NUMERIC, + matches_expected BOOLEAN +) +LANGUAGE plpgsql +AS $$ +DECLARE + v_relid oid; + v_qualified_name TEXT; + v_hot_updates BIGINT; + v_updates BIGINT; + v_xact_hot_updates BIGINT; + v_xact_updates BIGINT; +BEGIN + -- Force statistics update + PERFORM pg_stat_force_next_flush(); + + -- Get table OID + v_qualified_name := quote_ident(p_schema_name) || '.' || quote_ident(p_table_name); + v_relid := v_qualified_name::regclass; + + IF v_relid IS NULL THEN + RAISE EXCEPTION 'Table %.% not found', p_schema_name, p_table_name; + END IF; + + -- Get cumulative + transaction stats + v_hot_updates := COALESCE(pg_stat_get_tuples_hot_updated(v_relid), 0); + v_updates := COALESCE(pg_stat_get_tuples_updated(v_relid), 0); + v_xact_hot_updates := COALESCE(pg_stat_get_xact_tuples_hot_updated(v_relid), 0); + v_xact_updates := COALESCE(pg_stat_get_xact_tuples_updated(v_relid), 0); + + v_hot_updates := v_hot_updates + v_xact_hot_updates; + v_updates := v_updates + v_xact_updates; + + RETURN QUERY + SELECT + p_table_name::TEXT, + v_updates::BIGINT, + v_hot_updates::BIGINT, + CASE WHEN v_updates > 0 + THEN ROUND((v_hot_updates::numeric / v_updates::numeric * 100)::numeric, 2) + ELSE 0 + END, + (v_hot_updates = expected)::BOOLEAN; +END; +$$; +CREATE COLLATION case_insensitive ( + provider = libc, + locale = 'C' +); +-- ================================================================ +-- Basic JSONB Expression Index +-- ================================================================ +CREATE TABLE t(id INT PRIMARY KEY, docs JSONB) + WITH (autovacuum_enabled = off, fillfactor = 70); +CREATE INDEX t_docs_name_idx ON t((docs->'name')); +INSERT INTO t VALUES (1, '{"name": "alice", "age": 30}'); +-- Update non-indexed JSONB field - should be HOT +UPDATE t SET docs = '{"name": "alice", "age": 31}' WHERE id = 1; +SELECT * FROM check_hot_updates(1); + table_name | total_updates | hot_updates | hot_update_percentage | matches_expected +------------+---------------+-------------+-----------------------+------------------ + t | 1 | 1 | 100.00 | t +(1 row) + +-- Update indexed JSONB field - should NOT be HOT +UPDATE t SET docs = '{"name": "bob", "age": 31}' WHERE id = 1; +SELECT * FROM check_hot_updates(1); + table_name | total_updates | hot_updates | hot_update_percentage | matches_expected +------------+---------------+-------------+-----------------------+------------------ + t | 2 | 1 | 50.00 | t +(1 row) + +-- Update non-indexed field again - should be HOT +UPDATE t SET docs = '{"name": "bob", "age": 32}' WHERE id = 1; +SELECT * FROM check_hot_updates(2); + table_name | total_updates | hot_updates | hot_update_percentage | matches_expected +------------+---------------+-------------+-----------------------+------------------ + t | 3 | 2 | 66.67 | t +(1 row) + +DROP TABLE t; +-- ================================================================ +-- JSONB Expression Index an some including columns +-- ================================================================ +CREATE TABLE t(id INT PRIMARY KEY, docs JSONB, status TEXT) + WITH (autovacuum_enabled = off, fillfactor = 70); +CREATE INDEX t_docs_name_idx ON t((docs->'name')); +INSERT INTO t VALUES (1, '{"name": "alice", "age": 30}', 'ok'); +-- Update non-indexed JSONB field - should be HOT +UPDATE t SET docs = '{"name": "alice", "age": 31}' WHERE id = 1; +SELECT * FROM check_hot_updates(1); + table_name | total_updates | hot_updates | hot_update_percentage | matches_expected +------------+---------------+-------------+-----------------------+------------------ + t | 1 | 1 | 100.00 | t +(1 row) + +-- Update non-indexed JSONB field - should be HOT +UPDATE t SET status = 'not ok' WHERE id = 1; +SELECT * FROM check_hot_updates(2); + table_name | total_updates | hot_updates | hot_update_percentage | matches_expected +------------+---------------+-------------+-----------------------+------------------ + t | 2 | 2 | 100.00 | t +(1 row) + +DROP TABLE t; +-- ================================================================ +-- Partial Index with Predicate Transitions +-- ================================================================ +CREATE TABLE t(id INT, value INT) + WITH (autovacuum_enabled = off, fillfactor = 70); +CREATE INDEX t_value_idx ON t(value) WHERE value > 10; +INSERT INTO t VALUES (1, 5); +-- Both outside predicate - should be HOT +UPDATE t SET value = 8 WHERE id = 1; +SELECT * FROM check_hot_updates(1); + table_name | total_updates | hot_updates | hot_update_percentage | matches_expected +------------+---------------+-------------+-----------------------+------------------ + t | 1 | 1 | 100.00 | t +(1 row) + +-- Transition into predicate - should NOT be HOT +UPDATE t SET value = 15 WHERE id = 1; +SELECT * FROM check_hot_updates(1); + table_name | total_updates | hot_updates | hot_update_percentage | matches_expected +------------+---------------+-------------+-----------------------+------------------ + t | 2 | 1 | 50.00 | t +(1 row) + +-- Both inside predicate, value changes - should NOT be HOT +UPDATE t SET value = 20 WHERE id = 1; +SELECT * FROM check_hot_updates(1); + table_name | total_updates | hot_updates | hot_update_percentage | matches_expected +------------+---------------+-------------+-----------------------+------------------ + t | 3 | 1 | 33.33 | t +(1 row) + +-- Transition out of predicate - should NOT be HOT +UPDATE t SET value = 5 WHERE id = 1; +SELECT * FROM check_hot_updates(1); + table_name | total_updates | hot_updates | hot_update_percentage | matches_expected +------------+---------------+-------------+-----------------------+------------------ + t | 4 | 1 | 25.00 | t +(1 row) + +-- Both outside predicate again - should be HOT +UPDATE t SET value = 3 WHERE id = 1; +SELECT * FROM check_hot_updates(2); + table_name | total_updates | hot_updates | hot_update_percentage | matches_expected +------------+---------------+-------------+-----------------------+------------------ + t | 5 | 2 | 40.00 | t +(1 row) + +DROP TABLE t; +-- ================================================================ +-- Expression Index with Partial Predicate +-- ================================================================ +CREATE TABLE t(docs JSONB) + WITH (autovacuum_enabled = off, fillfactor = 70); +CREATE INDEX t_idx ON t((docs->'status')) + WHERE (docs->'priority')::int > 5; +INSERT INTO t VALUES ('{"status": "pending", "priority": 3}'); +-- Both outside predicate, status unchanged - should be HOT +UPDATE t SET docs = '{"status": "pending", "priority": 4}'; +SELECT * FROM check_hot_updates(1); + table_name | total_updates | hot_updates | hot_update_percentage | matches_expected +------------+---------------+-------------+-----------------------+------------------ + t | 1 | 1 | 100.00 | t +(1 row) + +-- Transition into predicate - should NOT be HOT +UPDATE t SET docs = '{"status": "pending", "priority": 10}'; +SELECT * FROM check_hot_updates(1); + table_name | total_updates | hot_updates | hot_update_percentage | matches_expected +------------+---------------+-------------+-----------------------+------------------ + t | 2 | 1 | 50.00 | t +(1 row) + +-- Inside predicate, status changes - should NOT be HOT +UPDATE t SET docs = '{"status": "active", "priority": 10}'; +SELECT * FROM check_hot_updates(1); + table_name | total_updates | hot_updates | hot_update_percentage | matches_expected +------------+---------------+-------------+-----------------------+------------------ + t | 3 | 1 | 33.33 | t +(1 row) + +-- Inside predicate, status unchanged - should be HOT +UPDATE t SET docs = '{"status": "active", "priority": 8}'; +SELECT * FROM check_hot_updates(2); + table_name | total_updates | hot_updates | hot_update_percentage | matches_expected +------------+---------------+-------------+-----------------------+------------------ + t | 4 | 2 | 50.00 | t +(1 row) + +DROP TABLE t; +-- ================================================================ +-- GIN Index on JSONB +-- ================================================================ +CREATE TABLE t(id INT, data JSONB) + WITH (autovacuum_enabled = off, fillfactor = 70); +CREATE INDEX t_gin_idx ON t USING gin(data); +INSERT INTO t VALUES (1, '{"tags": ["postgres", "database"]}'); +-- Change tags - GIN keys changed, should NOT be HOT +UPDATE t SET data = '{"tags": ["postgres", "sql"]}' WHERE id = 1; +SELECT * FROM check_hot_updates(0); + table_name | total_updates | hot_updates | hot_update_percentage | matches_expected +------------+---------------+-------------+-----------------------+------------------ + t | 1 | 0 | 0.00 | t +(1 row) + +-- Change tags again - GIN keys changed, should NOT be HOT +UPDATE t SET data = '{"tags": ["mysql", "sql"]}' WHERE id = 1; +SELECT * FROM check_hot_updates(0); + table_name | total_updates | hot_updates | hot_update_percentage | matches_expected +------------+---------------+-------------+-----------------------+------------------ + t | 2 | 0 | 0.00 | t +(1 row) + +-- Add field without changing existing keys - GIN keys changed (added "note"), NOT HOT +UPDATE t SET data = '{"tags": ["mysql", "sql"], "note": "test"}' WHERE id = 1; +SELECT * FROM check_hot_updates(0); + table_name | total_updates | hot_updates | hot_update_percentage | matches_expected +------------+---------------+-------------+-----------------------+------------------ + t | 3 | 0 | 0.00 | t +(1 row) + +DROP TABLE t; +-- ================================================================ +-- GIN Index with Unchanged Keys +-- ================================================================ +CREATE TABLE t(id INT, data JSONB) + WITH (autovacuum_enabled = off, fillfactor = 70); +-- Create GIN index on specific path +CREATE INDEX t_gin_idx ON t USING gin((data->'tags')); +INSERT INTO t VALUES (1, '{"tags": ["postgres", "sql"], "status": "active"}'); +-- Change non-indexed field - GIN keys on 'tags' unchanged, should be HOT +UPDATE t SET data = '{"tags": ["postgres", "sql"], "status": "inactive"}' WHERE id = 1; +SELECT * FROM check_hot_updates(1); + table_name | total_updates | hot_updates | hot_update_percentage | matches_expected +------------+---------------+-------------+-----------------------+------------------ + t | 1 | 1 | 100.00 | t +(1 row) + +-- Change indexed tags - GIN keys changed, should NOT be HOT +UPDATE t SET data = '{"tags": ["mysql", "sql"], "status": "inactive"}' WHERE id = 1; +SELECT * FROM check_hot_updates(1); + table_name | total_updates | hot_updates | hot_update_percentage | matches_expected +------------+---------------+-------------+-----------------------+------------------ + t | 2 | 1 | 50.00 | t +(1 row) + +DROP TABLE t; +-- ================================================================ +-- GIN with jsonb_path_ops +-- ================================================================ +CREATE TABLE t(id INT, data JSONB) + WITH (autovacuum_enabled = off, fillfactor = 70); +CREATE INDEX t_gin_idx ON t USING gin(data jsonb_path_ops); +INSERT INTO t VALUES (1, '{"user": {"name": "alice"}, "tags": ["a", "b"]}'); +-- Change value at different path - keys changed, NOT HOT +UPDATE t SET data = '{"user": {"name": "bob"}, "tags": ["a", "b"]}' WHERE id = 1; +SELECT * FROM check_hot_updates(0); + table_name | total_updates | hot_updates | hot_update_percentage | matches_expected +------------+---------------+-------------+-----------------------+------------------ + t | 1 | 0 | 0.00 | t +(1 row) + +DROP TABLE t; +-- ================================================================ +-- Multi-Column Expression Index +-- ================================================================ +CREATE TABLE t(id INT, a INT, b INT) + WITH (autovacuum_enabled = off, fillfactor = 70); +CREATE INDEX t_idx ON t(id, abs(a), abs(b)); +INSERT INTO t VALUES (1, -5, -10); +-- Change sign but not abs value - should be HOT +UPDATE t SET a = 5 WHERE id = 1; +SELECT * FROM check_hot_updates(1); + table_name | total_updates | hot_updates | hot_update_percentage | matches_expected +------------+---------------+-------------+-----------------------+------------------ + t | 1 | 1 | 100.00 | t +(1 row) + +-- Change abs value - should NOT be HOT +UPDATE t SET b = -15 WHERE id = 1; +SELECT * FROM check_hot_updates(1); + table_name | total_updates | hot_updates | hot_update_percentage | matches_expected +------------+---------------+-------------+-----------------------+------------------ + t | 2 | 1 | 50.00 | t +(1 row) + +-- Change id - should NOT be HOT +UPDATE t SET id = 2 WHERE id = 1; +SELECT * FROM check_hot_updates(1); + table_name | total_updates | hot_updates | hot_update_percentage | matches_expected +------------+---------------+-------------+-----------------------+------------------ + t | 3 | 1 | 33.33 | t +(1 row) + +DROP TABLE t; +-- ================================================================ +-- Mixed Index Types (BRIN + Expression) +-- ================================================================ +CREATE TABLE t(id INT, value INT, data JSONB) + WITH (autovacuum_enabled = off, fillfactor = 70); +CREATE INDEX t_brin_idx ON t USING brin(value); +CREATE INDEX t_expr_idx ON t((data->'status')); +INSERT INTO t VALUES (1, 100, '{"status": "active"}'); +-- Update only BRIN column - should be HOT +UPDATE t SET value = 200 WHERE id = 1; +SELECT * FROM check_hot_updates(1); + table_name | total_updates | hot_updates | hot_update_percentage | matches_expected +------------+---------------+-------------+-----------------------+------------------ + t | 1 | 1 | 100.00 | t +(1 row) + +-- Update only expression column - should NOT be HOT +UPDATE t SET data = '{"status": "inactive"}' WHERE id = 1; +SELECT * FROM check_hot_updates(1); + table_name | total_updates | hot_updates | hot_update_percentage | matches_expected +------------+---------------+-------------+-----------------------+------------------ + t | 2 | 1 | 50.00 | t +(1 row) + +-- Update both - should NOT be HOT +UPDATE t SET value = 300, data = '{"status": "pending"}' WHERE id = 1; +SELECT * FROM check_hot_updates(1); + table_name | total_updates | hot_updates | hot_update_percentage | matches_expected +------------+---------------+-------------+-----------------------+------------------ + t | 3 | 1 | 33.33 | t +(1 row) + +DROP TABLE t; +-- ================================================================ +-- Expression with COLLATION and BTREE (nbtree) index +-- ================================================================ +CREATE TABLE t( + id INT PRIMARY KEY, + name TEXT COLLATE case_insensitive +) WITH (autovacuum_enabled = off, fillfactor = 70); +CREATE INDEX t_lower_idx ON t USING BTREE (name COLLATE case_insensitive); +INSERT INTO t VALUES (1, 'ALICE'); +-- Change case but not value - should NOT be HOT in BTREE +UPDATE t SET name = 'Alice' WHERE id = 1; +SELECT * FROM check_hot_updates(0); + table_name | total_updates | hot_updates | hot_update_percentage | matches_expected +------------+---------------+-------------+-----------------------+------------------ + t | 1 | 0 | 0.00 | t +(1 row) + +-- Change to new value - should NOT be HOT +UPDATE t SET name = 'BOB' WHERE id = 1; +SELECT * FROM check_hot_updates(0); + table_name | total_updates | hot_updates | hot_update_percentage | matches_expected +------------+---------------+-------------+-----------------------+------------------ + t | 2 | 0 | 0.00 | t +(1 row) + +DROP TABLE t; +-- ================================================================ +-- Array Expression Index +-- ================================================================ +CREATE TABLE t(id INT, tags TEXT[]) + WITH (autovacuum_enabled = off, fillfactor = 70); +CREATE INDEX t_array_len_idx ON t(array_length(tags, 1)); +INSERT INTO t VALUES (1, ARRAY['a', 'b', 'c']); +-- Same length, different elements - should be HOT +UPDATE t SET tags = ARRAY['d', 'e', 'f'] WHERE id = 1; +SELECT * FROM check_hot_updates(1); + table_name | total_updates | hot_updates | hot_update_percentage | matches_expected +------------+---------------+-------------+-----------------------+------------------ + t | 1 | 1 | 100.00 | t +(1 row) + +-- Different length - should NOT be HOT +UPDATE t SET tags = ARRAY['d', 'e'] WHERE id = 1; +SELECT * FROM check_hot_updates(1); + table_name | total_updates | hot_updates | hot_update_percentage | matches_expected +------------+---------------+-------------+-----------------------+------------------ + t | 2 | 1 | 50.00 | t +(1 row) + +DROP TABLE t; +-- ================================================================ +-- Nested JSONB Expression and JSONB equality '->' (not '->>') +-- ================================================================ +CREATE TABLE t(data JSONB) + WITH (autovacuum_enabled = off, fillfactor = 70); +CREATE INDEX t_nested_idx ON t((data->'user'->'name')); +INSERT INTO t VALUES ('{"user": {"name": "alice", "age": 30}}'); +-- Change nested non-indexed field - should be HOT +UPDATE t SET data = '{"user": {"name": "alice", "age": 31}}'; +SELECT * FROM check_hot_updates(1); + table_name | total_updates | hot_updates | hot_update_percentage | matches_expected +------------+---------------+-------------+-----------------------+------------------ + t | 1 | 1 | 100.00 | t +(1 row) + +-- Change nested indexed field - should NOT be HOT +UPDATE t SET data = '{"user": {"name": "bob", "age": 31}}'; +SELECT * FROM check_hot_updates(1); + table_name | total_updates | hot_updates | hot_update_percentage | matches_expected +------------+---------------+-------------+-----------------------+------------------ + t | 2 | 1 | 50.00 | t +(1 row) + +DROP TABLE t; +-- ================================================================ +-- Complex Predicate on Multiple JSONB Fields +-- ================================================================ +CREATE TABLE t(data JSONB) + WITH (autovacuum_enabled = off, fillfactor = 70); +CREATE INDEX t_idx ON t((data->'status')) + WHERE (data->'priority')::int > 5 + AND (data->'active')::boolean = true; +INSERT INTO t VALUES ('{"status": "pending", "priority": 3, "active": true}'); +-- Outside predicate (priority too low) - should be HOT +UPDATE t SET data = '{"status": "done", "priority": 3, "active": true}'; +SELECT * FROM check_hot_updates(1); + table_name | total_updates | hot_updates | hot_update_percentage | matches_expected +------------+---------------+-------------+-----------------------+------------------ + t | 1 | 1 | 100.00 | t +(1 row) + +-- Transition into predicate - should NOT be HOT +UPDATE t SET data = '{"status": "done", "priority": 10, "active": true}'; +SELECT * FROM check_hot_updates(1); + table_name | total_updates | hot_updates | hot_update_percentage | matches_expected +------------+---------------+-------------+-----------------------+------------------ + t | 2 | 1 | 50.00 | t +(1 row) + +-- Inside predicate, change to outside (active = false) - should NOT be HOT +UPDATE t SET data = '{"status": "done", "priority": 10, "active": false}'; +SELECT * FROM check_hot_updates(1); + table_name | total_updates | hot_updates | hot_update_percentage | matches_expected +------------+---------------+-------------+-----------------------+------------------ + t | 3 | 1 | 33.33 | t +(1 row) + +DROP TABLE t; +-- ================================================================ +-- GIN Array Index - Order Insensitive Extraction +-- ================================================================ +CREATE TABLE t( + id INT PRIMARY KEY, + data JSONB +) WITH (autovacuum_enabled = off, fillfactor = 70); +-- GIN index on JSONB array (extracts all elements) +CREATE INDEX t_items_gin ON t USING GIN ((data->'items')); +INSERT INTO t VALUES (1, '{"items": [1, 2, 3], "status": "active"}'); +-- Update: Reorder array elements +-- JSONB equality: NOT equal (different arrays) +-- GIN extraction: Same elements extracted (might allow HOT if not careful) +UPDATE t SET data = '{"items": [3, 2, 1], "status": "active"}' WHERE id = 1; +SELECT * FROM check_hot_updates(1); + table_name | total_updates | hot_updates | hot_update_percentage | matches_expected +------------+---------------+-------------+-----------------------+------------------ + t | 1 | 1 | 100.00 | t +(1 row) + +-- Update: Add/remove element +UPDATE t SET data = '{"items": [1, 2, 3, 4], "status": "active"}' WHERE id = 1; +SELECT * FROM check_hot_updates(1); + table_name | total_updates | hot_updates | hot_update_percentage | matches_expected +------------+---------------+-------------+-----------------------+------------------ + t | 2 | 1 | 50.00 | t +(1 row) + +DROP TABLE t; +-- ================================================================ +-- TOASTed Values in Expression Index +-- ================================================================ +CREATE TABLE t(id INT, large_text TEXT) + WITH (autovacuum_enabled = off, fillfactor = 70); +CREATE INDEX t_substr_idx ON t(substr(large_text, 1, 10)); +INSERT INTO t VALUES (1, repeat('x', 5000) || 'identifier'); +-- Change end of string, prefix unchanged - should be HOT +UPDATE t SET large_text = repeat('x', 5000) || 'different' WHERE id = 1; +SELECT * FROM check_hot_updates(1); + table_name | total_updates | hot_updates | hot_update_percentage | matches_expected +------------+---------------+-------------+-----------------------+------------------ + t | 1 | 1 | 100.00 | t +(1 row) + +-- Change prefix - should NOT be HOT +UPDATE t SET large_text = repeat('y', 5000) || 'different' WHERE id = 1; +SELECT * FROM check_hot_updates(1); + table_name | total_updates | hot_updates | hot_update_percentage | matches_expected +------------+---------------+-------------+-----------------------+------------------ + t | 2 | 1 | 50.00 | t +(1 row) + +DROP TABLE t; +-- ================================================================ +-- TEST: GIN with TOASTed TEXT (tsvector) +-- ================================================================ +CREATE TABLE t(id INT, content TEXT, search_vec tsvector) + WITH (autovacuum_enabled = off, fillfactor = 70); +-- Create trigger to maintain tsvector +CREATE TRIGGER tsvectorupdate_toast + BEFORE INSERT OR UPDATE ON t + FOR EACH ROW EXECUTE FUNCTION + tsvector_update_trigger(search_vec, 'pg_catalog.english', content); +CREATE INDEX t_gin ON t USING gin(search_vec); +-- Insert with large content (will be TOASTed) +INSERT INTO t (id, content) VALUES + (1, repeat('important keyword ', 1000) || repeat('filler text ', 10000)); +-- Verify initial state +SELECT count(*) FROM t WHERE search_vec @@ to_tsquery('important'); + count +------- + 1 +(1 row) + +-- Expected: 1 row +-- IMPORTANT: The BEFORE UPDATE trigger modifies search_vec, so by the time +-- ExecWhichIndexesRequireUpdates() runs, search_vec has already changed. +-- This means the comparison sees old tsvector vs. trigger-modified tsvector, +-- not the natural progression. HOT won't happen because the trigger changed +-- the indexed column. +-- Update: Even though content keywords unchanged, trigger still fires +UPDATE t +SET content = repeat('important keyword ', 1000) || repeat('different filler ', 10000) +WHERE id = 1; +SELECT * FROM check_hot_updates(0); + table_name | total_updates | hot_updates | hot_update_percentage | matches_expected +------------+---------------+-------------+-----------------------+------------------ + t | 1 | 0 | 0.00 | t +(1 row) + +-- Expected: 0 HOT (trigger modifies search_vec, blocking HOT) +-- This is actually correct behavior - the trigger updated an indexed column +-- Update: Change indexed keywords +UPDATE t +SET content = repeat('critical keyword ', 1000) || repeat('different filler ', 10000) +WHERE id = 1; +SELECT * FROM check_hot_updates(0); + table_name | total_updates | hot_updates | hot_update_percentage | matches_expected +------------+---------------+-------------+-----------------------+------------------ + t | 2 | 0 | 0.00 | t +(1 row) + +-- Expected: 0 HOT (index keys changed) +-- Verify query correctness +SELECT count(*) FROM t WHERE search_vec @@ to_tsquery('critical'); + count +------- + 1 +(1 row) + +-- Expected: 1 row +DROP TABLE t CASCADE; +-- ================================================================ +-- TEST: GIN with TOASTed JSONB +-- ================================================================ +CREATE TABLE t(id INT, data JSONB) + WITH (autovacuum_enabled = off, fillfactor = 70); +CREATE INDEX t_gin ON t USING gin((data->'tags')); +-- Insert with TOASTed JSONB +INSERT INTO t (id, data) VALUES + (1, jsonb_build_object( + 'tags', '["postgres", "database"]'::jsonb, + 'large_field', repeat('x', 10000) + )); +-- Update: Change large_field, tags unchanged - should be HOT +UPDATE t +SET data = jsonb_build_object( + 'tags', '["postgres", "database"]'::jsonb, + 'large_field', repeat('y', 10000) +) +WHERE id = 1; +SELECT * FROM check_hot_updates(1); + table_name | total_updates | hot_updates | hot_update_percentage | matches_expected +------------+---------------+-------------+-----------------------+------------------ + t | 1 | 1 | 100.00 | t +(1 row) + +-- Expected: 1 HOT update +-- Update: Change tags - should NOT be HOT +UPDATE t +SET data = jsonb_build_object( + 'tags', '["postgres", "sql"]'::jsonb, + 'large_field', repeat('y', 10000) +) +WHERE id = 1; +SELECT * FROM check_hot_updates(1); + table_name | total_updates | hot_updates | hot_update_percentage | matches_expected +------------+---------------+-------------+-----------------------+------------------ + t | 2 | 1 | 50.00 | t +(1 row) + +-- Expected: Still 1 HOT +-- Verify correctness +SELECT count(*) FROM t WHERE data->'tags' @> '["database"]'::jsonb; + count +------- + 0 +(1 row) + +-- Expected: 0 rows +SELECT count(*) FROM t WHERE data->'tags' @> '["sql"]'::jsonb; + count +------- + 1 +(1 row) + +-- Expected: 1 row +DROP TABLE t CASCADE; +-- ================================================================ +-- TEST: GIN with Array of Large Strings +-- ================================================================ +CREATE TABLE t(id INT, tags TEXT[]) + WITH (autovacuum_enabled = off, fillfactor = 70); +CREATE INDEX t_gin ON t USING gin(tags); +-- Insert with large array elements (might be TOASTed) +INSERT INTO t (id, tags) VALUES + (1, ARRAY[repeat('tag1', 1000), repeat('tag2', 1000)]); +-- Update: Change to different large values - NOT HOT +UPDATE t +SET tags = ARRAY[repeat('tag3', 1000), repeat('tag4', 1000)] +WHERE id = 1; +SELECT * FROM check_hot_updates(0); + table_name | total_updates | hot_updates | hot_update_percentage | matches_expected +------------+---------------+-------------+-----------------------+------------------ + t | 1 | 0 | 0.00 | t +(1 row) + +-- Expected: 0 HOT (keys actually changed) +-- Update: Keep same tag values, just reorder - SHOULD BE HOT +-- (GIN is order-insensitive: both [tag3,tag4] and [tag4,tag3] +-- extract to the same sorted key set ['tag3','tag4']) +UPDATE t +SET tags = ARRAY[repeat('tag4', 1000), repeat('tag3', 1000)] +WHERE id = 1; +SELECT * FROM check_hot_updates(1); + table_name | total_updates | hot_updates | hot_update_percentage | matches_expected +------------+---------------+-------------+-----------------------+------------------ + t | 2 | 1 | 50.00 | t +(1 row) + +-- Expected: 1 HOT (GIN keys semantically identical) +-- Update: Remove an element - NOT HOT (keys changed) +UPDATE t +SET tags = ARRAY[repeat('tag4', 1000)] +WHERE id = 1; +SELECT * FROM check_hot_updates(1); + table_name | total_updates | hot_updates | hot_update_percentage | matches_expected +------------+---------------+-------------+-----------------------+------------------ + t | 3 | 1 | 33.33 | t +(1 row) + +-- Expected: Still 1 HOT (not this one) +DROP TABLE t CASCADE; +-- ================================================================ +-- BRIN Index with Partial Predicate +-- ================================================================ +CREATE TABLE t( + id INT PRIMARY KEY, + value INT, + description TEXT +) WITH (autovacuum_enabled = off, fillfactor = 70); +CREATE INDEX t_brin_partial_idx ON t USING brin(value) WHERE value > 100; +INSERT INTO t VALUES (1, 50, 'below range'); +-- Test 1: Outside predicate +UPDATE t SET description = 'updated' WHERE id = 1; +SELECT * FROM check_hot_updates(1); + table_name | total_updates | hot_updates | hot_update_percentage | matches_expected +------------+---------------+-------------+-----------------------+------------------ + t | 1 | 1 | 100.00 | t +(1 row) + +-- Validate: Predicate query returns 0 rows +SELECT COUNT(*) as cnt FROM t WHERE value > 100; + cnt +----- + 0 +(1 row) + +-- Test 2: Transition into predicate +UPDATE t SET value = 150 WHERE id = 1; +SELECT * FROM check_hot_updates(2); + table_name | total_updates | hot_updates | hot_update_percentage | matches_expected +------------+---------------+-------------+-----------------------+------------------ + t | 2 | 2 | 100.00 | t +(1 row) + +-- Validate: Predicate query returns 1 row with correct value +SELECT COUNT(*) as cnt, MAX(value) as max_val FROM t WHERE value > 100; + cnt | max_val +-----+--------- + 1 | 150 +(1 row) + +-- Test 3: Inside predicate, value changes +UPDATE t SET value = 160, description = 'updated again' WHERE id = 1; +SELECT * FROM check_hot_updates(3); + table_name | total_updates | hot_updates | hot_update_percentage | matches_expected +------------+---------------+-------------+-----------------------+------------------ + t | 3 | 3 | 100.00 | t +(1 row) + +-- Validate: Updated value (160) is returned +SELECT COUNT(*) as cnt, MAX(value) as max_val FROM t WHERE value > 100; + cnt | max_val +-----+--------- + 1 | 160 +(1 row) + +-- Test 4: Transition out of predicate +UPDATE t SET value = 50 WHERE id = 1; +SELECT * FROM check_hot_updates(4); + table_name | total_updates | hot_updates | hot_update_percentage | matches_expected +------------+---------------+-------------+-----------------------+------------------ + t | 4 | 4 | 100.00 | t +(1 row) + +SELECT COUNT(*) as cnt FROM t WHERE value > 100; + cnt +----- + 0 +(1 row) + +SELECT id, value, description FROM t; + id | value | description +----+-------+--------------- + 1 | 50 | updated again +(1 row) + +DROP TABLE t CASCADE; +-- ================================================================ +-- HASH Index (Simple Column) +-- ================================================================ +CREATE TABLE t(id INT, code VARCHAR(20), description TEXT) + WITH (autovacuum_enabled = off, fillfactor = 70); +CREATE INDEX t_hash_idx ON t USING hash(code); +INSERT INTO t VALUES (1, 'CODE001', 'initial'); +-- Update non-indexed column - should be HOT +UPDATE t SET description = 'updated' WHERE id = 1; +SELECT * FROM check_hot_updates(1); + table_name | total_updates | hot_updates | hot_update_percentage | matches_expected +------------+---------------+-------------+-----------------------+------------------ + t | 1 | 1 | 100.00 | t +(1 row) + +-- Update indexed column - HASH index requires update, NOT HOT +UPDATE t SET code = 'CODE002' WHERE id = 1; +SELECT * FROM check_hot_updates(1); + table_name | total_updates | hot_updates | hot_update_percentage | matches_expected +------------+---------------+-------------+-----------------------+------------------ + t | 2 | 1 | 50.00 | t +(1 row) + +-- Update both - NOT HOT +UPDATE t SET code = 'CODE003', description = 'changed' WHERE id = 1; +SELECT * FROM check_hot_updates(1); + table_name | total_updates | hot_updates | hot_update_percentage | matches_expected +------------+---------------+-------------+-----------------------+------------------ + t | 3 | 1 | 33.33 | t +(1 row) + +-- Back to original code - NOT HOT (different hash bucket location) +UPDATE t SET code = 'CODE001' WHERE id = 1; +SELECT * FROM check_hot_updates(1); + table_name | total_updates | hot_updates | hot_update_percentage | matches_expected +------------+---------------+-------------+-----------------------+------------------ + t | 4 | 1 | 25.00 | t +(1 row) + +DROP TABLE t CASCADE; +-- ================================================================ +-- HASH Index on Expression +-- ================================================================ +CREATE TABLE t(id INT, email TEXT, data JSONB) + WITH (autovacuum_enabled = off, fillfactor = 70); +CREATE INDEX t_hash_lower_email_idx ON t USING HASH(lower(email)); +INSERT INTO t VALUES (1, 'Alice@Example.com', '{"status": "new"}'); +-- Update non-indexed field - should be HOT +UPDATE t SET data = '{"status": "active"}' WHERE id = 1; +SELECT * FROM check_hot_updates(1); + table_name | total_updates | hot_updates | hot_update_percentage | matches_expected +------------+---------------+-------------+-----------------------+------------------ + t | 1 | 1 | 100.00 | t +(1 row) + +-- Update email with case change only (same lowercase) - should be HOT +UPDATE t SET email = 'alice@example.com' WHERE id = 1; +SELECT * FROM check_hot_updates(2); + table_name | total_updates | hot_updates | hot_update_percentage | matches_expected +------------+---------------+-------------+-----------------------+------------------ + t | 2 | 2 | 100.00 | t +(1 row) + +-- Update email to different lowercase - NOT HOT +UPDATE t SET email = 'bob@example.com' WHERE id = 1; +SELECT * FROM check_hot_updates(2); + table_name | total_updates | hot_updates | hot_update_percentage | matches_expected +------------+---------------+-------------+-----------------------+------------------ + t | 3 | 2 | 66.67 | t +(1 row) + +DROP TABLE t CASCADE; +-- ================================================================ +-- HASH Index on JSONB Field +-- ================================================================ +CREATE TABLE t(id INT, data JSONB) + WITH (autovacuum_enabled = off, fillfactor = 70); +CREATE INDEX t_hash_category_idx ON t USING hash((data->'category')); +INSERT INTO t VALUES (1, '{"category": "books", "title": "PostgreSQL Guide"}'); +-- Update non-indexed JSONB field - should be HOT +UPDATE t SET data = '{"category": "books", "title": "PostgreSQL Handbook"}' WHERE id = 1; +SELECT * FROM check_hot_updates(1); + table_name | total_updates | hot_updates | hot_update_percentage | matches_expected +------------+---------------+-------------+-----------------------+------------------ + t | 1 | 1 | 100.00 | t +(1 row) + +-- Update indexed JSONB field - NOT HOT +UPDATE t SET data = '{"category": "videos", "title": "PostgreSQL Handbook"}' WHERE id = 1; +SELECT * FROM check_hot_updates(1); + table_name | total_updates | hot_updates | hot_update_percentage | matches_expected +------------+---------------+-------------+-----------------------+------------------ + t | 2 | 1 | 50.00 | t +(1 row) + +-- Update both - NOT HOT +UPDATE t SET data = '{"category": "courses", "title": "PostgreSQL Basics"}' WHERE id = 1; +SELECT * FROM check_hot_updates(1); + table_name | total_updates | hot_updates | hot_update_percentage | matches_expected +------------+---------------+-------------+-----------------------+------------------ + t | 3 | 1 | 33.33 | t +(1 row) + +DROP TABLE t CASCADE; +-- ================================================================ +-- Multiple HASH Indexes +-- ================================================================ +CREATE TABLE t(id INT, category VARCHAR, status VARCHAR, value INT) + WITH (autovacuum_enabled = off, fillfactor = 70); +CREATE INDEX t_hash_category_idx ON t USING hash(category); +CREATE INDEX t_hash_status_idx ON t USING hash(status); +INSERT INTO t VALUES (1, 'electronics', 'active', 100); +-- Update non-indexed column - should be HOT +UPDATE t SET value = 150 WHERE id = 1; +SELECT * FROM check_hot_updates(1); + table_name | total_updates | hot_updates | hot_update_percentage | matches_expected +------------+---------------+-------------+-----------------------+------------------ + t | 1 | 1 | 100.00 | t +(1 row) + +-- Update one indexed column - NOT HOT +UPDATE t SET category = 'books' WHERE id = 1; +SELECT * FROM check_hot_updates(1); + table_name | total_updates | hot_updates | hot_update_percentage | matches_expected +------------+---------------+-------------+-----------------------+------------------ + t | 2 | 1 | 50.00 | t +(1 row) + +-- Update other indexed column - NOT HOT +UPDATE t SET status = 'inactive' WHERE id = 1; +SELECT * FROM check_hot_updates(1); + table_name | total_updates | hot_updates | hot_update_percentage | matches_expected +------------+---------------+-------------+-----------------------+------------------ + t | 3 | 1 | 33.33 | t +(1 row) + +-- Update both indexed columns - NOT HOT +UPDATE t SET category = 'videos', status = 'pending' WHERE id = 1; +SELECT * FROM check_hot_updates(1); + table_name | total_updates | hot_updates | hot_update_percentage | matches_expected +------------+---------------+-------------+-----------------------+------------------ + t | 4 | 1 | 25.00 | t +(1 row) + +DROP TABLE t CASCADE; +-- ================================================================ +-- BRIN vs HASH Comparison +-- ================================================================ +CREATE TABLE t_brin(id INT, value INT, data TEXT) + WITH (autovacuum_enabled = off, fillfactor = 70); +CREATE TABLE t_hash(id INT, value INT, data TEXT) + WITH (autovacuum_enabled = off, fillfactor = 70); +CREATE INDEX t_brin_value_idx ON t_brin USING brin(value); +CREATE INDEX t_hash_value_idx ON t_hash USING hash(value); +INSERT INTO t_brin VALUES (1, 100, 'initial'); +INSERT INTO t_hash VALUES (1, 100, 'initial'); +-- Same update on both - different HOT behavior expected +-- BRIN: might allow HOT (range summary unchanged) +-- HASH: blocks HOT (hash bucket changed) +UPDATE t_brin SET value = 150 WHERE id = 1; +SELECT * FROM check_hot_updates(1, 't_brin'); + table_name | total_updates | hot_updates | hot_update_percentage | matches_expected +------------+---------------+-------------+-----------------------+------------------ + t_brin | 1 | 1 | 100.00 | t +(1 row) + +-- Expected: 1 HOT (BRIN allows it for single row) +UPDATE t_hash SET value = 150 WHERE id = 1; +SELECT * FROM check_hot_updates(0, 't_hash'); + table_name | total_updates | hot_updates | hot_update_percentage | matches_expected +------------+---------------+-------------+-----------------------+------------------ + t_hash | 1 | 0 | 0.00 | t +(1 row) + +-- Expected: 0 HOT (HASH blocks it) +DROP TABLE t_brin CASCADE; +DROP TABLE t_hash CASCADE; +-- ================================================================ +-- HASH Index with NULL Values +-- ================================================================ +CREATE TABLE t(id INT, category VARCHAR, data TEXT) + WITH (autovacuum_enabled = off, fillfactor = 70); +CREATE INDEX t_hash_category_idx ON t USING hash(category); +INSERT INTO t VALUES (1, 'electronics', 'initial'); +-- Update indexed column to NULL - NOT HOT (hash value changed) +UPDATE t SET category = NULL WHERE id = 1; +SELECT * FROM check_hot_updates(0); + table_name | total_updates | hot_updates | hot_update_percentage | matches_expected +------------+---------------+-------------+-----------------------+------------------ + t | 1 | 0 | 0.00 | t +(1 row) + +-- Expected: 0 HOT +-- Update indexed column from NULL to value - NOT HOT +UPDATE t SET category = 'books' WHERE id = 1; +SELECT * FROM check_hot_updates(0); + table_name | total_updates | hot_updates | hot_update_percentage | matches_expected +------------+---------------+-------------+-----------------------+------------------ + t | 2 | 0 | 0.00 | t +(1 row) + +-- Expected: 0 HOT +-- Update non-indexed column - should be HOT +UPDATE t SET data = 'updated' WHERE id = 1; +SELECT * FROM check_hot_updates(1); + table_name | total_updates | hot_updates | hot_update_percentage | matches_expected +------------+---------------+-------------+-----------------------+------------------ + t | 3 | 1 | 33.33 | t +(1 row) + +-- Expected: 1 HOT +DROP TABLE t CASCADE; +-- ================================================================ +-- BRIN on JSONB Field +-- ================================================================ +CREATE TABLE t(id INT, metrics JSONB) + WITH (autovacuum_enabled = off, fillfactor = 70); +-- BRIN doesn't directly support JSONB, but we can test on expression +CREATE INDEX t_brin_count_idx ON t USING brin( + CAST(metrics->>'count' AS INTEGER) +); +INSERT INTO t VALUES (1, '{"count": "100", "timestamp": "2024-01-01"}'); +-- Update non-indexed JSONB field - should be HOT +UPDATE t SET metrics = '{"count": "100", "timestamp": "2024-01-02"}' WHERE id = 1; +SELECT * FROM check_hot_updates(1); + table_name | total_updates | hot_updates | hot_update_percentage | matches_expected +------------+---------------+-------------+-----------------------+------------------ + t | 1 | 1 | 100.00 | t +(1 row) + +-- Expected: 1 HOT +-- Update indexed field - BRIN allows HOT for single row +UPDATE t SET metrics = '{"count": "150", "timestamp": "2024-01-02"}' WHERE id = 1; +SELECT * FROM check_hot_updates(2); + table_name | total_updates | hot_updates | hot_update_percentage | matches_expected +------------+---------------+-------------+-----------------------+------------------ + t | 2 | 2 | 100.00 | t +(1 row) + +-- Expected: 2 HOT (BRIN permits single-row updates) +DROP TABLE t CASCADE; +-- ================================================================ +-- Mixed BRIN + HASH on Same Table +-- ================================================================ +CREATE TABLE t(id INT, category VARCHAR, timestamp TIMESTAMP, price NUMERIC, data TEXT) + WITH (autovacuum_enabled = off, fillfactor = 70); +CREATE INDEX t_brin_timestamp_idx ON t USING brin(timestamp); +CREATE INDEX t_hash_category_idx ON t USING hash(category); +INSERT INTO t VALUES (1, 'books', '2024-01-01 10:00:00', 29.99, 'initial'); +-- Update non-indexed column - should be HOT +UPDATE t SET data = 'updated' WHERE id = 1; +SELECT * FROM check_hot_updates(1); + table_name | total_updates | hot_updates | hot_update_percentage | matches_expected +------------+---------------+-------------+-----------------------+------------------ + t | 1 | 1 | 100.00 | t +(1 row) + +-- Expected: 1 HOT +-- Update BRIN indexed column - allows HOT +UPDATE t SET timestamp = '2024-01-02 10:00:00' WHERE id = 1; +SELECT * FROM check_hot_updates(2); + table_name | total_updates | hot_updates | hot_update_percentage | matches_expected +------------+---------------+-------------+-----------------------+------------------ + t | 2 | 2 | 100.00 | t +(1 row) + +-- Expected: 2 HOT +-- Update HASH indexed column - blocks HOT +UPDATE t SET category = 'videos' WHERE id = 1; +SELECT * FROM check_hot_updates(2); + table_name | total_updates | hot_updates | hot_update_percentage | matches_expected +------------+---------------+-------------+-----------------------+------------------ + t | 3 | 2 | 66.67 | t +(1 row) + +-- Expected: 2 HOT (HASH blocks it) +-- Update price (non-indexed) - should be HOT +UPDATE t SET price = 39.99 WHERE id = 1; +SELECT * FROM check_hot_updates(3); + table_name | total_updates | hot_updates | hot_update_percentage | matches_expected +------------+---------------+-------------+-----------------------+------------------ + t | 4 | 3 | 75.00 | t +(1 row) + +-- Expected: 3 HOT +DROP TABLE t CASCADE; +-- ================================================================ +-- Index both on a field in a JSONB document, and the document +-- ================================================================ +CREATE TABLE t(id INT PRIMARY KEY, docs JSONB) WITH (autovacuum_enabled = off, fillfactor = 70); +CREATE INDEX t_docs_idx ON t((docs->'name')); +CREATE INDEX t_docs_col_idx ON t(docs); +INSERT INTO t VALUES (1, '{"name": "john", "data": "some data"}'); +-- Update impacts index on whole docment attribute, can't go HOT +UPDATE t SET docs='{"name": "john", "data": "some other data"}' WHERE id=1; +SELECT * FROM check_hot_updates(0); + table_name | total_updates | hot_updates | hot_update_percentage | matches_expected +------------+---------------+-------------+-----------------------+------------------ + t | 1 | 0 | 0.00 | t +(1 row) + +DROP TABLE t CASCADE; +-- ================================================================ +-- Two indexes on a JSONB document, one partial +-- ================================================================ +CREATE TABLE t (docs JSONB) WITH (autovacuum_enabled = off, fillfactor = 70); +INSERT INTO t (docs) VALUES ('{"a": 0, "b": 0}'); +INSERT INTO t (docs) SELECT jsonb_build_object('b', n) FROM generate_series(100, 10000) as n; +CREATE INDEX t_idx_a ON t ((docs->'a')); +CREATE INDEX t_idx_b ON t ((docs->'b')) WHERE (docs->'b')::numeric > 9; +SET SESSION enable_seqscan = OFF; +SET SESSION enable_bitmapscan = OFF; +-- Leave 'a' unchanged but modify 'b' to a value outside of the index predicate. +-- This should be a HOT update because neither index is changed. +UPDATE t SET docs = jsonb_build_object('a', 0, 'b', 1) WHERE (docs->'a')::numeric = 0; +SELECT * FROM check_hot_updates(1); + table_name | total_updates | hot_updates | hot_update_percentage | matches_expected +------------+---------------+-------------+-----------------------+------------------ + t | 1 | 1 | 100.00 | t +(1 row) + +-- Check to make sure that the index does not contain a value for 'b' +EXPLAIN (COSTS OFF) SELECT * FROM t WHERE (docs->'b')::numeric > 9 AND (docs->'b')::numeric < 100; + QUERY PLAN +------------------------------------------------------------- + Index Scan using t_idx_b on t + Filter: (((docs -> 'b'::text))::numeric < '100'::numeric) +(2 rows) + +SELECT * FROM t WHERE (docs->'b')::numeric > 9 AND (docs->'b')::numeric < 100; + docs +------ +(0 rows) + +-- Leave 'a' unchanged but modify 'b' to a value within the index predicate. +-- This represents a change for field 'b' from unindexed to indexed and so +-- this should not take the HOT path. +UPDATE t SET docs = jsonb_build_object('a', 0, 'b', 10) WHERE (docs->'a')::numeric = 0; +SELECT * FROM check_hot_updates(1); + table_name | total_updates | hot_updates | hot_update_percentage | matches_expected +------------+---------------+-------------+-----------------------+------------------ + t | 2 | 1 | 50.00 | t +(1 row) + +-- Check to make sure that the index contains the new value of 'b' +EXPLAIN (COSTS OFF) SELECT * FROM t WHERE (docs->'b')::numeric > 9 AND (docs->'b')::numeric < 100; + QUERY PLAN +------------------------------------------------------------- + Index Scan using t_idx_b on t + Filter: (((docs -> 'b'::text))::numeric < '100'::numeric) +(2 rows) + +SELECT * FROM t WHERE (docs->'b')::numeric > 9 AND (docs->'b')::numeric < 100; + docs +------------------- + {"a": 0, "b": 10} +(1 row) + +-- This update modifies the value of 'a', an indexed field, so it also cannot +-- be a HOT update. +UPDATE t SET docs = jsonb_build_object('a', 1, 'b', 10) WHERE (docs->'b')::numeric = 10; +SELECT * FROM check_hot_updates(1); + table_name | total_updates | hot_updates | hot_update_percentage | matches_expected +------------+---------------+-------------+-----------------------+------------------ + t | 3 | 1 | 33.33 | t +(1 row) + +-- This update changes both 'a' and 'b' to new values this cannot use the HOT path. +UPDATE t SET docs = jsonb_build_object('a', 2, 'b', 12) WHERE (docs->'b')::numeric = 10; +SELECT * FROM check_hot_updates(1); + table_name | total_updates | hot_updates | hot_update_percentage | matches_expected +------------+---------------+-------------+-----------------------+------------------ + t | 4 | 1 | 25.00 | t +(1 row) + +-- Check to make sure that the index contains the new value of 'b' +EXPLAIN (COSTS OFF) SELECT * FROM t WHERE (docs->'b')::numeric > 9 AND (docs->'b')::numeric < 100; + QUERY PLAN +------------------------------------------------------------- + Index Scan using t_idx_b on t + Filter: (((docs -> 'b'::text))::numeric < '100'::numeric) +(2 rows) + +SELECT * FROM t WHERE (docs->'b')::numeric > 9 AND (docs->'b')::numeric < 100; + docs +------------------- + {"a": 2, "b": 12} +(1 row) + +-- This update changes 'b' to a value outside its predicate requiring that +-- we remove it from the index. That's a transition that can't be done +-- during a HOT update. +UPDATE t SET docs = jsonb_build_object('a', 2, 'b', 1) WHERE (docs->'b')::numeric = 12; +SELECT * FROM check_hot_updates(1); + table_name | total_updates | hot_updates | hot_update_percentage | matches_expected +------------+---------------+-------------+-----------------------+------------------ + t | 5 | 1 | 20.00 | t +(1 row) + +-- Check to make sure that the index no longer contains the value of 'b' +EXPLAIN (COSTS OFF) SELECT * FROM t WHERE (docs->'b')::numeric > 9 AND (docs->'b')::numeric < 100; + QUERY PLAN +------------------------------------------------------------- + Index Scan using t_idx_b on t + Filter: (((docs -> 'b'::text))::numeric < '100'::numeric) +(2 rows) + +SELECT * FROM t WHERE (docs->'b')::numeric > 9 AND (docs->'b')::numeric < 100; + docs +------ +(0 rows) + +DROP TABLE t CASCADE; +SET SESSION enable_seqscan = ON; +SET SESSION enable_bitmapscan = ON; +-- ================================================================ +-- Tests to check expression indexes +-- ================================================================ +CREATE TABLE t(a INT, b INT) WITH (autovacuum_enabled = off, fillfactor = 70); +CREATE INDEX t_idx_a ON t(abs(a)) WHERE abs(a) > 10; +CREATE INDEX t_idx_b ON t(abs(b)); +INSERT INTO t VALUES (-1, -1), (-2, -2), (-3, -3), (-4, -4), (-5, -5); +INSERT INTO t SELECT m, n FROM generate_series(-10000, -10) AS m, abs(m) AS n; +SET SESSION enable_seqscan = OFF; +SET SESSION enable_bitmapscan = OFF; +-- The indexed value of b hasn't changed, this should be a HOT update. +-- (-5, -5) -> (-5, 1) +UPDATE t SET b = 5 WHERE a = -5; +SELECT * FROM check_hot_updates(1); + table_name | total_updates | hot_updates | hot_update_percentage | matches_expected +------------+---------------+-------------+-----------------------+------------------ + t | 1 | 1 | 100.00 | t +(1 row) + +EXPLAIN (COSTS OFF) SELECT b FROM t WHERE abs(b) < 10 AND abs(b) > 0; + QUERY PLAN +------------------------------------------------ + Index Scan using t_idx_b on t + Index Cond: ((abs(b) < 10) AND (abs(b) > 0)) +(2 rows) + +SELECT b FROM t WHERE abs(b) < 10 AND abs(b) > 0; + b +---- + -1 + -2 + -3 + -4 + 5 +(5 rows) + +-- Now that we're not checking the predicate of the partial index, this +-- update of a from -5 to 5 should be HOT because we should ignore the +-- predicate and check the expression and find it unchanged. +-- (-5, 1) -> (5, 1) +UPDATE t SET a = 5 WHERE a = -5; +SELECT * FROM check_hot_updates(2); + table_name | total_updates | hot_updates | hot_update_percentage | matches_expected +------------+---------------+-------------+-----------------------+------------------ + t | 2 | 2 | 100.00 | t +(1 row) + +-- This update moves a into the partial index and should not +-- be HOT. Let's make sure of that and check the index as well. +-- (-4, -4) -> (-11, -4) +UPDATE t SET a = -11 WHERE a = -4; +SELECT * FROM check_hot_updates(2); + table_name | total_updates | hot_updates | hot_update_percentage | matches_expected +------------+---------------+-------------+-----------------------+------------------ + t | 3 | 2 | 66.67 | t +(1 row) + +EXPLAIN (COSTS OFF) SELECT * FROM t WHERE abs(a) > 10 AND abs(a) < 15; + QUERY PLAN +------------------------------- + Index Scan using t_idx_a on t + Index Cond: (abs(a) < 15) +(2 rows) + +SELECT * FROM t WHERE abs(a) > 10 AND abs(a) < 15; + a | b +-----+---- + -10 | 10 + -11 | -4 + -11 | 11 + -12 | 12 + -13 | 13 + -14 | 14 +(6 rows) + +-- (-11, -4) -> (11, -4) +UPDATE t SET a = 11 WHERE b = -4; +SELECT * FROM check_hot_updates(3); + table_name | total_updates | hot_updates | hot_update_percentage | matches_expected +------------+---------------+-------------+-----------------------+------------------ + t | 4 | 3 | 75.00 | t +(1 row) + +EXPLAIN (COSTS OFF) SELECT * FROM t WHERE abs(a) > 10 AND abs(a) < 15; + QUERY PLAN +------------------------------- + Index Scan using t_idx_a on t + Index Cond: (abs(a) < 15) +(2 rows) + +SELECT * FROM t WHERE abs(a) > 10 AND abs(a) < 15; + a | b +-----+---- + -10 | 10 + 11 | -4 + -11 | 11 + -12 | 12 + -13 | 13 + -14 | 14 +(6 rows) + +-- (11, -4) -> (-4, -4) +UPDATE t SET a = -4 WHERE b = -4; +SELECT * FROM check_hot_updates(3); + table_name | total_updates | hot_updates | hot_update_percentage | matches_expected +------------+---------------+-------------+-----------------------+------------------ + t | 5 | 3 | 60.00 | t +(1 row) + +EXPLAIN (COSTS OFF) SELECT * FROM t WHERE abs(a) > 10 AND abs(a) < 15; + QUERY PLAN +------------------------------- + Index Scan using t_idx_a on t + Index Cond: (abs(a) < 15) +(2 rows) + +SELECT * FROM t WHERE abs(a) > 10 AND abs(a) < 15; + a | b +-----+---- + -10 | 10 + -11 | 11 + -12 | 12 + -13 | 13 + -14 | 14 +(5 rows) + +-- This update of a from 5 to -1 is HOT despite that attribute +-- being indexed because the before and after values for the +-- partial index predicate are outside the index definition. +-- (5, 1) -> (-1, 1) +UPDATE t SET a = -1 WHERE a = 5; +SELECT * FROM check_hot_updates(4); + table_name | total_updates | hot_updates | hot_update_percentage | matches_expected +------------+---------------+-------------+-----------------------+------------------ + t | 6 | 4 | 66.67 | t +(1 row) + +-- This update of a from -2 to -1 will be HOT because the before/after values +-- of a are both outside the predicate of the partial index. +-- (-1, 1) -> (-2, 1) +UPDATE t SET a = -2 WHERE b = -2; +SELECT * FROM check_hot_updates(5); + table_name | total_updates | hot_updates | hot_update_percentage | matches_expected +------------+---------------+-------------+-----------------------+------------------ + t | 7 | 5 | 71.43 | t +(1 row) + +-- The indexed value for b isn't changing, this should be HOT. +-- (-2, -2) -> (-2, 2) +UPDATE t SET b = 2 WHERE b = -2; +SELECT * FROM check_hot_updates(6); + table_name | total_updates | hot_updates | hot_update_percentage | matches_expected +------------+---------------+-------------+-----------------------+------------------ + t | 8 | 6 | 75.00 | t +(1 row) + +EXPLAIN (COSTS OFF) SELECT b FROM t WHERE abs(b) < 10 AND abs(b) > 0; + QUERY PLAN +------------------------------------------------ + Index Scan using t_idx_b on t + Index Cond: ((abs(b) < 10) AND (abs(b) > 0)) +(2 rows) + +SELECT b FROM t WHERE abs(b) < 10 AND abs(b) > 0; + b +---- + -1 + 2 + -3 + -4 + 5 +(5 rows) + +SELECT * FROM t where a > -10 AND a < 10; + a | b +----+---- + -1 | -1 + -3 | -3 + -1 | 5 + -4 | -4 + -2 | 2 +(5 rows) + +-- Before and after values for a are outside the predicate of the index, +-- and because we're checking this should be HOT. +-- (-2, 1) -> (5, 1) +-- (-2, -2) -> (5, -2) +UPDATE t SET a = 5 WHERE a = -1; +SELECT * FROM check_hot_updates(8); + table_name | total_updates | hot_updates | hot_update_percentage | matches_expected +------------+---------------+-------------+-----------------------+------------------ + t | 10 | 8 | 80.00 | t +(1 row) + +EXPLAIN (COSTS OFF) SELECT * FROM t WHERE abs(a) > 10 AND abs(a) < 15; + QUERY PLAN +------------------------------- + Index Scan using t_idx_a on t + Index Cond: (abs(a) < 15) +(2 rows) + +SELECT * FROM t WHERE abs(a) > 10 AND abs(a) < 15; + a | b +-----+---- + -10 | 10 + -11 | 11 + -12 | 12 + -13 | 13 + -14 | 14 +(5 rows) + +DROP TABLE t CASCADE; +SET SESSION enable_seqscan = ON; +SET SESSION enable_bitmapscan = ON; +-- ================================================================ +-- JSONB with two indexes each on separate fields, one partial +-- ================================================================ +CREATE TABLE t(docs JSONB) WITH (autovacuum_enabled = off, fillfactor = 70); +CREATE INDEX t_docs_idx ON t((docs->'a')) WHERE (docs->'b')::integer = 1; +INSERT INTO t VALUES ('{"a": 1, "b": 1}'); +EXPLAIN (COSTS OFF) SELECT * FROM t; + QUERY PLAN +--------------- + Seq Scan on t +(1 row) + +SELECT * FROM t; + docs +------------------ + {"a": 1, "b": 1} +(1 row) + +SET SESSION enable_seqscan = OFF; +SET SESSION enable_bitmapscan = OFF; +EXPLAIN (COSTS OFF) SELECT * FROM t WHERE (docs->'b')::integer = 1; + QUERY PLAN +---------------------------------- + Index Scan using t_docs_idx on t +(1 row) + +SELECT * FROM t WHERE (docs->'b')::integer = 1; + docs +------------------ + {"a": 1, "b": 1} +(1 row) + +SELECT * FROM check_hot_updates(0); + table_name | total_updates | hot_updates | hot_update_percentage | matches_expected +------------+---------------+-------------+-----------------------+------------------ + t | 0 | 0 | 0 | t +(1 row) + +UPDATE t SET docs='{"a": 1, "b": 0}'; +SELECT * FROM check_hot_updates(0); + table_name | total_updates | hot_updates | hot_update_percentage | matches_expected +------------+---------------+-------------+-----------------------+------------------ + t | 1 | 0 | 0.00 | t +(1 row) + +SELECT * FROM t WHERE (docs->'b')::integer = 1; + docs +------ +(0 rows) + +SET SESSION enable_seqscan = ON; +SET SESSION enable_bitmapscan = ON; +DROP TABLE t CASCADE; +-- ================================================================ +-- Tests for multi-column indexes +-- ================================================================ +CREATE TABLE t(id INT, docs JSONB) WITH (autovacuum_enabled = off, fillfactor = 70); +CREATE INDEX t_docs_idx ON t(id, (docs->'a')); +INSERT INTO t VALUES (1, '{"a": 1, "b": 1}'); +SET SESSION enable_seqscan = OFF; +SET SESSION enable_bitmapscan = OFF; +EXPLAIN (COSTS OFF) SELECT * FROM t WHERE id > 0 AND (docs->'a')::integer > 0; + QUERY PLAN +------------------------------------------------ + Index Scan using t_docs_idx on t + Index Cond: (id > 0) + Filter: (((docs -> 'a'::text))::integer > 0) +(3 rows) + +SELECT * FROM t WHERE id > 0 AND (docs->'a')::integer > 0; + id | docs +----+------------------ + 1 | {"a": 1, "b": 1} +(1 row) + +SELECT * FROM check_hot_updates(0); + table_name | total_updates | hot_updates | hot_update_percentage | matches_expected +------------+---------------+-------------+-----------------------+------------------ + t | 0 | 0 | 0 | t +(1 row) + +-- Changing the id attribute which is an indexed attribute should +-- prevent HOT updates. +UPDATE t SET id = 2; +SELECT * FROM check_hot_updates(0); + table_name | total_updates | hot_updates | hot_update_percentage | matches_expected +------------+---------------+-------------+-----------------------+------------------ + t | 1 | 0 | 0.00 | t +(1 row) + +SELECT * FROM t WHERE id > 0 AND (docs->'a')::integer > 0; + id | docs +----+------------------ + 2 | {"a": 1, "b": 1} +(1 row) + +-- Changing the docs->'a' field in the indexed attribute 'docs' +-- should prevent HOT updates. +UPDATE t SET docs='{"a": -2, "b": 1}'; +SELECT * FROM check_hot_updates(0); + table_name | total_updates | hot_updates | hot_update_percentage | matches_expected +------------+---------------+-------------+-----------------------+------------------ + t | 2 | 0 | 0.00 | t +(1 row) + +SELECT * FROM t WHERE id > 0 AND (docs->'a')::integer < 0; + id | docs +----+------------------- + 2 | {"a": -2, "b": 1} +(1 row) + +-- Leaving the docs->'a' attribute unchanged means that the expression +-- is unchanged and because the 'id' attribute isn't in the modified +-- set the indexed tuple is unchanged, this can go HOT. +UPDATE t SET docs='{"a": -2, "b": 2}'; +SELECT * FROM check_hot_updates(1); + table_name | total_updates | hot_updates | hot_update_percentage | matches_expected +------------+---------------+-------------+-----------------------+------------------ + t | 3 | 1 | 33.33 | t +(1 row) + +SELECT * FROM t WHERE id > 0 AND (docs->'a')::integer < 0; + id | docs +----+------------------- + 2 | {"a": -2, "b": 2} +(1 row) + +-- Here we change the 'id' attribute and the 'docs' attribute setting +-- the expression docs->'a' to a new value, this cannot be a HOT update. +UPDATE t SET id = 3, docs='{"a": 3, "b": 3}'; +SELECT * FROM check_hot_updates(1); + table_name | total_updates | hot_updates | hot_update_percentage | matches_expected +------------+---------------+-------------+-----------------------+------------------ + t | 4 | 1 | 25.00 | t +(1 row) + +SELECT * FROM t WHERE id > 0 AND (docs->'a')::integer > 0; + id | docs +----+------------------ + 3 | {"a": 3, "b": 3} +(1 row) + +SET SESSION enable_seqscan = ON; +SET SESSION enable_bitmapscan = ON; +DROP TABLE t CASCADE; +-- ================================================================ +-- Relation with unique constraint, partial index +-- ================================================================ +CREATE TABLE users ( + user_id serial primary key, + name VARCHAR(255) NOT NULL, + email VARCHAR(255) NOT NULL, + EXCLUDE USING btree (lower(email) WITH =) +); +-- Add some data to the table and then update it in ways that should and should +-- not be HOT updates. +INSERT INTO users (name, email) VALUES +('user1', 'user1@example.com'), +('user2', 'user2@example.com'), +('taken', 'taken@EXAMPLE.com'), +('you', 'you@domain.com'), +('taken', 'taken@domain.com'); +-- Should fail because of the unique constraint on the email column. +UPDATE users SET email = 'user1@example.com' WHERE email = 'user2@example.com'; +ERROR: conflicting key value violates exclusion constraint "users_lower_excl" +DETAIL: Key (lower(email::text))=(user1@example.com) conflicts with existing key (lower(email::text))=(user1@example.com). +SELECT * FROM check_hot_updates(0, 'users'); + table_name | total_updates | hot_updates | hot_update_percentage | matches_expected +------------+---------------+-------------+-----------------------+------------------ + users | 1 | 0 | 0.00 | t +(1 row) + +-- Should succeed because the email column is not being updated and should go HOT. +UPDATE users SET name = 'foo' WHERE email = 'user1@example.com'; +SELECT * FROM check_hot_updates(1, 'users'); + table_name | total_updates | hot_updates | hot_update_percentage | matches_expected +------------+---------------+-------------+-----------------------+------------------ + users | 2 | 1 | 50.00 | t +(1 row) + +-- Create a partial index on the email column, updates +CREATE INDEX idx_users_email_no_example ON users (lower(email)) WHERE lower(email) LIKE '%@example.com%'; +-- An update that changes the email column but not the indexed portion of it and falls outside the constraint. +-- Shouldn't be a HOT update because of the exclusion constraint. +UPDATE users SET email = 'you+2@domain.com' WHERE name = 'you'; +SELECT * FROM check_hot_updates(1, 'users'); + table_name | total_updates | hot_updates | hot_update_percentage | matches_expected +------------+---------------+-------------+-----------------------+------------------ + users | 3 | 1 | 33.33 | t +(1 row) + +-- An update that changes the email column but not the indexed portion of it and falls within the constraint. +-- Again, should fail constraint and fail to be a HOT update. +UPDATE users SET email = 'taken@domain.com' WHERE name = 'you'; +ERROR: conflicting key value violates exclusion constraint "users_lower_excl" +DETAIL: Key (lower(email::text))=(taken@domain.com) conflicts with existing key (lower(email::text))=(taken@domain.com). +SELECT * FROM check_hot_updates(1, 'users'); + table_name | total_updates | hot_updates | hot_update_percentage | matches_expected +------------+---------------+-------------+-----------------------+------------------ + users | 4 | 1 | 25.00 | t +(1 row) + +DROP TABLE users CASCADE; +-- ================================================================ +-- Constraints spoiling HOT updates, this time with a range. +-- ================================================================ +CREATE TABLE events ( + id serial primary key, + name VARCHAR(255) NOT NULL, + event_time tstzrange, + constraint no_screening_time_overlap exclude using gist ( + event_time WITH && + ) +); +-- Add two non-overlapping events. +INSERT INTO events (id, event_time, name) +VALUES + (1, '["2023-01-01 19:00:00", "2023-01-01 20:45:00"]', 'event1'), + (2, '["2023-01-01 21:00:00", "2023-01-01 21:45:00"]', 'event2'); +-- Update the first event to overlap with the second, should fail the constraint and not be HOT. +UPDATE events SET event_time = '["2023-01-01 20:00:00", "2023-01-01 21:45:00"]' WHERE id = 1; +ERROR: conflicting key value violates exclusion constraint "no_screening_time_overlap" +DETAIL: Key (event_time)=(["Sun Jan 01 20:00:00 2023 PST","Sun Jan 01 21:45:00 2023 PST"]) conflicts with existing key (event_time)=(["Sun Jan 01 21:00:00 2023 PST","Sun Jan 01 21:45:00 2023 PST"]). +SELECT * FROM check_hot_updates(0, 'events'); + table_name | total_updates | hot_updates | hot_update_percentage | matches_expected +------------+---------------+-------------+-----------------------+------------------ + events | 1 | 0 | 0.00 | t +(1 row) + +-- Update the first event to not overlap with the second, again not HOT due to the constraint. +UPDATE events SET event_time = '["2023-01-01 22:00:00", "2023-01-01 22:45:00"]' WHERE id = 1; +SELECT * FROM check_hot_updates(0, 'events'); + table_name | total_updates | hot_updates | hot_update_percentage | matches_expected +------------+---------------+-------------+-----------------------+------------------ + events | 2 | 0 | 0.00 | t +(1 row) + +-- Update the first event to not overlap with the second, this time we're HOT because we don't overlap with the constraint. +UPDATE events SET name = 'new name here' WHERE id = 1; +SELECT * FROM check_hot_updates(1, 'events'); + table_name | total_updates | hot_updates | hot_update_percentage | matches_expected +------------+---------------+-------------+-----------------------+------------------ + events | 3 | 1 | 33.33 | t +(1 row) + +DROP TABLE events CASCADE; +-- ================================================================ +-- Ensure that only the modified summarizing indexes are updated. +-- ================================================================ +CREATE TABLE ex (id SERIAL primary key, att1 JSONB, att2 text, att3 text, att4 text) WITH (fillfactor = 60); +CREATE INDEX ex_expr1_idx ON ex USING btree((att1->'data')); +CREATE INDEX ex_sumr1_idx ON ex USING BRIN(att2); +CREATE INDEX ex_expr2_idx ON ex USING btree((att1->'a')); +CREATE INDEX ex_expr3_idx ON ex USING btree((att1->'b')); +CREATE INDEX ex_expr4_idx ON ex USING btree((att1->'c')); +CREATE INDEX ex_sumr2_idx ON ex USING BRIN(att3); +CREATE INDEX ex_sumr3_idx ON ex USING BRIN(att4); +CREATE INDEX ex_expr5_idx ON ex USING btree((att1->'d')); +INSERT INTO ex (att1, att2) VALUES ('{"data": []}'::json, 'nothing special'); +SELECT * FROM ex; + id | att1 | att2 | att3 | att4 +----+--------------+-----------------+------+------ + 1 | {"data": []} | nothing special | | +(1 row) + +-- Update att2 and att4 both are BRIN/summarizing indexes, this should be a HOT update and +-- only update two of the three summarizing indexes. +UPDATE ex SET att2 = 'special indeed', att4 = 'whatever'; +SELECT * FROM check_hot_updates(1, 'ex'); + table_name | total_updates | hot_updates | hot_update_percentage | matches_expected +------------+---------------+-------------+-----------------------+------------------ + ex | 1 | 1 | 100.00 | t +(1 row) + +SELECT * FROM ex; + id | att1 | att2 | att3 | att4 +----+--------------+----------------+------+---------- + 1 | {"data": []} | special indeed | | whatever +(1 row) + +-- Update att1 and att2, only one is BRIN/summarizing, this should NOT be a HOT update. +UPDATE ex SET att1 = att1 || '{"data": "howdy"}', att2 = 'special, so special'; +SELECT * FROM check_hot_updates(1, 'ex'); + table_name | total_updates | hot_updates | hot_update_percentage | matches_expected +------------+---------------+-------------+-----------------------+------------------ + ex | 2 | 1 | 50.00 | t +(1 row) + +SELECT * FROM ex; + id | att1 | att2 | att3 | att4 +----+-------------------+---------------------+------+---------- + 1 | {"data": "howdy"} | special, so special | | whatever +(1 row) + +-- Update att2, att3, and att4 all are BRIN/summarizing indexes, this should be a HOT update +-- and yet still update all three summarizing indexes. +UPDATE ex SET att2 = 'a', att3 = 'b', att4 = 'c'; +SELECT * FROM check_hot_updates(2, 'ex'); + table_name | total_updates | hot_updates | hot_update_percentage | matches_expected +------------+---------------+-------------+-----------------------+------------------ + ex | 3 | 2 | 66.67 | t +(1 row) + +SELECT * FROM ex; + id | att1 | att2 | att3 | att4 +----+-------------------+------+------+------ + 1 | {"data": "howdy"} | a | b | c +(1 row) + +-- Update att1, att2, and att3 all modified values are BRIN/summarizing indexes, this should be a HOT update +-- and yet still update all three summarizing indexes. +UPDATE ex SET att1 = '{"data": "howdy"}', att2 = 'd', att3 = 'e'; +SELECT * FROM check_hot_updates(3, 'ex'); + table_name | total_updates | hot_updates | hot_update_percentage | matches_expected +------------+---------------+-------------+-----------------------+------------------ + ex | 4 | 3 | 75.00 | t +(1 row) + +SELECT * FROM ex; + id | att1 | att2 | att3 | att4 +----+-------------------+------+------+------ + 1 | {"data": "howdy"} | d | e | c +(1 row) + +DROP TABLE ex CASCADE; +-- ================================================================ +-- Don't update unmodified summarizing indexes but do allow HOT +-- ================================================================ +CREATE TABLE ex (att1 JSONB, att2 text) WITH (fillfactor = 60); +CREATE INDEX ex_expr1_idx ON ex USING btree((att1->'data')); +CREATE INDEX ex_sumr1_idx ON ex USING BRIN(att2); +INSERT INTO ex VALUES ('{"data": []}', 'nothing special'); +-- Update the unindexed value of att1, this should be a HOT update and and should +-- update the summarizing index. +UPDATE ex SET att1 = att1 || '{"status": "stalemate"}'; +SELECT * FROM check_hot_updates(1, 'ex'); + table_name | total_updates | hot_updates | hot_update_percentage | matches_expected +------------+---------------+-------------+-----------------------+------------------ + ex | 1 | 1 | 100.00 | t +(1 row) + +-- Update the indexed value of att2, a summarized value, this is a summarized +-- only update and should use the HOT path while still triggering an update to +-- the summarizing BRIN index. +UPDATE ex SET att2 = 'special indeed'; +SELECT * FROM check_hot_updates(2, 'ex'); + table_name | total_updates | hot_updates | hot_update_percentage | matches_expected +------------+---------------+-------------+-----------------------+------------------ + ex | 2 | 2 | 100.00 | t +(1 row) + +-- Update to att1 doesn't change the indexed value while the update to att2 does, +-- this again is a summarized only update and should use the HOT path as well as +-- trigger an update to the BRIN index. +UPDATE ex SET att1 = att1 || '{"status": "checkmate"}', att2 = 'special, so special'; +SELECT * FROM check_hot_updates(3, 'ex'); + table_name | total_updates | hot_updates | hot_update_percentage | matches_expected +------------+---------------+-------------+-----------------------+------------------ + ex | 3 | 3 | 100.00 | t +(1 row) + +-- This updates both indexes, the expression index on att1 and the summarizing +-- index on att2. This should not be a HOT update because there are modified +-- indexes and only some are summarized, not all. This should force all +-- indexes to be updated. +UPDATE ex SET att1 = att1 || '{"data": [1,2,3]}', att2 = 'do you want to play a game?'; +SELECT * FROM check_hot_updates(3, 'ex'); + table_name | total_updates | hot_updates | hot_update_percentage | matches_expected +------------+---------------+-------------+-----------------------+------------------ + ex | 4 | 3 | 75.00 | t +(1 row) + +DROP TABLE ex CASCADE; +-- ================================================================ +-- Ensure custom type equality operators are used +-- ================================================================ +CREATE TYPE my_custom_type AS (val int); +-- Comparison functions (returns boolean) +CREATE FUNCTION my_custom_lt(a my_custom_type, b my_custom_type) RETURNS boolean AS $$ +BEGIN + RETURN a.val < b.val; +END; +$$ LANGUAGE plpgsql IMMUTABLE STRICT; +CREATE FUNCTION my_custom_le(a my_custom_type, b my_custom_type) RETURNS boolean AS $$ +BEGIN + RETURN a.val <= b.val; +END; +$$ LANGUAGE plpgsql IMMUTABLE STRICT; +CREATE FUNCTION my_custom_eq(a my_custom_type, b my_custom_type) RETURNS boolean AS $$ +BEGIN + RETURN a.val = b.val; +END; +$$ LANGUAGE plpgsql IMMUTABLE STRICT; +CREATE FUNCTION my_custom_ge(a my_custom_type, b my_custom_type) RETURNS boolean AS $$ +BEGIN + RETURN a.val >= b.val; +END; +$$ LANGUAGE plpgsql IMMUTABLE STRICT; +CREATE FUNCTION my_custom_gt(a my_custom_type, b my_custom_type) RETURNS boolean AS $$ +BEGIN + RETURN a.val > b.val; +END; +$$ LANGUAGE plpgsql IMMUTABLE STRICT; +CREATE FUNCTION my_custom_ne(a my_custom_type, b my_custom_type) RETURNS boolean AS $$ +BEGIN + RETURN a.val != b.val; +END; +$$ LANGUAGE plpgsql IMMUTABLE STRICT; +-- Comparison function (returns -1, 0, 1) +CREATE FUNCTION my_custom_cmp(a my_custom_type, b my_custom_type) RETURNS int AS $$ +BEGIN + IF a.val < b.val THEN + RETURN -1; + ELSIF a.val > b.val THEN + RETURN 1; + ELSE + RETURN 0; + END IF; +END; +$$ LANGUAGE plpgsql IMMUTABLE STRICT; +-- Create the operators +CREATE OPERATOR < ( + LEFTARG = my_custom_type, + RIGHTARG = my_custom_type, + PROCEDURE = my_custom_lt, + COMMUTATOR = >, + NEGATOR = >= +); +CREATE OPERATOR <= ( + LEFTARG = my_custom_type, + RIGHTARG = my_custom_type, + PROCEDURE = my_custom_le, + COMMUTATOR = >=, + NEGATOR = > +); +CREATE OPERATOR = ( + LEFTARG = my_custom_type, + RIGHTARG = my_custom_type, + PROCEDURE = my_custom_eq, + COMMUTATOR = =, + NEGATOR = <> +); +CREATE OPERATOR >= ( + LEFTARG = my_custom_type, + RIGHTARG = my_custom_type, + PROCEDURE = my_custom_ge, + COMMUTATOR = <=, + NEGATOR = < +); +CREATE OPERATOR > ( + LEFTARG = my_custom_type, + RIGHTARG = my_custom_type, + PROCEDURE = my_custom_gt, + COMMUTATOR = <, + NEGATOR = <= +); +CREATE OPERATOR <> ( + LEFTARG = my_custom_type, + RIGHTARG = my_custom_type, + PROCEDURE = my_custom_ne, + COMMUTATOR = <>, + NEGATOR = = +); +-- Create the operator class (including the support function) +CREATE OPERATOR CLASS my_custom_ops + DEFAULT FOR TYPE my_custom_type USING btree AS + OPERATOR 1 <, + OPERATOR 2 <=, + OPERATOR 3 =, + OPERATOR 4 >=, + OPERATOR 5 >, + FUNCTION 1 my_custom_cmp(my_custom_type, my_custom_type); +-- Create the table +CREATE TABLE my_table ( + id int, + custom_val my_custom_type +); +-- Insert some data +INSERT INTO my_table (id, custom_val) VALUES +(1, ROW(3)::my_custom_type), +(2, ROW(1)::my_custom_type), +(3, ROW(4)::my_custom_type), +(4, ROW(2)::my_custom_type); +-- Create a function to use when indexing +CREATE OR REPLACE FUNCTION abs_val(val my_custom_type) RETURNS int AS $$ +BEGIN + RETURN abs(val.val); +END; +$$ LANGUAGE plpgsql IMMUTABLE STRICT; +-- Create the index +CREATE INDEX idx_custom_val_abs ON my_table (abs_val(custom_val)); +-- Update 1 +UPDATE my_table SET custom_val = ROW(5)::my_custom_type WHERE id = 1; +SELECT * FROM check_hot_updates(0, 'my_table'); + table_name | total_updates | hot_updates | hot_update_percentage | matches_expected +------------+---------------+-------------+-----------------------+------------------ + my_table | 1 | 0 | 0.00 | t +(1 row) + +-- Update 2 +UPDATE my_table SET custom_val = ROW(0)::my_custom_type WHERE custom_val < ROW(3)::my_custom_type; +SELECT * FROM check_hot_updates(0, 'my_table'); + table_name | total_updates | hot_updates | hot_update_percentage | matches_expected +------------+---------------+-------------+-----------------------+------------------ + my_table | 3 | 0 | 0.00 | t +(1 row) + +-- Update 3 +UPDATE my_table SET custom_val = ROW(6)::my_custom_type WHERE id = 3; +SELECT * FROM check_hot_updates(0, 'my_table'); + table_name | total_updates | hot_updates | hot_update_percentage | matches_expected +------------+---------------+-------------+-----------------------+------------------ + my_table | 4 | 0 | 0.00 | t +(1 row) + +-- Update 4 +UPDATE my_table SET id = 5 WHERE id = 1; +SELECT * FROM check_hot_updates(1, 'my_table'); + table_name | total_updates | hot_updates | hot_update_percentage | matches_expected +------------+---------------+-------------+-----------------------+------------------ + my_table | 5 | 1 | 20.00 | t +(1 row) + +-- Query using the index +SELECT * FROM my_table WHERE abs_val(custom_val) = 6; + id | custom_val +----+------------ + 3 | (6) +(1 row) + +-- Clean up test case +DROP TABLE my_table CASCADE; +DROP OPERATOR CLASS my_custom_ops USING btree CASCADE; +DROP OPERATOR < (my_custom_type, my_custom_type); +DROP OPERATOR <= (my_custom_type, my_custom_type); +DROP OPERATOR = (my_custom_type, my_custom_type); +DROP OPERATOR >= (my_custom_type, my_custom_type); +DROP OPERATOR > (my_custom_type, my_custom_type); +DROP OPERATOR <> (my_custom_type, my_custom_type); +DROP FUNCTION my_custom_lt(my_custom_type, my_custom_type); +DROP FUNCTION my_custom_le(my_custom_type, my_custom_type); +DROP FUNCTION my_custom_eq(my_custom_type, my_custom_type); +DROP FUNCTION my_custom_ge(my_custom_type, my_custom_type); +DROP FUNCTION my_custom_gt(my_custom_type, my_custom_type); +DROP FUNCTION my_custom_ne(my_custom_type, my_custom_type); +DROP FUNCTION my_custom_cmp(my_custom_type, my_custom_type); +DROP FUNCTION abs_val(my_custom_type); +DROP TYPE my_custom_type CASCADE; +-- Cleanup +DROP FUNCTION check_hot_updates(int, text, text); +DROP COLLATION case_insensitive; diff --git a/src/test/regress/parallel_schedule b/src/test/regress/parallel_schedule index f56482fb9f1..9520d0d4601 100644 --- a/src/test/regress/parallel_schedule +++ b/src/test/regress/parallel_schedule @@ -125,6 +125,12 @@ test: plancache limit plpgsql copy2 temp domain rangefuncs prepare conversion tr # ---------- test: partition_join partition_prune reloptions hash_part indexing partition_aggregate partition_info tuplesort explain compression compression_lz4 memoize stats predicate numa eager_aggregate + +# ---------- +# Another group of parallel tests, these focused on heap HOT updates +# ---------- +test: heap_hot_updates + # event_trigger depends on create_am and cannot run concurrently with # any test that runs DDL # oidjoins is read-only, though, and should run late for best coverage diff --git a/src/test/regress/sql/heap_hot_updates.sql b/src/test/regress/sql/heap_hot_updates.sql new file mode 100644 index 00000000000..8d5510989df --- /dev/null +++ b/src/test/regress/sql/heap_hot_updates.sql @@ -0,0 +1,1325 @@ +-- ================================================================ +-- Test Suite for Heap-only (HOT) Updates +-- ================================================================ + +-- Setup: Create function to measure HOT updates +CREATE OR REPLACE FUNCTION check_hot_updates( + expected INT, + p_table_name TEXT DEFAULT 't', + p_schema_name TEXT DEFAULT current_schema() +) +RETURNS TABLE ( + table_name TEXT, + total_updates BIGINT, + hot_updates BIGINT, + hot_update_percentage NUMERIC, + matches_expected BOOLEAN +) +LANGUAGE plpgsql +AS $$ +DECLARE + v_relid oid; + v_qualified_name TEXT; + v_hot_updates BIGINT; + v_updates BIGINT; + v_xact_hot_updates BIGINT; + v_xact_updates BIGINT; +BEGIN + -- Force statistics update + PERFORM pg_stat_force_next_flush(); + + -- Get table OID + v_qualified_name := quote_ident(p_schema_name) || '.' || quote_ident(p_table_name); + v_relid := v_qualified_name::regclass; + + IF v_relid IS NULL THEN + RAISE EXCEPTION 'Table %.% not found', p_schema_name, p_table_name; + END IF; + + -- Get cumulative + transaction stats + v_hot_updates := COALESCE(pg_stat_get_tuples_hot_updated(v_relid), 0); + v_updates := COALESCE(pg_stat_get_tuples_updated(v_relid), 0); + v_xact_hot_updates := COALESCE(pg_stat_get_xact_tuples_hot_updated(v_relid), 0); + v_xact_updates := COALESCE(pg_stat_get_xact_tuples_updated(v_relid), 0); + + v_hot_updates := v_hot_updates + v_xact_hot_updates; + v_updates := v_updates + v_xact_updates; + + RETURN QUERY + SELECT + p_table_name::TEXT, + v_updates::BIGINT, + v_hot_updates::BIGINT, + CASE WHEN v_updates > 0 + THEN ROUND((v_hot_updates::numeric / v_updates::numeric * 100)::numeric, 2) + ELSE 0 + END, + (v_hot_updates = expected)::BOOLEAN; +END; +$$; + +CREATE COLLATION case_insensitive ( + provider = libc, + locale = 'C' +); + +-- ================================================================ +-- Basic JSONB Expression Index +-- ================================================================ +CREATE TABLE t(id INT PRIMARY KEY, docs JSONB) + WITH (autovacuum_enabled = off, fillfactor = 70); +CREATE INDEX t_docs_name_idx ON t((docs->'name')); +INSERT INTO t VALUES (1, '{"name": "alice", "age": 30}'); + +-- Update non-indexed JSONB field - should be HOT +UPDATE t SET docs = '{"name": "alice", "age": 31}' WHERE id = 1; +SELECT * FROM check_hot_updates(1); + +-- Update indexed JSONB field - should NOT be HOT +UPDATE t SET docs = '{"name": "bob", "age": 31}' WHERE id = 1; +SELECT * FROM check_hot_updates(1); + +-- Update non-indexed field again - should be HOT +UPDATE t SET docs = '{"name": "bob", "age": 32}' WHERE id = 1; +SELECT * FROM check_hot_updates(2); + +DROP TABLE t; + +-- ================================================================ +-- JSONB Expression Index an some including columns +-- ================================================================ +CREATE TABLE t(id INT PRIMARY KEY, docs JSONB, status TEXT) + WITH (autovacuum_enabled = off, fillfactor = 70); +CREATE INDEX t_docs_name_idx ON t((docs->'name')); +INSERT INTO t VALUES (1, '{"name": "alice", "age": 30}', 'ok'); + +-- Update non-indexed JSONB field - should be HOT +UPDATE t SET docs = '{"name": "alice", "age": 31}' WHERE id = 1; +SELECT * FROM check_hot_updates(1); + +-- Update non-indexed JSONB field - should be HOT +UPDATE t SET status = 'not ok' WHERE id = 1; +SELECT * FROM check_hot_updates(2); + +DROP TABLE t; + +-- ================================================================ +-- Partial Index with Predicate Transitions +-- ================================================================ +CREATE TABLE t(id INT, value INT) + WITH (autovacuum_enabled = off, fillfactor = 70); +CREATE INDEX t_value_idx ON t(value) WHERE value > 10; +INSERT INTO t VALUES (1, 5); + +-- Both outside predicate - should be HOT +UPDATE t SET value = 8 WHERE id = 1; +SELECT * FROM check_hot_updates(1); + +-- Transition into predicate - should NOT be HOT +UPDATE t SET value = 15 WHERE id = 1; +SELECT * FROM check_hot_updates(1); + +-- Both inside predicate, value changes - should NOT be HOT +UPDATE t SET value = 20 WHERE id = 1; +SELECT * FROM check_hot_updates(1); + +-- Transition out of predicate - should NOT be HOT +UPDATE t SET value = 5 WHERE id = 1; +SELECT * FROM check_hot_updates(1); + +-- Both outside predicate again - should be HOT +UPDATE t SET value = 3 WHERE id = 1; +SELECT * FROM check_hot_updates(2); + +DROP TABLE t; + +-- ================================================================ +-- Expression Index with Partial Predicate +-- ================================================================ +CREATE TABLE t(docs JSONB) + WITH (autovacuum_enabled = off, fillfactor = 70); +CREATE INDEX t_idx ON t((docs->'status')) + WHERE (docs->'priority')::int > 5; +INSERT INTO t VALUES ('{"status": "pending", "priority": 3}'); + +-- Both outside predicate, status unchanged - should be HOT +UPDATE t SET docs = '{"status": "pending", "priority": 4}'; +SELECT * FROM check_hot_updates(1); + +-- Transition into predicate - should NOT be HOT +UPDATE t SET docs = '{"status": "pending", "priority": 10}'; +SELECT * FROM check_hot_updates(1); + +-- Inside predicate, status changes - should NOT be HOT +UPDATE t SET docs = '{"status": "active", "priority": 10}'; +SELECT * FROM check_hot_updates(1); + +-- Inside predicate, status unchanged - should be HOT +UPDATE t SET docs = '{"status": "active", "priority": 8}'; +SELECT * FROM check_hot_updates(2); + +DROP TABLE t; + +-- ================================================================ +-- GIN Index on JSONB +-- ================================================================ +CREATE TABLE t(id INT, data JSONB) + WITH (autovacuum_enabled = off, fillfactor = 70); +CREATE INDEX t_gin_idx ON t USING gin(data); +INSERT INTO t VALUES (1, '{"tags": ["postgres", "database"]}'); + +-- Change tags - GIN keys changed, should NOT be HOT +UPDATE t SET data = '{"tags": ["postgres", "sql"]}' WHERE id = 1; +SELECT * FROM check_hot_updates(0); + +-- Change tags again - GIN keys changed, should NOT be HOT +UPDATE t SET data = '{"tags": ["mysql", "sql"]}' WHERE id = 1; +SELECT * FROM check_hot_updates(0); + +-- Add field without changing existing keys - GIN keys changed (added "note"), NOT HOT +UPDATE t SET data = '{"tags": ["mysql", "sql"], "note": "test"}' WHERE id = 1; +SELECT * FROM check_hot_updates(0); + +DROP TABLE t; + +-- ================================================================ +-- GIN Index with Unchanged Keys +-- ================================================================ +CREATE TABLE t(id INT, data JSONB) + WITH (autovacuum_enabled = off, fillfactor = 70); +-- Create GIN index on specific path +CREATE INDEX t_gin_idx ON t USING gin((data->'tags')); +INSERT INTO t VALUES (1, '{"tags": ["postgres", "sql"], "status": "active"}'); + +-- Change non-indexed field - GIN keys on 'tags' unchanged, should be HOT +UPDATE t SET data = '{"tags": ["postgres", "sql"], "status": "inactive"}' WHERE id = 1; +SELECT * FROM check_hot_updates(1); + +-- Change indexed tags - GIN keys changed, should NOT be HOT +UPDATE t SET data = '{"tags": ["mysql", "sql"], "status": "inactive"}' WHERE id = 1; +SELECT * FROM check_hot_updates(1); + +DROP TABLE t; + +-- ================================================================ +-- GIN with jsonb_path_ops +-- ================================================================ +CREATE TABLE t(id INT, data JSONB) + WITH (autovacuum_enabled = off, fillfactor = 70); +CREATE INDEX t_gin_idx ON t USING gin(data jsonb_path_ops); +INSERT INTO t VALUES (1, '{"user": {"name": "alice"}, "tags": ["a", "b"]}'); + +-- Change value at different path - keys changed, NOT HOT +UPDATE t SET data = '{"user": {"name": "bob"}, "tags": ["a", "b"]}' WHERE id = 1; +SELECT * FROM check_hot_updates(0); + +DROP TABLE t; + +-- ================================================================ +-- Multi-Column Expression Index +-- ================================================================ +CREATE TABLE t(id INT, a INT, b INT) + WITH (autovacuum_enabled = off, fillfactor = 70); +CREATE INDEX t_idx ON t(id, abs(a), abs(b)); +INSERT INTO t VALUES (1, -5, -10); + +-- Change sign but not abs value - should be HOT +UPDATE t SET a = 5 WHERE id = 1; +SELECT * FROM check_hot_updates(1); + +-- Change abs value - should NOT be HOT +UPDATE t SET b = -15 WHERE id = 1; +SELECT * FROM check_hot_updates(1); + +-- Change id - should NOT be HOT +UPDATE t SET id = 2 WHERE id = 1; +SELECT * FROM check_hot_updates(1); + +DROP TABLE t; + +-- ================================================================ +-- Mixed Index Types (BRIN + Expression) +-- ================================================================ +CREATE TABLE t(id INT, value INT, data JSONB) + WITH (autovacuum_enabled = off, fillfactor = 70); +CREATE INDEX t_brin_idx ON t USING brin(value); +CREATE INDEX t_expr_idx ON t((data->'status')); +INSERT INTO t VALUES (1, 100, '{"status": "active"}'); + +-- Update only BRIN column - should be HOT +UPDATE t SET value = 200 WHERE id = 1; +SELECT * FROM check_hot_updates(1); + +-- Update only expression column - should NOT be HOT +UPDATE t SET data = '{"status": "inactive"}' WHERE id = 1; +SELECT * FROM check_hot_updates(1); + +-- Update both - should NOT be HOT +UPDATE t SET value = 300, data = '{"status": "pending"}' WHERE id = 1; +SELECT * FROM check_hot_updates(1); + +DROP TABLE t; + +-- ================================================================ +-- Expression with COLLATION and BTREE (nbtree) index +-- ================================================================ +CREATE TABLE t( + id INT PRIMARY KEY, + name TEXT COLLATE case_insensitive +) WITH (autovacuum_enabled = off, fillfactor = 70); + +CREATE INDEX t_lower_idx ON t USING BTREE (name COLLATE case_insensitive); + +INSERT INTO t VALUES (1, 'ALICE'); + +-- Change case but not value - should NOT be HOT in BTREE +UPDATE t SET name = 'Alice' WHERE id = 1; +SELECT * FROM check_hot_updates(0); + +-- Change to new value - should NOT be HOT +UPDATE t SET name = 'BOB' WHERE id = 1; +SELECT * FROM check_hot_updates(0); + +DROP TABLE t; + +-- ================================================================ +-- Array Expression Index +-- ================================================================ +CREATE TABLE t(id INT, tags TEXT[]) + WITH (autovacuum_enabled = off, fillfactor = 70); +CREATE INDEX t_array_len_idx ON t(array_length(tags, 1)); +INSERT INTO t VALUES (1, ARRAY['a', 'b', 'c']); + +-- Same length, different elements - should be HOT +UPDATE t SET tags = ARRAY['d', 'e', 'f'] WHERE id = 1; +SELECT * FROM check_hot_updates(1); + +-- Different length - should NOT be HOT +UPDATE t SET tags = ARRAY['d', 'e'] WHERE id = 1; +SELECT * FROM check_hot_updates(1); + +DROP TABLE t; + +-- ================================================================ +-- Nested JSONB Expression and JSONB equality '->' (not '->>') +-- ================================================================ +CREATE TABLE t(data JSONB) + WITH (autovacuum_enabled = off, fillfactor = 70); +CREATE INDEX t_nested_idx ON t((data->'user'->'name')); +INSERT INTO t VALUES ('{"user": {"name": "alice", "age": 30}}'); + +-- Change nested non-indexed field - should be HOT +UPDATE t SET data = '{"user": {"name": "alice", "age": 31}}'; +SELECT * FROM check_hot_updates(1); + +-- Change nested indexed field - should NOT be HOT +UPDATE t SET data = '{"user": {"name": "bob", "age": 31}}'; +SELECT * FROM check_hot_updates(1); + +DROP TABLE t; + +-- ================================================================ +-- Complex Predicate on Multiple JSONB Fields +-- ================================================================ +CREATE TABLE t(data JSONB) + WITH (autovacuum_enabled = off, fillfactor = 70); +CREATE INDEX t_idx ON t((data->'status')) + WHERE (data->'priority')::int > 5 + AND (data->'active')::boolean = true; + +INSERT INTO t VALUES ('{"status": "pending", "priority": 3, "active": true}'); + +-- Outside predicate (priority too low) - should be HOT +UPDATE t SET data = '{"status": "done", "priority": 3, "active": true}'; +SELECT * FROM check_hot_updates(1); + +-- Transition into predicate - should NOT be HOT +UPDATE t SET data = '{"status": "done", "priority": 10, "active": true}'; +SELECT * FROM check_hot_updates(1); + +-- Inside predicate, change to outside (active = false) - should NOT be HOT +UPDATE t SET data = '{"status": "done", "priority": 10, "active": false}'; +SELECT * FROM check_hot_updates(1); + +DROP TABLE t; + +-- ================================================================ +-- GIN Array Index - Order Insensitive Extraction +-- ================================================================ +CREATE TABLE t( + id INT PRIMARY KEY, + data JSONB +) WITH (autovacuum_enabled = off, fillfactor = 70); + +-- GIN index on JSONB array (extracts all elements) +CREATE INDEX t_items_gin ON t USING GIN ((data->'items')); + +INSERT INTO t VALUES (1, '{"items": [1, 2, 3], "status": "active"}'); + +-- Update: Reorder array elements +-- JSONB equality: NOT equal (different arrays) +-- GIN extraction: Same elements extracted (might allow HOT if not careful) +UPDATE t SET data = '{"items": [3, 2, 1], "status": "active"}' WHERE id = 1; +SELECT * FROM check_hot_updates(1); + +-- Update: Add/remove element +UPDATE t SET data = '{"items": [1, 2, 3, 4], "status": "active"}' WHERE id = 1; +SELECT * FROM check_hot_updates(1); + +DROP TABLE t; + +-- ================================================================ +-- TOASTed Values in Expression Index +-- ================================================================ +CREATE TABLE t(id INT, large_text TEXT) + WITH (autovacuum_enabled = off, fillfactor = 70); +CREATE INDEX t_substr_idx ON t(substr(large_text, 1, 10)); + +INSERT INTO t VALUES (1, repeat('x', 5000) || 'identifier'); + +-- Change end of string, prefix unchanged - should be HOT +UPDATE t SET large_text = repeat('x', 5000) || 'different' WHERE id = 1; +SELECT * FROM check_hot_updates(1); + +-- Change prefix - should NOT be HOT +UPDATE t SET large_text = repeat('y', 5000) || 'different' WHERE id = 1; +SELECT * FROM check_hot_updates(1); + +DROP TABLE t; + +-- ================================================================ +-- TEST: GIN with TOASTed TEXT (tsvector) +-- ================================================================ +CREATE TABLE t(id INT, content TEXT, search_vec tsvector) + WITH (autovacuum_enabled = off, fillfactor = 70); + +-- Create trigger to maintain tsvector +CREATE TRIGGER tsvectorupdate_toast + BEFORE INSERT OR UPDATE ON t + FOR EACH ROW EXECUTE FUNCTION + tsvector_update_trigger(search_vec, 'pg_catalog.english', content); + +CREATE INDEX t_gin ON t USING gin(search_vec); + +-- Insert with large content (will be TOASTed) +INSERT INTO t (id, content) VALUES + (1, repeat('important keyword ', 1000) || repeat('filler text ', 10000)); + +-- Verify initial state +SELECT count(*) FROM t WHERE search_vec @@ to_tsquery('important'); +-- Expected: 1 row + +-- IMPORTANT: The BEFORE UPDATE trigger modifies search_vec, so by the time +-- ExecWhichIndexesRequireUpdates() runs, search_vec has already changed. +-- This means the comparison sees old tsvector vs. trigger-modified tsvector, +-- not the natural progression. HOT won't happen because the trigger changed +-- the indexed column. + +-- Update: Even though content keywords unchanged, trigger still fires +UPDATE t +SET content = repeat('important keyword ', 1000) || repeat('different filler ', 10000) +WHERE id = 1; +SELECT * FROM check_hot_updates(0); +-- Expected: 0 HOT (trigger modifies search_vec, blocking HOT) +-- This is actually correct behavior - the trigger updated an indexed column + +-- Update: Change indexed keywords +UPDATE t +SET content = repeat('critical keyword ', 1000) || repeat('different filler ', 10000) +WHERE id = 1; +SELECT * FROM check_hot_updates(0); +-- Expected: 0 HOT (index keys changed) + +-- Verify query correctness +SELECT count(*) FROM t WHERE search_vec @@ to_tsquery('critical'); +-- Expected: 1 row + +DROP TABLE t CASCADE; + +-- ================================================================ +-- TEST: GIN with TOASTed JSONB +-- ================================================================ +CREATE TABLE t(id INT, data JSONB) + WITH (autovacuum_enabled = off, fillfactor = 70); +CREATE INDEX t_gin ON t USING gin((data->'tags')); + +-- Insert with TOASTed JSONB +INSERT INTO t (id, data) VALUES + (1, jsonb_build_object( + 'tags', '["postgres", "database"]'::jsonb, + 'large_field', repeat('x', 10000) + )); + +-- Update: Change large_field, tags unchanged - should be HOT +UPDATE t +SET data = jsonb_build_object( + 'tags', '["postgres", "database"]'::jsonb, + 'large_field', repeat('y', 10000) +) +WHERE id = 1; +SELECT * FROM check_hot_updates(1); +-- Expected: 1 HOT update + +-- Update: Change tags - should NOT be HOT +UPDATE t +SET data = jsonb_build_object( + 'tags', '["postgres", "sql"]'::jsonb, + 'large_field', repeat('y', 10000) +) +WHERE id = 1; +SELECT * FROM check_hot_updates(1); +-- Expected: Still 1 HOT + +-- Verify correctness +SELECT count(*) FROM t WHERE data->'tags' @> '["database"]'::jsonb; +-- Expected: 0 rows +SELECT count(*) FROM t WHERE data->'tags' @> '["sql"]'::jsonb; +-- Expected: 1 row + +DROP TABLE t CASCADE; + +-- ================================================================ +-- TEST: GIN with Array of Large Strings +-- ================================================================ +CREATE TABLE t(id INT, tags TEXT[]) + WITH (autovacuum_enabled = off, fillfactor = 70); +CREATE INDEX t_gin ON t USING gin(tags); + +-- Insert with large array elements (might be TOASTed) +INSERT INTO t (id, tags) VALUES + (1, ARRAY[repeat('tag1', 1000), repeat('tag2', 1000)]); + +-- Update: Change to different large values - NOT HOT +UPDATE t +SET tags = ARRAY[repeat('tag3', 1000), repeat('tag4', 1000)] +WHERE id = 1; +SELECT * FROM check_hot_updates(0); +-- Expected: 0 HOT (keys actually changed) + +-- Update: Keep same tag values, just reorder - SHOULD BE HOT +-- (GIN is order-insensitive: both [tag3,tag4] and [tag4,tag3] +-- extract to the same sorted key set ['tag3','tag4']) +UPDATE t +SET tags = ARRAY[repeat('tag4', 1000), repeat('tag3', 1000)] +WHERE id = 1; +SELECT * FROM check_hot_updates(1); +-- Expected: 1 HOT (GIN keys semantically identical) + +-- Update: Remove an element - NOT HOT (keys changed) +UPDATE t +SET tags = ARRAY[repeat('tag4', 1000)] +WHERE id = 1; +SELECT * FROM check_hot_updates(1); +-- Expected: Still 1 HOT (not this one) + +DROP TABLE t CASCADE; + +-- ================================================================ +-- BRIN Index with Partial Predicate +-- ================================================================ +CREATE TABLE t( + id INT PRIMARY KEY, + value INT, + description TEXT +) WITH (autovacuum_enabled = off, fillfactor = 70); + +CREATE INDEX t_brin_partial_idx ON t USING brin(value) WHERE value > 100; + +INSERT INTO t VALUES (1, 50, 'below range'); + +-- Test 1: Outside predicate +UPDATE t SET description = 'updated' WHERE id = 1; +SELECT * FROM check_hot_updates(1); + +-- Validate: Predicate query returns 0 rows +SELECT COUNT(*) as cnt FROM t WHERE value > 100; + +-- Test 2: Transition into predicate +UPDATE t SET value = 150 WHERE id = 1; +SELECT * FROM check_hot_updates(2); + +-- Validate: Predicate query returns 1 row with correct value +SELECT COUNT(*) as cnt, MAX(value) as max_val FROM t WHERE value > 100; + +-- Test 3: Inside predicate, value changes +UPDATE t SET value = 160, description = 'updated again' WHERE id = 1; +SELECT * FROM check_hot_updates(3); + +-- Validate: Updated value (160) is returned +SELECT COUNT(*) as cnt, MAX(value) as max_val FROM t WHERE value > 100; + +-- Test 4: Transition out of predicate +UPDATE t SET value = 50 WHERE id = 1; +SELECT * FROM check_hot_updates(4); + +SELECT COUNT(*) as cnt FROM t WHERE value > 100; + +SELECT id, value, description FROM t; + +DROP TABLE t CASCADE; + +-- ================================================================ +-- HASH Index (Simple Column) +-- ================================================================ +CREATE TABLE t(id INT, code VARCHAR(20), description TEXT) + WITH (autovacuum_enabled = off, fillfactor = 70); +CREATE INDEX t_hash_idx ON t USING hash(code); +INSERT INTO t VALUES (1, 'CODE001', 'initial'); + +-- Update non-indexed column - should be HOT +UPDATE t SET description = 'updated' WHERE id = 1; +SELECT * FROM check_hot_updates(1); + +-- Update indexed column - HASH index requires update, NOT HOT +UPDATE t SET code = 'CODE002' WHERE id = 1; +SELECT * FROM check_hot_updates(1); + +-- Update both - NOT HOT +UPDATE t SET code = 'CODE003', description = 'changed' WHERE id = 1; +SELECT * FROM check_hot_updates(1); + +-- Back to original code - NOT HOT (different hash bucket location) +UPDATE t SET code = 'CODE001' WHERE id = 1; +SELECT * FROM check_hot_updates(1); + +DROP TABLE t CASCADE; + +-- ================================================================ +-- HASH Index on Expression +-- ================================================================ +CREATE TABLE t(id INT, email TEXT, data JSONB) + WITH (autovacuum_enabled = off, fillfactor = 70); +CREATE INDEX t_hash_lower_email_idx ON t USING HASH(lower(email)); +INSERT INTO t VALUES (1, 'Alice@Example.com', '{"status": "new"}'); + +-- Update non-indexed field - should be HOT +UPDATE t SET data = '{"status": "active"}' WHERE id = 1; +SELECT * FROM check_hot_updates(1); + +-- Update email with case change only (same lowercase) - should be HOT +UPDATE t SET email = 'alice@example.com' WHERE id = 1; +SELECT * FROM check_hot_updates(2); + +-- Update email to different lowercase - NOT HOT +UPDATE t SET email = 'bob@example.com' WHERE id = 1; +SELECT * FROM check_hot_updates(2); + +DROP TABLE t CASCADE; + +-- ================================================================ +-- HASH Index on JSONB Field +-- ================================================================ +CREATE TABLE t(id INT, data JSONB) + WITH (autovacuum_enabled = off, fillfactor = 70); +CREATE INDEX t_hash_category_idx ON t USING hash((data->'category')); +INSERT INTO t VALUES (1, '{"category": "books", "title": "PostgreSQL Guide"}'); + +-- Update non-indexed JSONB field - should be HOT +UPDATE t SET data = '{"category": "books", "title": "PostgreSQL Handbook"}' WHERE id = 1; +SELECT * FROM check_hot_updates(1); + +-- Update indexed JSONB field - NOT HOT +UPDATE t SET data = '{"category": "videos", "title": "PostgreSQL Handbook"}' WHERE id = 1; +SELECT * FROM check_hot_updates(1); + +-- Update both - NOT HOT +UPDATE t SET data = '{"category": "courses", "title": "PostgreSQL Basics"}' WHERE id = 1; +SELECT * FROM check_hot_updates(1); + +DROP TABLE t CASCADE; + +-- ================================================================ +-- Multiple HASH Indexes +-- ================================================================ +CREATE TABLE t(id INT, category VARCHAR, status VARCHAR, value INT) + WITH (autovacuum_enabled = off, fillfactor = 70); +CREATE INDEX t_hash_category_idx ON t USING hash(category); +CREATE INDEX t_hash_status_idx ON t USING hash(status); +INSERT INTO t VALUES (1, 'electronics', 'active', 100); + +-- Update non-indexed column - should be HOT +UPDATE t SET value = 150 WHERE id = 1; +SELECT * FROM check_hot_updates(1); + +-- Update one indexed column - NOT HOT +UPDATE t SET category = 'books' WHERE id = 1; +SELECT * FROM check_hot_updates(1); + +-- Update other indexed column - NOT HOT +UPDATE t SET status = 'inactive' WHERE id = 1; +SELECT * FROM check_hot_updates(1); + +-- Update both indexed columns - NOT HOT +UPDATE t SET category = 'videos', status = 'pending' WHERE id = 1; +SELECT * FROM check_hot_updates(1); + +DROP TABLE t CASCADE; + +-- ================================================================ +-- BRIN vs HASH Comparison +-- ================================================================ +CREATE TABLE t_brin(id INT, value INT, data TEXT) + WITH (autovacuum_enabled = off, fillfactor = 70); +CREATE TABLE t_hash(id INT, value INT, data TEXT) + WITH (autovacuum_enabled = off, fillfactor = 70); + +CREATE INDEX t_brin_value_idx ON t_brin USING brin(value); +CREATE INDEX t_hash_value_idx ON t_hash USING hash(value); + +INSERT INTO t_brin VALUES (1, 100, 'initial'); +INSERT INTO t_hash VALUES (1, 100, 'initial'); + +-- Same update on both - different HOT behavior expected +-- BRIN: might allow HOT (range summary unchanged) +-- HASH: blocks HOT (hash bucket changed) +UPDATE t_brin SET value = 150 WHERE id = 1; +SELECT * FROM check_hot_updates(1, 't_brin'); +-- Expected: 1 HOT (BRIN allows it for single row) + +UPDATE t_hash SET value = 150 WHERE id = 1; +SELECT * FROM check_hot_updates(0, 't_hash'); +-- Expected: 0 HOT (HASH blocks it) + +DROP TABLE t_brin CASCADE; +DROP TABLE t_hash CASCADE; + +-- ================================================================ +-- HASH Index with NULL Values +-- ================================================================ +CREATE TABLE t(id INT, category VARCHAR, data TEXT) + WITH (autovacuum_enabled = off, fillfactor = 70); +CREATE INDEX t_hash_category_idx ON t USING hash(category); +INSERT INTO t VALUES (1, 'electronics', 'initial'); + +-- Update indexed column to NULL - NOT HOT (hash value changed) +UPDATE t SET category = NULL WHERE id = 1; +SELECT * FROM check_hot_updates(0); +-- Expected: 0 HOT + +-- Update indexed column from NULL to value - NOT HOT +UPDATE t SET category = 'books' WHERE id = 1; +SELECT * FROM check_hot_updates(0); +-- Expected: 0 HOT + +-- Update non-indexed column - should be HOT +UPDATE t SET data = 'updated' WHERE id = 1; +SELECT * FROM check_hot_updates(1); +-- Expected: 1 HOT + +DROP TABLE t CASCADE; + +-- ================================================================ +-- BRIN on JSONB Field +-- ================================================================ +CREATE TABLE t(id INT, metrics JSONB) + WITH (autovacuum_enabled = off, fillfactor = 70); +-- BRIN doesn't directly support JSONB, but we can test on expression +CREATE INDEX t_brin_count_idx ON t USING brin( + CAST(metrics->>'count' AS INTEGER) +); +INSERT INTO t VALUES (1, '{"count": "100", "timestamp": "2024-01-01"}'); + +-- Update non-indexed JSONB field - should be HOT +UPDATE t SET metrics = '{"count": "100", "timestamp": "2024-01-02"}' WHERE id = 1; +SELECT * FROM check_hot_updates(1); +-- Expected: 1 HOT + +-- Update indexed field - BRIN allows HOT for single row +UPDATE t SET metrics = '{"count": "150", "timestamp": "2024-01-02"}' WHERE id = 1; +SELECT * FROM check_hot_updates(2); +-- Expected: 2 HOT (BRIN permits single-row updates) + +DROP TABLE t CASCADE; + +-- ================================================================ +-- Mixed BRIN + HASH on Same Table +-- ================================================================ +CREATE TABLE t(id INT, category VARCHAR, timestamp TIMESTAMP, price NUMERIC, data TEXT) + WITH (autovacuum_enabled = off, fillfactor = 70); +CREATE INDEX t_brin_timestamp_idx ON t USING brin(timestamp); +CREATE INDEX t_hash_category_idx ON t USING hash(category); +INSERT INTO t VALUES (1, 'books', '2024-01-01 10:00:00', 29.99, 'initial'); + +-- Update non-indexed column - should be HOT +UPDATE t SET data = 'updated' WHERE id = 1; +SELECT * FROM check_hot_updates(1); +-- Expected: 1 HOT + +-- Update BRIN indexed column - allows HOT +UPDATE t SET timestamp = '2024-01-02 10:00:00' WHERE id = 1; +SELECT * FROM check_hot_updates(2); +-- Expected: 2 HOT + +-- Update HASH indexed column - blocks HOT +UPDATE t SET category = 'videos' WHERE id = 1; +SELECT * FROM check_hot_updates(2); +-- Expected: 2 HOT (HASH blocks it) + +-- Update price (non-indexed) - should be HOT +UPDATE t SET price = 39.99 WHERE id = 1; +SELECT * FROM check_hot_updates(3); +-- Expected: 3 HOT + +DROP TABLE t CASCADE; + +-- ================================================================ +-- Index both on a field in a JSONB document, and the document +-- ================================================================ +CREATE TABLE t(id INT PRIMARY KEY, docs JSONB) WITH (autovacuum_enabled = off, fillfactor = 70); +CREATE INDEX t_docs_idx ON t((docs->'name')); +CREATE INDEX t_docs_col_idx ON t(docs); +INSERT INTO t VALUES (1, '{"name": "john", "data": "some data"}'); + +-- Update impacts index on whole docment attribute, can't go HOT +UPDATE t SET docs='{"name": "john", "data": "some other data"}' WHERE id=1; +SELECT * FROM check_hot_updates(0); + +DROP TABLE t CASCADE; + + +-- ================================================================ +-- Two indexes on a JSONB document, one partial +-- ================================================================ +CREATE TABLE t (docs JSONB) WITH (autovacuum_enabled = off, fillfactor = 70); +INSERT INTO t (docs) VALUES ('{"a": 0, "b": 0}'); +INSERT INTO t (docs) SELECT jsonb_build_object('b', n) FROM generate_series(100, 10000) as n; +CREATE INDEX t_idx_a ON t ((docs->'a')); +CREATE INDEX t_idx_b ON t ((docs->'b')) WHERE (docs->'b')::numeric > 9; + +SET SESSION enable_seqscan = OFF; +SET SESSION enable_bitmapscan = OFF; + +-- Leave 'a' unchanged but modify 'b' to a value outside of the index predicate. +-- This should be a HOT update because neither index is changed. +UPDATE t SET docs = jsonb_build_object('a', 0, 'b', 1) WHERE (docs->'a')::numeric = 0; +SELECT * FROM check_hot_updates(1); + +-- Check to make sure that the index does not contain a value for 'b' +EXPLAIN (COSTS OFF) SELECT * FROM t WHERE (docs->'b')::numeric > 9 AND (docs->'b')::numeric < 100; +SELECT * FROM t WHERE (docs->'b')::numeric > 9 AND (docs->'b')::numeric < 100; + +-- Leave 'a' unchanged but modify 'b' to a value within the index predicate. +-- This represents a change for field 'b' from unindexed to indexed and so +-- this should not take the HOT path. +UPDATE t SET docs = jsonb_build_object('a', 0, 'b', 10) WHERE (docs->'a')::numeric = 0; +SELECT * FROM check_hot_updates(1); + +-- Check to make sure that the index contains the new value of 'b' +EXPLAIN (COSTS OFF) SELECT * FROM t WHERE (docs->'b')::numeric > 9 AND (docs->'b')::numeric < 100; +SELECT * FROM t WHERE (docs->'b')::numeric > 9 AND (docs->'b')::numeric < 100; + +-- This update modifies the value of 'a', an indexed field, so it also cannot +-- be a HOT update. +UPDATE t SET docs = jsonb_build_object('a', 1, 'b', 10) WHERE (docs->'b')::numeric = 10; +SELECT * FROM check_hot_updates(1); + +-- This update changes both 'a' and 'b' to new values this cannot use the HOT path. +UPDATE t SET docs = jsonb_build_object('a', 2, 'b', 12) WHERE (docs->'b')::numeric = 10; +SELECT * FROM check_hot_updates(1); + +-- Check to make sure that the index contains the new value of 'b' +EXPLAIN (COSTS OFF) SELECT * FROM t WHERE (docs->'b')::numeric > 9 AND (docs->'b')::numeric < 100; +SELECT * FROM t WHERE (docs->'b')::numeric > 9 AND (docs->'b')::numeric < 100; + +-- This update changes 'b' to a value outside its predicate requiring that +-- we remove it from the index. That's a transition that can't be done +-- during a HOT update. +UPDATE t SET docs = jsonb_build_object('a', 2, 'b', 1) WHERE (docs->'b')::numeric = 12; +SELECT * FROM check_hot_updates(1); + +-- Check to make sure that the index no longer contains the value of 'b' +EXPLAIN (COSTS OFF) SELECT * FROM t WHERE (docs->'b')::numeric > 9 AND (docs->'b')::numeric < 100; +SELECT * FROM t WHERE (docs->'b')::numeric > 9 AND (docs->'b')::numeric < 100; + +DROP TABLE t CASCADE; +SET SESSION enable_seqscan = ON; +SET SESSION enable_bitmapscan = ON; + +-- ================================================================ +-- Tests to check expression indexes +-- ================================================================ +CREATE TABLE t(a INT, b INT) WITH (autovacuum_enabled = off, fillfactor = 70); +CREATE INDEX t_idx_a ON t(abs(a)) WHERE abs(a) > 10; +CREATE INDEX t_idx_b ON t(abs(b)); +INSERT INTO t VALUES (-1, -1), (-2, -2), (-3, -3), (-4, -4), (-5, -5); +INSERT INTO t SELECT m, n FROM generate_series(-10000, -10) AS m, abs(m) AS n; +SET SESSION enable_seqscan = OFF; +SET SESSION enable_bitmapscan = OFF; + +-- The indexed value of b hasn't changed, this should be a HOT update. +-- (-5, -5) -> (-5, 1) +UPDATE t SET b = 5 WHERE a = -5; +SELECT * FROM check_hot_updates(1); +EXPLAIN (COSTS OFF) SELECT b FROM t WHERE abs(b) < 10 AND abs(b) > 0; +SELECT b FROM t WHERE abs(b) < 10 AND abs(b) > 0; + +-- Now that we're not checking the predicate of the partial index, this +-- update of a from -5 to 5 should be HOT because we should ignore the +-- predicate and check the expression and find it unchanged. +-- (-5, 1) -> (5, 1) +UPDATE t SET a = 5 WHERE a = -5; +SELECT * FROM check_hot_updates(2); + +-- This update moves a into the partial index and should not +-- be HOT. Let's make sure of that and check the index as well. +-- (-4, -4) -> (-11, -4) +UPDATE t SET a = -11 WHERE a = -4; +SELECT * FROM check_hot_updates(2); +EXPLAIN (COSTS OFF) SELECT * FROM t WHERE abs(a) > 10 AND abs(a) < 15; +SELECT * FROM t WHERE abs(a) > 10 AND abs(a) < 15; + +-- (-11, -4) -> (11, -4) +UPDATE t SET a = 11 WHERE b = -4; +SELECT * FROM check_hot_updates(3); +EXPLAIN (COSTS OFF) SELECT * FROM t WHERE abs(a) > 10 AND abs(a) < 15; +SELECT * FROM t WHERE abs(a) > 10 AND abs(a) < 15; + +-- (11, -4) -> (-4, -4) +UPDATE t SET a = -4 WHERE b = -4; +SELECT * FROM check_hot_updates(3); +EXPLAIN (COSTS OFF) SELECT * FROM t WHERE abs(a) > 10 AND abs(a) < 15; +SELECT * FROM t WHERE abs(a) > 10 AND abs(a) < 15; + +-- This update of a from 5 to -1 is HOT despite that attribute +-- being indexed because the before and after values for the +-- partial index predicate are outside the index definition. +-- (5, 1) -> (-1, 1) +UPDATE t SET a = -1 WHERE a = 5; +SELECT * FROM check_hot_updates(4); + +-- This update of a from -2 to -1 will be HOT because the before/after values +-- of a are both outside the predicate of the partial index. +-- (-1, 1) -> (-2, 1) +UPDATE t SET a = -2 WHERE b = -2; +SELECT * FROM check_hot_updates(5); + +-- The indexed value for b isn't changing, this should be HOT. +-- (-2, -2) -> (-2, 2) +UPDATE t SET b = 2 WHERE b = -2; +SELECT * FROM check_hot_updates(6); +EXPLAIN (COSTS OFF) SELECT b FROM t WHERE abs(b) < 10 AND abs(b) > 0; +SELECT b FROM t WHERE abs(b) < 10 AND abs(b) > 0; + +SELECT * FROM t where a > -10 AND a < 10; + +-- Before and after values for a are outside the predicate of the index, +-- and because we're checking this should be HOT. +-- (-2, 1) -> (5, 1) +-- (-2, -2) -> (5, -2) +UPDATE t SET a = 5 WHERE a = -1; +SELECT * FROM check_hot_updates(8); + +EXPLAIN (COSTS OFF) SELECT * FROM t WHERE abs(a) > 10 AND abs(a) < 15; +SELECT * FROM t WHERE abs(a) > 10 AND abs(a) < 15; + +DROP TABLE t CASCADE; +SET SESSION enable_seqscan = ON; +SET SESSION enable_bitmapscan = ON; + + +-- ================================================================ +-- JSONB with two indexes each on separate fields, one partial +-- ================================================================ +CREATE TABLE t(docs JSONB) WITH (autovacuum_enabled = off, fillfactor = 70); +CREATE INDEX t_docs_idx ON t((docs->'a')) WHERE (docs->'b')::integer = 1; +INSERT INTO t VALUES ('{"a": 1, "b": 1}'); + +EXPLAIN (COSTS OFF) SELECT * FROM t; +SELECT * FROM t; + +SET SESSION enable_seqscan = OFF; +SET SESSION enable_bitmapscan = OFF; + +EXPLAIN (COSTS OFF) SELECT * FROM t WHERE (docs->'b')::integer = 1; +SELECT * FROM t WHERE (docs->'b')::integer = 1; + +SELECT * FROM check_hot_updates(0); + +UPDATE t SET docs='{"a": 1, "b": 0}'; +SELECT * FROM check_hot_updates(0); + +SELECT * FROM t WHERE (docs->'b')::integer = 1; + +SET SESSION enable_seqscan = ON; +SET SESSION enable_bitmapscan = ON; + +DROP TABLE t CASCADE; + + +-- ================================================================ +-- Tests for multi-column indexes +-- ================================================================ +CREATE TABLE t(id INT, docs JSONB) WITH (autovacuum_enabled = off, fillfactor = 70); +CREATE INDEX t_docs_idx ON t(id, (docs->'a')); +INSERT INTO t VALUES (1, '{"a": 1, "b": 1}'); + +SET SESSION enable_seqscan = OFF; +SET SESSION enable_bitmapscan = OFF; + +EXPLAIN (COSTS OFF) SELECT * FROM t WHERE id > 0 AND (docs->'a')::integer > 0; +SELECT * FROM t WHERE id > 0 AND (docs->'a')::integer > 0; + +SELECT * FROM check_hot_updates(0); + +-- Changing the id attribute which is an indexed attribute should +-- prevent HOT updates. +UPDATE t SET id = 2; +SELECT * FROM check_hot_updates(0); + +SELECT * FROM t WHERE id > 0 AND (docs->'a')::integer > 0; + +-- Changing the docs->'a' field in the indexed attribute 'docs' +-- should prevent HOT updates. +UPDATE t SET docs='{"a": -2, "b": 1}'; +SELECT * FROM check_hot_updates(0); + +SELECT * FROM t WHERE id > 0 AND (docs->'a')::integer < 0; + +-- Leaving the docs->'a' attribute unchanged means that the expression +-- is unchanged and because the 'id' attribute isn't in the modified +-- set the indexed tuple is unchanged, this can go HOT. +UPDATE t SET docs='{"a": -2, "b": 2}'; +SELECT * FROM check_hot_updates(1); + +SELECT * FROM t WHERE id > 0 AND (docs->'a')::integer < 0; + +-- Here we change the 'id' attribute and the 'docs' attribute setting +-- the expression docs->'a' to a new value, this cannot be a HOT update. +UPDATE t SET id = 3, docs='{"a": 3, "b": 3}'; +SELECT * FROM check_hot_updates(1); + +SELECT * FROM t WHERE id > 0 AND (docs->'a')::integer > 0; + +SET SESSION enable_seqscan = ON; +SET SESSION enable_bitmapscan = ON; + +DROP TABLE t CASCADE; + +-- ================================================================ +-- Relation with unique constraint, partial index +-- ================================================================ +CREATE TABLE users ( + user_id serial primary key, + name VARCHAR(255) NOT NULL, + email VARCHAR(255) NOT NULL, + EXCLUDE USING btree (lower(email) WITH =) +); + +-- Add some data to the table and then update it in ways that should and should +-- not be HOT updates. +INSERT INTO users (name, email) VALUES +('user1', 'user1@example.com'), +('user2', 'user2@example.com'), +('taken', 'taken@EXAMPLE.com'), +('you', 'you@domain.com'), +('taken', 'taken@domain.com'); + +-- Should fail because of the unique constraint on the email column. +UPDATE users SET email = 'user1@example.com' WHERE email = 'user2@example.com'; +SELECT * FROM check_hot_updates(0, 'users'); + +-- Should succeed because the email column is not being updated and should go HOT. +UPDATE users SET name = 'foo' WHERE email = 'user1@example.com'; +SELECT * FROM check_hot_updates(1, 'users'); + +-- Create a partial index on the email column, updates +CREATE INDEX idx_users_email_no_example ON users (lower(email)) WHERE lower(email) LIKE '%@example.com%'; + +-- An update that changes the email column but not the indexed portion of it and falls outside the constraint. +-- Shouldn't be a HOT update because of the exclusion constraint. +UPDATE users SET email = 'you+2@domain.com' WHERE name = 'you'; +SELECT * FROM check_hot_updates(1, 'users'); + +-- An update that changes the email column but not the indexed portion of it and falls within the constraint. +-- Again, should fail constraint and fail to be a HOT update. +UPDATE users SET email = 'taken@domain.com' WHERE name = 'you'; +SELECT * FROM check_hot_updates(1, 'users'); + +DROP TABLE users CASCADE; + +-- ================================================================ +-- Constraints spoiling HOT updates, this time with a range. +-- ================================================================ +CREATE TABLE events ( + id serial primary key, + name VARCHAR(255) NOT NULL, + event_time tstzrange, + constraint no_screening_time_overlap exclude using gist ( + event_time WITH && + ) +); + +-- Add two non-overlapping events. +INSERT INTO events (id, event_time, name) +VALUES + (1, '["2023-01-01 19:00:00", "2023-01-01 20:45:00"]', 'event1'), + (2, '["2023-01-01 21:00:00", "2023-01-01 21:45:00"]', 'event2'); + +-- Update the first event to overlap with the second, should fail the constraint and not be HOT. +UPDATE events SET event_time = '["2023-01-01 20:00:00", "2023-01-01 21:45:00"]' WHERE id = 1; +SELECT * FROM check_hot_updates(0, 'events'); + +-- Update the first event to not overlap with the second, again not HOT due to the constraint. +UPDATE events SET event_time = '["2023-01-01 22:00:00", "2023-01-01 22:45:00"]' WHERE id = 1; +SELECT * FROM check_hot_updates(0, 'events'); + +-- Update the first event to not overlap with the second, this time we're HOT because we don't overlap with the constraint. +UPDATE events SET name = 'new name here' WHERE id = 1; +SELECT * FROM check_hot_updates(1, 'events'); + +DROP TABLE events CASCADE; + +-- ================================================================ +-- Ensure that only the modified summarizing indexes are updated. +-- ================================================================ +CREATE TABLE ex (id SERIAL primary key, att1 JSONB, att2 text, att3 text, att4 text) WITH (fillfactor = 60); +CREATE INDEX ex_expr1_idx ON ex USING btree((att1->'data')); +CREATE INDEX ex_sumr1_idx ON ex USING BRIN(att2); +CREATE INDEX ex_expr2_idx ON ex USING btree((att1->'a')); +CREATE INDEX ex_expr3_idx ON ex USING btree((att1->'b')); +CREATE INDEX ex_expr4_idx ON ex USING btree((att1->'c')); +CREATE INDEX ex_sumr2_idx ON ex USING BRIN(att3); +CREATE INDEX ex_sumr3_idx ON ex USING BRIN(att4); +CREATE INDEX ex_expr5_idx ON ex USING btree((att1->'d')); +INSERT INTO ex (att1, att2) VALUES ('{"data": []}'::json, 'nothing special'); + +SELECT * FROM ex; + +-- Update att2 and att4 both are BRIN/summarizing indexes, this should be a HOT update and +-- only update two of the three summarizing indexes. +UPDATE ex SET att2 = 'special indeed', att4 = 'whatever'; +SELECT * FROM check_hot_updates(1, 'ex'); +SELECT * FROM ex; + +-- Update att1 and att2, only one is BRIN/summarizing, this should NOT be a HOT update. +UPDATE ex SET att1 = att1 || '{"data": "howdy"}', att2 = 'special, so special'; +SELECT * FROM check_hot_updates(1, 'ex'); +SELECT * FROM ex; + +-- Update att2, att3, and att4 all are BRIN/summarizing indexes, this should be a HOT update +-- and yet still update all three summarizing indexes. +UPDATE ex SET att2 = 'a', att3 = 'b', att4 = 'c'; +SELECT * FROM check_hot_updates(2, 'ex'); +SELECT * FROM ex; + +-- Update att1, att2, and att3 all modified values are BRIN/summarizing indexes, this should be a HOT update +-- and yet still update all three summarizing indexes. +UPDATE ex SET att1 = '{"data": "howdy"}', att2 = 'd', att3 = 'e'; +SELECT * FROM check_hot_updates(3, 'ex'); +SELECT * FROM ex; + +DROP TABLE ex CASCADE; + +-- ================================================================ +-- Don't update unmodified summarizing indexes but do allow HOT +-- ================================================================ +CREATE TABLE ex (att1 JSONB, att2 text) WITH (fillfactor = 60); +CREATE INDEX ex_expr1_idx ON ex USING btree((att1->'data')); +CREATE INDEX ex_sumr1_idx ON ex USING BRIN(att2); +INSERT INTO ex VALUES ('{"data": []}', 'nothing special'); + +-- Update the unindexed value of att1, this should be a HOT update and and should +-- update the summarizing index. +UPDATE ex SET att1 = att1 || '{"status": "stalemate"}'; +SELECT * FROM check_hot_updates(1, 'ex'); + +-- Update the indexed value of att2, a summarized value, this is a summarized +-- only update and should use the HOT path while still triggering an update to +-- the summarizing BRIN index. +UPDATE ex SET att2 = 'special indeed'; +SELECT * FROM check_hot_updates(2, 'ex'); + +-- Update to att1 doesn't change the indexed value while the update to att2 does, +-- this again is a summarized only update and should use the HOT path as well as +-- trigger an update to the BRIN index. +UPDATE ex SET att1 = att1 || '{"status": "checkmate"}', att2 = 'special, so special'; +SELECT * FROM check_hot_updates(3, 'ex'); + +-- This updates both indexes, the expression index on att1 and the summarizing +-- index on att2. This should not be a HOT update because there are modified +-- indexes and only some are summarized, not all. This should force all +-- indexes to be updated. +UPDATE ex SET att1 = att1 || '{"data": [1,2,3]}', att2 = 'do you want to play a game?'; +SELECT * FROM check_hot_updates(3, 'ex'); + +DROP TABLE ex CASCADE; + +-- ================================================================ +-- Ensure custom type equality operators are used +-- ================================================================ + +CREATE TYPE my_custom_type AS (val int); + +-- Comparison functions (returns boolean) +CREATE FUNCTION my_custom_lt(a my_custom_type, b my_custom_type) RETURNS boolean AS $$ +BEGIN + RETURN a.val < b.val; +END; +$$ LANGUAGE plpgsql IMMUTABLE STRICT; + +CREATE FUNCTION my_custom_le(a my_custom_type, b my_custom_type) RETURNS boolean AS $$ +BEGIN + RETURN a.val <= b.val; +END; +$$ LANGUAGE plpgsql IMMUTABLE STRICT; + +CREATE FUNCTION my_custom_eq(a my_custom_type, b my_custom_type) RETURNS boolean AS $$ +BEGIN + RETURN a.val = b.val; +END; +$$ LANGUAGE plpgsql IMMUTABLE STRICT; + +CREATE FUNCTION my_custom_ge(a my_custom_type, b my_custom_type) RETURNS boolean AS $$ +BEGIN + RETURN a.val >= b.val; +END; +$$ LANGUAGE plpgsql IMMUTABLE STRICT; + +CREATE FUNCTION my_custom_gt(a my_custom_type, b my_custom_type) RETURNS boolean AS $$ +BEGIN + RETURN a.val > b.val; +END; +$$ LANGUAGE plpgsql IMMUTABLE STRICT; + +CREATE FUNCTION my_custom_ne(a my_custom_type, b my_custom_type) RETURNS boolean AS $$ +BEGIN + RETURN a.val != b.val; +END; +$$ LANGUAGE plpgsql IMMUTABLE STRICT; + +-- Comparison function (returns -1, 0, 1) +CREATE FUNCTION my_custom_cmp(a my_custom_type, b my_custom_type) RETURNS int AS $$ +BEGIN + IF a.val < b.val THEN + RETURN -1; + ELSIF a.val > b.val THEN + RETURN 1; + ELSE + RETURN 0; + END IF; +END; +$$ LANGUAGE plpgsql IMMUTABLE STRICT; + +-- Create the operators +CREATE OPERATOR < ( + LEFTARG = my_custom_type, + RIGHTARG = my_custom_type, + PROCEDURE = my_custom_lt, + COMMUTATOR = >, + NEGATOR = >= +); + +CREATE OPERATOR <= ( + LEFTARG = my_custom_type, + RIGHTARG = my_custom_type, + PROCEDURE = my_custom_le, + COMMUTATOR = >=, + NEGATOR = > +); + +CREATE OPERATOR = ( + LEFTARG = my_custom_type, + RIGHTARG = my_custom_type, + PROCEDURE = my_custom_eq, + COMMUTATOR = =, + NEGATOR = <> +); + +CREATE OPERATOR >= ( + LEFTARG = my_custom_type, + RIGHTARG = my_custom_type, + PROCEDURE = my_custom_ge, + COMMUTATOR = <=, + NEGATOR = < +); + +CREATE OPERATOR > ( + LEFTARG = my_custom_type, + RIGHTARG = my_custom_type, + PROCEDURE = my_custom_gt, + COMMUTATOR = <, + NEGATOR = <= +); + +CREATE OPERATOR <> ( + LEFTARG = my_custom_type, + RIGHTARG = my_custom_type, + PROCEDURE = my_custom_ne, + COMMUTATOR = <>, + NEGATOR = = +); + +-- Create the operator class (including the support function) +CREATE OPERATOR CLASS my_custom_ops + DEFAULT FOR TYPE my_custom_type USING btree AS + OPERATOR 1 <, + OPERATOR 2 <=, + OPERATOR 3 =, + OPERATOR 4 >=, + OPERATOR 5 >, + FUNCTION 1 my_custom_cmp(my_custom_type, my_custom_type); + +-- Create the table +CREATE TABLE my_table ( + id int, + custom_val my_custom_type +); + +-- Insert some data +INSERT INTO my_table (id, custom_val) VALUES +(1, ROW(3)::my_custom_type), +(2, ROW(1)::my_custom_type), +(3, ROW(4)::my_custom_type), +(4, ROW(2)::my_custom_type); + +-- Create a function to use when indexing +CREATE OR REPLACE FUNCTION abs_val(val my_custom_type) RETURNS int AS $$ +BEGIN + RETURN abs(val.val); +END; +$$ LANGUAGE plpgsql IMMUTABLE STRICT; + +-- Create the index +CREATE INDEX idx_custom_val_abs ON my_table (abs_val(custom_val)); + +-- Update 1 +UPDATE my_table SET custom_val = ROW(5)::my_custom_type WHERE id = 1; +SELECT * FROM check_hot_updates(0, 'my_table'); + +-- Update 2 +UPDATE my_table SET custom_val = ROW(0)::my_custom_type WHERE custom_val < ROW(3)::my_custom_type; +SELECT * FROM check_hot_updates(0, 'my_table'); + +-- Update 3 +UPDATE my_table SET custom_val = ROW(6)::my_custom_type WHERE id = 3; +SELECT * FROM check_hot_updates(0, 'my_table'); + +-- Update 4 +UPDATE my_table SET id = 5 WHERE id = 1; +SELECT * FROM check_hot_updates(1, 'my_table'); + +-- Query using the index +SELECT * FROM my_table WHERE abs_val(custom_val) = 6; + +-- Clean up test case +DROP TABLE my_table CASCADE; +DROP OPERATOR CLASS my_custom_ops USING btree CASCADE; +DROP OPERATOR < (my_custom_type, my_custom_type); +DROP OPERATOR <= (my_custom_type, my_custom_type); +DROP OPERATOR = (my_custom_type, my_custom_type); +DROP OPERATOR >= (my_custom_type, my_custom_type); +DROP OPERATOR > (my_custom_type, my_custom_type); +DROP OPERATOR <> (my_custom_type, my_custom_type); +DROP FUNCTION my_custom_lt(my_custom_type, my_custom_type); +DROP FUNCTION my_custom_le(my_custom_type, my_custom_type); +DROP FUNCTION my_custom_eq(my_custom_type, my_custom_type); +DROP FUNCTION my_custom_ge(my_custom_type, my_custom_type); +DROP FUNCTION my_custom_gt(my_custom_type, my_custom_type); +DROP FUNCTION my_custom_ne(my_custom_type, my_custom_type); +DROP FUNCTION my_custom_cmp(my_custom_type, my_custom_type); +DROP FUNCTION abs_val(my_custom_type); +DROP TYPE my_custom_type CASCADE; + +-- Cleanup +DROP FUNCTION check_hot_updates(int, text, text); +DROP COLLATION case_insensitive; diff --git a/src/tools/pgindent/typedefs.list b/src/tools/pgindent/typedefs.list index 27a4d131897..1eace574994 100644 --- a/src/tools/pgindent/typedefs.list +++ b/src/tools/pgindent/typedefs.list @@ -390,6 +390,7 @@ CachedFunctionCompileCallback CachedFunctionDeleteCallback CachedFunctionHashEntry CachedFunctionHashKey +CachedIndexDatum CachedPlan CachedPlanSource CallContext -- 2.49.0