From efa2b802f68b4057611a8a85be0e3ce241f3c19c Mon Sep 17 00:00:00 2001 From: Vinod Sridharan Date: Fri, 2 May 2025 10:14:06 +0000 Subject: [PATCH] Merged PR 1659003: [Composite OpClass] Enable Runtime Functions and add test coverage ### Does this PR have any customer impact? No ### Type (Feature, Refactoring, Bugfix, DevOps, Testing, Perf, etc) Feature/POC ### Does it involve schema level changes? (Table, Column, Index, UDF, etc level changes) No ### Are you introducing any new config? If yes, do you have tests with and without them being set? Yes ### ChangeLog (Refer [Template](../oss/CHANGELOG.md)) ### Description Fix up runtime index recheck function support to reduce loading documents. This should reduce the number of runtime rechecks that are needed for documents and trust the index more as we will evaluate these clauses directly on the index first. Also add option to trigger jstest coverage for the new opclass - and set them to run on the MX jstests - this is still disabled right now since there are some failing tests but will be enabled separately. ---- #### AI description (iteration 1) #### PR Classification New feature: This pull request introduces runtime functions for composite index operations and enhances test coverage. #### PR Summary This pull request enables runtime functions for composite index operations, improving the flexibility and efficiency of index handling. It also adds test coverage to ensure the reliability of these new features. - `bson_gin_composite_entrypoint.c`: Refactored comparison logic to support runtime functions for index rechecks. - `bson_gin_composite_core.c`: Implemented `IsValidForIndexValue` function to handle various BSON index strategies with runtime rechecks. - `create_indexes.c`: Modified index creation logic to conditionally enable new composite index opclass based on configuration. - `bson_gin_composite_private.h`: Added `IndexRecheckArgs` structure to support runtime recheck strategies. - `testing_configs.c`: Introduced configuration options for enabling the new composite index opclass by default. --- ...operator_tests_explain_index_composite.out | 16 +- ...tor_tests_pg17_explain_index_composite.out | 16 +- .../regress/expected/commands_update_bulk.out | 8 +- .../test/regress/sql/commands_update_bulk.sql | 8 +- .../opclass/bson_gin_composite_private.h | 14 + .../include/opclass/bson_gin_index_term.h | 13 + pg_documentdb/src/commands/create_indexes.c | 17 +- pg_documentdb/src/configs/testing_configs.c | 10 + .../src/opclass/bson_gin_composite_core.c | 433 ++++++++++++++++-- .../opclass/bson_gin_composite_entrypoint.c | 169 ++++--- .../src/opclass/bson_gin_entrypoint.c | 16 +- pg_documentdb/src/opclass/gin_index_term.c | 87 +++- ...son_composite_index_tests_insert_terms.out | 6 +- 13 files changed, 647 insertions(+), 166 deletions(-) diff --git a/internal/pg_documentdb_distributed/src/test/regress/expected/bson_query_operator_tests_explain_index_composite.out b/internal/pg_documentdb_distributed/src/test/regress/expected/bson_query_operator_tests_explain_index_composite.out index 54b271ca..eb970cbd 100644 --- a/internal/pg_documentdb_distributed/src/test/regress/expected/bson_query_operator_tests_explain_index_composite.out +++ b/internal/pg_documentdb_distributed/src/test/regress/expected/bson_query_operator_tests_explain_index_composite.out @@ -591,9 +591,9 @@ EXPLAIN (COSTS OFF, ANALYZE ON, SUMMARY OFF, TIMING OFF) SELECT object_id, docum Node: host=localhost port=58070 dbname=regression -> Bitmap Heap Scan on documents_1200_1200005 collection (actual rows=19 loops=1) Recheck Cond: (document OPERATOR(documentdb_api_catalog.@!=) '{ "a.b" : { "$numberInt" : "1" } }'::documentdb_core.bson) - Rows Removed by Index Recheck: 4 + Rows Removed by Index Recheck: 3 Heap Blocks: exact=1 - -> Bitmap Index Scan on queryoperator_ab (actual rows=23 loops=1) + -> Bitmap Index Scan on queryoperator_ab (actual rows=22 loops=1) Index Cond: (document OPERATOR(documentdb_api_catalog.@!=) '{ "a.b" : { "$numberInt" : "1" } }'::documentdb_core.bson) (13 rows) @@ -985,9 +985,9 @@ EXPLAIN (COSTS OFF, ANALYZE ON, SUMMARY OFF, TIMING OFF) SELECT object_id, docum Node: host=localhost port=58070 dbname=regression -> Bitmap Heap Scan on documents_1200_1200005 collection (actual rows=21 loops=1) Recheck Cond: (document OPERATOR(documentdb_api_catalog.@!=) '{ "a" : { "b" : { "$numberInt" : "1" } } }'::documentdb_core.bson) - Rows Removed by Index Recheck: 2 + Rows Removed by Index Recheck: 1 Heap Blocks: exact=1 - -> Bitmap Index Scan on queryoperator_b_a (actual rows=23 loops=1) + -> Bitmap Index Scan on queryoperator_b_a (actual rows=22 loops=1) Index Cond: (document OPERATOR(documentdb_api_catalog.@!=) '{ "a" : { "b" : { "$numberInt" : "1" } } }'::documentdb_core.bson) (13 rows) @@ -1273,9 +1273,9 @@ EXPLAIN (COSTS OFF, ANALYZE ON, SUMMARY OFF, TIMING OFF) SELECT object_id, docum Sort Method: quicksort Memory: 25kB -> Bitmap Heap Scan on documents_1200_1200005 collection (actual rows=2 loops=1) Recheck Cond: (document OPERATOR(documentdb_api_catalog.@&=) '{ "a" : [ { "$elemMatch" : { "b" : "M", "c" : { "$gt" : { "$numberInt" : "50" } } } }, { "$elemMatch" : { "c" : { "$numberInt" : "100" }, "d" : "Y" } } ] }'::documentdb_core.bson) - Rows Removed by Index Recheck: 9 + Rows Removed by Index Recheck: 1 Heap Blocks: exact=1 - -> Bitmap Index Scan on queryoperator_b_a (actual rows=11 loops=1) + -> Bitmap Index Scan on queryoperator_b_a (actual rows=3 loops=1) Index Cond: (document OPERATOR(documentdb_api_catalog.@&=) '{ "a" : [ { "$elemMatch" : { "b" : "M", "c" : { "$gt" : { "$numberInt" : "50" } } } }, { "$elemMatch" : { "c" : { "$numberInt" : "100" }, "d" : "Y" } } ] }'::documentdb_core.bson) (16 rows) @@ -1588,9 +1588,9 @@ EXPLAIN (COSTS OFF, ANALYZE ON, SUMMARY OFF, TIMING OFF) SELECT object_id, docum Sort Method: quicksort Memory: 27kB -> Bitmap Heap Scan on documents_1200_1200005 collection (actual rows=21 loops=1) Recheck Cond: (document OPERATOR(documentdb_api_catalog.@!=) '{ "a" : { "$numberInt" : "1" } }'::documentdb_core.bson) - Rows Removed by Index Recheck: 2 + Rows Removed by Index Recheck: 1 Heap Blocks: exact=1 - -> Bitmap Index Scan on queryoperator_b_a (actual rows=23 loops=1) + -> Bitmap Index Scan on queryoperator_b_a (actual rows=22 loops=1) Index Cond: (document OPERATOR(documentdb_api_catalog.@!=) '{ "a" : { "$numberInt" : "1" } }'::documentdb_core.bson) (16 rows) diff --git a/internal/pg_documentdb_distributed/src/test/regress/expected/bson_query_operator_tests_pg17_explain_index_composite.out b/internal/pg_documentdb_distributed/src/test/regress/expected/bson_query_operator_tests_pg17_explain_index_composite.out index 81dca470..a9b4e924 100644 --- a/internal/pg_documentdb_distributed/src/test/regress/expected/bson_query_operator_tests_pg17_explain_index_composite.out +++ b/internal/pg_documentdb_distributed/src/test/regress/expected/bson_query_operator_tests_pg17_explain_index_composite.out @@ -592,9 +592,9 @@ EXPLAIN (COSTS OFF, ANALYZE ON, SUMMARY OFF, TIMING OFF) SELECT object_id, docum Node: host=localhost port=58070 dbname=regression -> Bitmap Heap Scan on documents_1200_1200005 collection (actual rows=19 loops=1) Recheck Cond: (document OPERATOR(documentdb_api_catalog.@!=) '{ "a.b" : { "$numberInt" : "1" } }'::documentdb_core.bson) - Rows Removed by Index Recheck: 4 + Rows Removed by Index Recheck: 3 Heap Blocks: exact=1 - -> Bitmap Index Scan on queryoperator_ab (actual rows=23 loops=1) + -> Bitmap Index Scan on queryoperator_ab (actual rows=22 loops=1) Index Cond: (document OPERATOR(documentdb_api_catalog.@!=) '{ "a.b" : { "$numberInt" : "1" } }'::documentdb_core.bson) (13 rows) @@ -986,9 +986,9 @@ EXPLAIN (COSTS OFF, ANALYZE ON, SUMMARY OFF, TIMING OFF) SELECT object_id, docum Node: host=localhost port=58070 dbname=regression -> Bitmap Heap Scan on documents_1200_1200005 collection (actual rows=21 loops=1) Recheck Cond: (document OPERATOR(documentdb_api_catalog.@!=) '{ "a" : { "b" : { "$numberInt" : "1" } } }'::documentdb_core.bson) - Rows Removed by Index Recheck: 2 + Rows Removed by Index Recheck: 1 Heap Blocks: exact=1 - -> Bitmap Index Scan on queryoperator_b_a (actual rows=23 loops=1) + -> Bitmap Index Scan on queryoperator_b_a (actual rows=22 loops=1) Index Cond: (document OPERATOR(documentdb_api_catalog.@!=) '{ "a" : { "b" : { "$numberInt" : "1" } } }'::documentdb_core.bson) (13 rows) @@ -1267,9 +1267,9 @@ EXPLAIN (COSTS OFF, ANALYZE ON, SUMMARY OFF, TIMING OFF) SELECT object_id, docum Sort Method: quicksort Memory: 25kB -> Bitmap Heap Scan on documents_1200_1200005 collection (actual rows=2 loops=1) Recheck Cond: (document OPERATOR(documentdb_api_catalog.@&=) '{ "a" : [ { "$elemMatch" : { "b" : "M", "c" : { "$gt" : { "$numberInt" : "50" } } } }, { "$elemMatch" : { "c" : { "$numberInt" : "100" }, "d" : "Y" } } ] }'::documentdb_core.bson) - Rows Removed by Index Recheck: 9 + Rows Removed by Index Recheck: 1 Heap Blocks: exact=1 - -> Bitmap Index Scan on queryoperator_b_a (actual rows=11 loops=1) + -> Bitmap Index Scan on queryoperator_b_a (actual rows=3 loops=1) Index Cond: (document OPERATOR(documentdb_api_catalog.@&=) '{ "a" : [ { "$elemMatch" : { "b" : "M", "c" : { "$gt" : { "$numberInt" : "50" } } } }, { "$elemMatch" : { "c" : { "$numberInt" : "100" }, "d" : "Y" } } ] }'::documentdb_core.bson) (16 rows) @@ -1582,9 +1582,9 @@ EXPLAIN (COSTS OFF, ANALYZE ON, SUMMARY OFF, TIMING OFF) SELECT object_id, docum Sort Method: quicksort Memory: 27kB -> Bitmap Heap Scan on documents_1200_1200005 collection (actual rows=21 loops=1) Recheck Cond: (document OPERATOR(documentdb_api_catalog.@!=) '{ "a" : { "$numberInt" : "1" } }'::documentdb_core.bson) - Rows Removed by Index Recheck: 2 + Rows Removed by Index Recheck: 1 Heap Blocks: exact=1 - -> Bitmap Index Scan on queryoperator_b_a (actual rows=23 loops=1) + -> Bitmap Index Scan on queryoperator_b_a (actual rows=22 loops=1) Index Cond: (document OPERATOR(documentdb_api_catalog.@!=) '{ "a" : { "$numberInt" : "1" } }'::documentdb_core.bson) (16 rows) diff --git a/internal/pg_documentdb_distributed/src/test/regress/expected/commands_update_bulk.out b/internal/pg_documentdb_distributed/src/test/regress/expected/commands_update_bulk.out index 36296835..b2c3fb1a 100644 --- a/internal/pg_documentdb_distributed/src/test/regress/expected/commands_update_bulk.out +++ b/internal/pg_documentdb_distributed/src/test/regress/expected/commands_update_bulk.out @@ -1724,7 +1724,7 @@ DEBUG: Commiting intermediate state and reacquiring collection lock (1 row) -- should have updated 10 times -SELECT document FROM documentdb_api.collection('update_bulk', 'test_update_batch'); +SELECT document FROM documentdb_api.collection('update_bulk', 'test_update_batch') ORDER BY object_id; document --------------------------------------------------------------------- { "_id" : { "$numberInt" : "1" }, "a" : { "$numberInt" : "1" }, "b" : { "$numberInt" : "11" } } @@ -1771,7 +1771,7 @@ DEBUG: Commiting intermediate state and reacquiring collection lock (1 row) -- still increments -SELECT document FROM documentdb_api.collection('update_bulk', 'test_update_batch'); +SELECT document FROM documentdb_api.collection('update_bulk', 'test_update_batch') ORDER BY object_id; document --------------------------------------------------------------------- { "_id" : { "$numberInt" : "1" }, "a" : { "$numberInt" : "1" }, "b" : { "$numberInt" : "21" } } @@ -1817,7 +1817,7 @@ DEBUG: Commiting intermediate state and reacquiring collection lock (1 row) -- still increments -SELECT document FROM documentdb_api.collection('update_bulk', 'test_update_batch'); +SELECT document FROM documentdb_api.collection('update_bulk', 'test_update_batch') ORDER BY object_id; document --------------------------------------------------------------------- { "_id" : { "$numberInt" : "1" }, "a" : { "$numberInt" : "1" }, "b" : { "$numberInt" : "31" } } @@ -1864,7 +1864,7 @@ DEBUG: executing " SELECT documentdb_api_internal.update_worker($1, $2, $3, $4: (1 row) -- still increments -SELECT document FROM documentdb_api.collection('update_bulk', 'test_update_batch'); +SELECT document FROM documentdb_api.collection('update_bulk', 'test_update_batch') ORDER BY object_id; document --------------------------------------------------------------------- { "_id" : { "$numberInt" : "1" }, "a" : { "$numberInt" : "1" }, "b" : { "$numberInt" : "41" } } diff --git a/internal/pg_documentdb_distributed/src/test/regress/sql/commands_update_bulk.sql b/internal/pg_documentdb_distributed/src/test/regress/sql/commands_update_bulk.sql index 941915b3..1cb2dc3e 100644 --- a/internal/pg_documentdb_distributed/src/test/regress/sql/commands_update_bulk.sql +++ b/internal/pg_documentdb_distributed/src/test/regress/sql/commands_update_bulk.sql @@ -684,7 +684,7 @@ CALL documentdb_api.update_bulk('update_bulk', :'update_query2'); CALL documentdb_api.update_bulk('update_bulk', :'update_query3'); -- should have updated 10 times -SELECT document FROM documentdb_api.collection('update_bulk', 'test_update_batch'); +SELECT document FROM documentdb_api.collection('update_bulk', 'test_update_batch') ORDER BY object_id; -- reduce batch to 8 set documentdb.batchWriteSubTransactionCount to 8; @@ -699,7 +699,7 @@ CALL documentdb_api.update_bulk('update_bulk', :'update_query2'); CALL documentdb_api.update_bulk('update_bulk', :'update_query3'); -- still increments -SELECT document FROM documentdb_api.collection('update_bulk', 'test_update_batch'); +SELECT document FROM documentdb_api.collection('update_bulk', 'test_update_batch') ORDER BY object_id; -- now reduce to 3 set documentdb.batchWriteSubTransactionCount to 3; @@ -714,7 +714,7 @@ CALL documentdb_api.update_bulk('update_bulk', :'update_query2'); CALL documentdb_api.update_bulk('update_bulk', :'update_query3'); -- still increments -SELECT document FROM documentdb_api.collection('update_bulk', 'test_update_batch'); +SELECT document FROM documentdb_api.collection('update_bulk', 'test_update_batch') ORDER BY object_id; -- disable local writes set documentdb.useLocalExecutionShardQueries to off; @@ -725,4 +725,4 @@ CALL documentdb_api.update_bulk('update_bulk', :'update_query2'); CALL documentdb_api.update_bulk('update_bulk', :'update_query3'); -- still increments -SELECT document FROM documentdb_api.collection('update_bulk', 'test_update_batch'); +SELECT document FROM documentdb_api.collection('update_bulk', 'test_update_batch') ORDER BY object_id; diff --git a/pg_documentdb/include/opclass/bson_gin_composite_private.h b/pg_documentdb/include/opclass/bson_gin_composite_private.h index 986ae88f..2e579fed 100644 --- a/pg_documentdb/include/opclass/bson_gin_composite_private.h +++ b/pg_documentdb/include/opclass/bson_gin_composite_private.h @@ -23,6 +23,13 @@ typedef struct CompositeSingleBound bool isProcessedValueTruncated; } CompositeSingleBound; +typedef struct IndexRecheckArgs +{ + Pointer queryDatum; + + BsonIndexStrategy queryStrategy; +} IndexRecheckArgs; + typedef struct CompositeIndexBounds { CompositeSingleBound lowerBound; @@ -31,6 +38,9 @@ typedef struct CompositeIndexBounds bool isEqualityBound; bool requiresRuntimeRecheck; + + /* A list of IndexRecheckArgs that need recheck */ + List *indexRecheckFunctions; } CompositeIndexBounds; typedef struct PathScanKeyMap @@ -88,6 +98,10 @@ CreateCompositeIndexBoundsSet(int32_t numTerms, int32_t indexAttribute) } +bool IsValidRecheckForIndexValue(const bson_value_t *compareValue, + bool indexTermHasTruncation, + IndexRecheckArgs *recheckArgs); + bytea * BuildLowerBoundTermFromIndexBounds(CompositeQueryRunData *runData, IndexTermCreateMetadata *metadata, bool *hasInequalityMatch); diff --git a/pg_documentdb/include/opclass/bson_gin_index_term.h b/pg_documentdb/include/opclass/bson_gin_index_term.h index 17d5fa90..7c67ad5e 100644 --- a/pg_documentdb/include/opclass/bson_gin_index_term.h +++ b/pg_documentdb/include/opclass/bson_gin_index_term.h @@ -91,6 +91,19 @@ BsonCompressableIndexTermSerialized SerializeBsonIndexTermWithCompression( IndexTermCreateMetadata *indexMetadata); +BsonIndexTermSerialized SerializeCompositeBsonIndexTerm(pgbsonelement *indexElement, + const IndexTermCreateMetadata * + indexMetadata, bool + hasTruncatedPaths); +BsonCompressableIndexTermSerialized SerializeCompositeBsonIndexTermWithCompression( + pgbsonelement *indexElement, + const + IndexTermCreateMetadata + * + indexMetadata, + bool + hasTruncatedPaths); + Datum GenerateRootTerm(const IndexTermCreateMetadata *); Datum GenerateRootExistsTerm(const IndexTermCreateMetadata *); Datum GenerateRootNonExistsTerm(const IndexTermCreateMetadata *); diff --git a/pg_documentdb/src/commands/create_indexes.c b/pg_documentdb/src/commands/create_indexes.c index 7bc8cd2b..384d9611 100644 --- a/pg_documentdb/src/commands/create_indexes.c +++ b/pg_documentdb/src/commands/create_indexes.c @@ -187,6 +187,7 @@ extern bool SkipFailOnCollation; extern bool DisableStatisticsForUniqueColumns; extern bool EnableNewCompositeIndexOpclass; extern bool ForceWildcardReducedTerm; +extern bool DefaultUseCompositeOpClass; char *AlternateIndexHandler = NULL; @@ -4525,11 +4526,11 @@ CreatePostgresIndexCreationCmd(uint64 collectionId, IndexDef *indexDef, int inde enableLargeIndexKeys = true; } - bool enableNewIndexOpClass = false; - if (EnableNewCompositeIndexOpclass && - indexDef->enableCompositeTerm == BoolIndexOption_True) + bool enableNewIndexOpClass = EnableNewCompositeIndexOpclass && + DefaultUseCompositeOpClass; + if (indexDef->enableCompositeTerm != BoolIndexOption_Undefined) { - enableNewIndexOpClass = true; + enableNewIndexOpClass = indexDef->enableCompositeTerm == BoolIndexOption_True; } bool supportsAlternateIndexHandler = false; @@ -4667,11 +4668,11 @@ CreatePostgresIndexCreationCmd(uint64 collectionId, IndexDef *indexDef, int inde BoolIndexOption_False; } - bool enableNewIndexOpClass = false; - if (EnableNewCompositeIndexOpclass && - indexDef->enableCompositeTerm == BoolIndexOption_True) + bool enableNewIndexOpClass = EnableNewCompositeIndexOpclass && + DefaultUseCompositeOpClass; + if (indexDef->enableCompositeTerm != BoolIndexOption_Undefined) { - enableNewIndexOpClass = true; + enableNewIndexOpClass = indexDef->enableCompositeTerm == BoolIndexOption_True; } /* Currently alternate index handler is only supported for single path simple indexes, this will be updated as we add more support. */ diff --git a/pg_documentdb/src/configs/testing_configs.c b/pg_documentdb/src/configs/testing_configs.c index 4bf42e7a..8243c89c 100644 --- a/pg_documentdb/src/configs/testing_configs.c +++ b/pg_documentdb/src/configs/testing_configs.c @@ -48,6 +48,9 @@ bool ForceIndexTermTruncation = DEFAULT_FORCE_INDEX_TERM_TRUNCATION; #define DEFAULT_ENABLE_NEW_COMPOSITE_INDEX_OPCLASS false bool EnableNewCompositeIndexOpclass = DEFAULT_ENABLE_NEW_COMPOSITE_INDEX_OPCLASS; +#define DEFAULT_USE_NEW_COMPOSITE_INDEX_OPCLASS false +bool DefaultUseCompositeOpClass = DEFAULT_USE_NEW_COMPOSITE_INDEX_OPCLASS; + #define DEFAULT_ENABLE_INDEX_ORDERBY_PUSHDOWN false bool EnableIndexOrderbyPushdown = DEFAULT_ENABLE_INDEX_ORDERBY_PUSHDOWN; @@ -157,6 +160,13 @@ InitializeTestConfigurations(const char *prefix, const char *newGucPrefix) NULL, &EnableNewCompositeIndexOpclass, DEFAULT_ENABLE_NEW_COMPOSITE_INDEX_OPCLASS, PGC_USERSET, 0, NULL, NULL, NULL); + DefineCustomBoolVariable( + psprintf("%s.defaultUseCompositeOpClass", newGucPrefix), + gettext_noop( + "Whether to enable the new experimental composite index opclass for default index creates"), + NULL, &DefaultUseCompositeOpClass, DEFAULT_USE_NEW_COMPOSITE_INDEX_OPCLASS, + PGC_USERSET, 0, NULL, NULL, NULL); + DefineCustomBoolVariable( psprintf("%s.enableIndexOrderbyPushdown", newGucPrefix), gettext_noop( diff --git a/pg_documentdb/src/opclass/bson_gin_composite_core.c b/pg_documentdb/src/opclass/bson_gin_composite_core.c index 43f5078a..e698d595 100644 --- a/pg_documentdb/src/opclass/bson_gin_composite_core.c +++ b/pg_documentdb/src/opclass/bson_gin_composite_core.c @@ -39,6 +39,7 @@ #include "utils/documentdb_errors.h" #include "metadata/metadata_cache.h" #include "collation/collation.h" + #include "query/bson_dollar_operators.h" #include "opclass/bson_gin_composite_private.h" static void ProcessBoundForQuery(CompositeSingleBound *bound, const @@ -65,7 +66,8 @@ static void AddMultiBoundaryForDollarType(int32_t indexAttribute, static void AddMultiBoundaryForDollarNotIn(int32_t indexAttribute, pgbsonelement *queryElement, VariableIndexBounds *indexBounds); -static void AddMultiBoundaryForBitwiseOperator(int32_t indexAttribute, +static void AddMultiBoundaryForBitwiseOperator(BsonIndexStrategy strategy, + int32_t indexAttribute, pgbsonelement *queryElement, VariableIndexBounds *indexBounds); static void AddMultiBoundaryForNotGreater(int32_t indexAttribute, @@ -78,7 +80,11 @@ static void AddMultiBoundaryForNotLess(int32_t indexAttribute, static void AddMultiBoundaryForDollarRange(int32_t indexAttribute, pgbsonelement *queryElement, VariableIndexBounds *indexBounds); - +static CompositeIndexBoundsSet * AddMultiBoundaryForDollarRegex(int32_t indexAttribute, + pgbsonelement * + queryElement, + VariableIndexBounds * + indexBounds); inline static CompositeSingleBound GetTypeLowerBound(bson_type_t type) @@ -109,12 +115,15 @@ BuildLowerBoundTermFromIndexBounds(CompositeQueryRunData *runData, PgbsonWriterInit(&lower_bound_writer); PgbsonWriterStartArray(&lower_bound_writer, "$", 1, &lower_bound_array_writer); + bool hasTruncation = false; for (int i = 0; i < runData->numIndexPaths; i++) { runData->metaInfo->requiresRuntimeRecheck = runData->metaInfo->requiresRuntimeRecheck || runData->indexBounds[i]. requiresRuntimeRecheck; + hasTruncation = hasTruncation || + runData->indexBounds[i].lowerBound.isProcessedValueTruncated; /* If both lower and upper bound match it's equality */ if (runData->indexBounds[i].lowerBound.bound.value_type != BSON_TYPE_EOD && @@ -156,7 +165,9 @@ BuildLowerBoundTermFromIndexBounds(CompositeQueryRunData *runData, lower_bound_element.pathLength = 1; lower_bound_element.bsonValue = PgbsonArrayWriterGetValue(&lower_bound_array_writer); - BsonIndexTermSerialized ser = SerializeBsonIndexTerm(&lower_bound_element, metadata); + BsonIndexTermSerialized ser = SerializeCompositeBsonIndexTerm(&lower_bound_element, + metadata, + hasTruncation); return ser.indexTermVal; } @@ -222,6 +233,14 @@ UpdateRunDataForVariableBounds(CompositeQueryRunData *runData, &bound->upperBound); } + if (bound->indexRecheckFunctions != NIL) + { + runData->indexBounds[set->indexAttribute].indexRecheckFunctions = + list_concat( + runData->indexBounds[set->indexAttribute].indexRecheckFunctions, + bound->indexRecheckFunctions); + } + runData->metaInfo->requiresRuntimeRecheck = runData->metaInfo->requiresRuntimeRecheck || bound->requiresRuntimeRecheck; @@ -260,6 +279,15 @@ MergeSingleVariableBounds(VariableIndexBounds *variableBounds, runData->indexBounds[set->indexAttribute].requiresRuntimeRecheck || set->bounds->requiresRuntimeRecheck; + if (set->bounds->indexRecheckFunctions != NIL) + { + runData->indexBounds[set->indexAttribute].indexRecheckFunctions = + list_concat( + runData->indexBounds[set->indexAttribute].indexRecheckFunctions, + set->bounds->indexRecheckFunctions); + } + + /* Postgres requires that we don't use cell or anything in foreach after * calling delete. explicity add a continue to match that contract. */ @@ -334,7 +362,6 @@ ParseOperatorStrategy(const char **indexPaths, int32_t numPaths, case BSON_INDEX_STRATEGY_DOLLAR_GREATER: case BSON_INDEX_STRATEGY_DOLLAR_LESS: case BSON_INDEX_STRATEGY_DOLLAR_LESS_EQUAL: - case BSON_INDEX_STRATEGY_DOLLAR_REGEX: case BSON_INDEX_STRATEGY_DOLLAR_EXISTS: case BSON_INDEX_STRATEGY_DOLLAR_ELEMMATCH: case BSON_INDEX_STRATEGY_DOLLAR_SIZE: @@ -350,6 +377,26 @@ ParseOperatorStrategy(const char **indexPaths, int32_t numPaths, break; } + case BSON_INDEX_STRATEGY_DOLLAR_REGEX: + { + if (queryElement->bsonValue.value_type == BSON_TYPE_REGEX) + { + AddMultiBoundaryForDollarRegex(i, queryElement, indexBounds); + } + else + { + /* Regex with a string - single strategy */ + int numterms = 1; + CompositeIndexBoundsSet *set = CreateCompositeIndexBoundsSet(numterms, i); + SetSingleRangeBoundsFromStrategy(queryElement, + queryStrategy, set->bounds); + indexBounds->variableBoundsList = lappend(indexBounds->variableBoundsList, + set); + } + + break; + } + case BSON_INDEX_STRATEGY_DOLLAR_RANGE: { AddMultiBoundaryForDollarRange(i, queryElement, indexBounds); @@ -398,7 +445,8 @@ ParseOperatorStrategy(const char **indexPaths, int32_t numPaths, case BSON_INDEX_STRATEGY_DOLLAR_BITS_ALL_SET: case BSON_INDEX_STRATEGY_DOLLAR_BITS_ANY_SET: { - AddMultiBoundaryForBitwiseOperator(i, queryElement, indexBounds); + AddMultiBoundaryForBitwiseOperator(queryStrategy, i, queryElement, + indexBounds); break; } @@ -454,6 +502,211 @@ ParseOperatorStrategy(const char **indexPaths, int32_t numPaths, } +bool +IsValidRecheckForIndexValue(const bson_value_t *compareValue, + bool hasTruncation, + IndexRecheckArgs *recheckArgs) +{ + switch (recheckArgs->queryStrategy) + { + case BSON_INDEX_STRATEGY_DOLLAR_REGEX: + { + if (hasTruncation) + { + /* don't bother, let the runtime check on this */ + return true; + } + + RegexData *regexData = (RegexData *) recheckArgs->queryDatum; + return CompareRegexTextMatch(compareValue, regexData); + } + + case BSON_INDEX_STRATEGY_DOLLAR_EXISTS: + { + bool *exists = (bool *) recheckArgs->queryDatum; + if (!*exists) + { + /* exists: false, check that it's not undefined */ + return compareValue->value_type == BSON_TYPE_UNDEFINED; + } + else + { + /* exists true, matches all values except that */ + return compareValue->value_type != BSON_TYPE_UNDEFINED; + } + } + + case BSON_INDEX_STRATEGY_DOLLAR_ELEMMATCH: + { + if (hasTruncation) + { + /* don't bother, let the runtime check on this */ + return true; + } + + bool compareResult = false; + BsonElemMatchIndexExprState *exprState = + (BsonElemMatchIndexExprState *) recheckArgs->queryDatum; + if (exprState->isEmptyExpression) + { + compareResult = false; + bson_iter_t arrayIter; + BsonValueInitIterator(compareValue, &arrayIter); + while (bson_iter_next(&arrayIter)) + { + if (bson_iter_type(&arrayIter) == BSON_TYPE_DOCUMENT || + bson_iter_type(&arrayIter) == BSON_TYPE_ARRAY) + { + compareResult = true; + break; + } + } + } + else + { + compareResult = EvalBooleanExpressionAgainstArray(exprState->expression, + compareValue); + } + + return compareResult; + } + + case BSON_INDEX_STRATEGY_DOLLAR_SIZE: + { + int64_t arraySize = *(int64_t *) recheckArgs->queryDatum; + bson_iter_t arrayIter; + bson_iter_init_from_data(&arrayIter, + compareValue->value.v_doc.data, + compareValue->value.v_doc.data_len); + int64_t actualArraySize = 0; + while (bson_iter_next(&arrayIter) && actualArraySize <= arraySize) + { + actualArraySize++; + } + + if (hasTruncation && actualArraySize < arraySize) + { + /* There may be more terms that have been truncated out + * let runtime recheck handle this + */ + return true; + } + + return actualArraySize == arraySize; + } + + case BSON_INDEX_STRATEGY_DOLLAR_MOD: + { + bson_value_t *modQuery = (bson_value_t *) recheckArgs->queryDatum; + return CompareModOperator(compareValue, modQuery); + } + + case BSON_INDEX_STRATEGY_DOLLAR_NOT_EQUAL: + { + bson_value_t *notEqualQuery = (bson_value_t *) recheckArgs->queryDatum; + + if (hasTruncation) + { + /* don't bother, let the runtime check on this */ + return true; + } + + return !BsonValueEquals(compareValue, notEqualQuery); + } + + case BSON_INDEX_STRATEGY_DOLLAR_BITS_ALL_CLEAR: + { + bson_value_t *bitsQuery = (bson_value_t *) recheckArgs->queryDatum; + if (hasTruncation) + { + /* don't bother, let the runtime check on this */ + return true; + } + + return CompareBitwiseOperator(compareValue, + bitsQuery, CompareArrayForBitsAllClear); + } + + case BSON_INDEX_STRATEGY_DOLLAR_BITS_ANY_CLEAR: + { + bson_value_t *bitsQuery = (bson_value_t *) recheckArgs->queryDatum; + if (hasTruncation) + { + /* don't bother, let the runtime check on this */ + return true; + } + + return CompareBitwiseOperator(compareValue, + bitsQuery, CompareArrayForBitsAnyClear); + } + + case BSON_INDEX_STRATEGY_DOLLAR_BITS_ALL_SET: + { + bson_value_t *bitsQuery = (bson_value_t *) recheckArgs->queryDatum; + if (hasTruncation) + { + /* don't bother, let the runtime check on this */ + return true; + } + + return CompareBitwiseOperator(compareValue, + bitsQuery, CompareArrayForBitsAllSet); + } + + case BSON_INDEX_STRATEGY_DOLLAR_BITS_ANY_SET: + { + bson_value_t *bitsQuery = (bson_value_t *) recheckArgs->queryDatum; + if (hasTruncation) + { + /* don't bother, let the runtime check on this */ + return true; + } + + return CompareBitwiseOperator(compareValue, + bitsQuery, CompareArrayForBitsAnySet); + } + + case BSON_INDEX_STRATEGY_DOLLAR_EQUAL: + case BSON_INDEX_STRATEGY_DOLLAR_GREATER_EQUAL: + case BSON_INDEX_STRATEGY_DOLLAR_GREATER: + case BSON_INDEX_STRATEGY_DOLLAR_LESS: + case BSON_INDEX_STRATEGY_DOLLAR_LESS_EQUAL: + case BSON_INDEX_STRATEGY_DOLLAR_RANGE: + case BSON_INDEX_STRATEGY_DOLLAR_TYPE: + case BSON_INDEX_STRATEGY_DOLLAR_ALL: + case BSON_INDEX_STRATEGY_DOLLAR_IN: + case BSON_INDEX_STRATEGY_DOLLAR_NOT_IN: + case BSON_INDEX_STRATEGY_DOLLAR_NOT_GT: + case BSON_INDEX_STRATEGY_DOLLAR_NOT_GTE: + case BSON_INDEX_STRATEGY_DOLLAR_NOT_LT: + case BSON_INDEX_STRATEGY_DOLLAR_NOT_LTE: + case BSON_INDEX_STRATEGY_DOLLAR_ORDERBY: + { + /* No recheck */ + ereport(ERROR, (errmsg( + "Unexpected - should not have Index Recheck function for %d", + recheckArgs->queryStrategy))); + return false; + } + + case BSON_INDEX_STRATEGY_DOLLAR_TEXT: + case BSON_INDEX_STRATEGY_DOLLAR_GEOINTERSECTS: + case BSON_INDEX_STRATEGY_DOLLAR_GEOWITHIN: + case BSON_INDEX_STRATEGY_GEONEAR: + case BSON_INDEX_STRATEGY_GEONEAR_RANGE: + case BSON_INDEX_STRATEGY_COMPOSITE_QUERY: + case BSON_INDEX_STRATEGY_UNIQUE_EQUAL: + default: + { + ereport(ERROR, (errcode(ERRCODE_DOCUMENTDB_INTERNALERROR), errmsg( + "Unsupported strategy for composite index: %d", + recheckArgs->queryStrategy))); + return false; + } + } +} + + static void ProcessBoundForQuery(CompositeSingleBound *bound, const IndexTermCreateMetadata *metadata) { @@ -563,7 +816,6 @@ SetBoundsExistsTrue(CompositeIndexBounds *queryBounds) bounds.isBoundInclusive = true; SetUpperBound(&queryBounds->upperBound, &bounds); - /* TODO: Replace this with index eval function */ queryBounds->requiresRuntimeRecheck = true; } @@ -629,8 +881,16 @@ SetSingleRangeBoundsFromStrategy(pgbsonelement *queryElement, SetLowerBound(&queryBounds->lowerBound, &bounds); /* Apply type bracketing */ - bounds = GetTypeUpperBound(queryElement->bsonValue.value_type); - SetUpperBound(&queryBounds->upperBound, &bounds); + if (queryElement->bsonValue.value_type == BSON_TYPE_MINKEY) + { + bounds = GetTypeUpperBound(BSON_TYPE_MAXKEY); + SetUpperBound(&queryBounds->upperBound, &bounds); + } + else + { + bounds = GetTypeUpperBound(queryElement->bsonValue.value_type); + SetUpperBound(&queryBounds->upperBound, &bounds); + } break; } @@ -644,8 +904,16 @@ SetSingleRangeBoundsFromStrategy(pgbsonelement *queryElement, SetUpperBound(&queryBounds->upperBound, &bounds); /* Apply type bracketing */ - bounds = GetTypeLowerBound(queryElement->bsonValue.value_type); - SetLowerBound(&queryBounds->lowerBound, &bounds); + if (queryElement->bsonValue.value_type == BSON_TYPE_MAXKEY) + { + bounds = GetTypeLowerBound(BSON_TYPE_MINKEY); + SetLowerBound(&queryBounds->lowerBound, &bounds); + } + else + { + bounds = GetTypeLowerBound(queryElement->bsonValue.value_type); + SetLowerBound(&queryBounds->lowerBound, &bounds); + } if (queryElement->bsonValue.value_type == BSON_TYPE_NULL) { @@ -663,8 +931,26 @@ SetSingleRangeBoundsFromStrategy(pgbsonelement *queryElement, bounds = GetTypeUpperBound(BSON_TYPE_UTF8); SetUpperBound(&queryBounds->upperBound, &bounds); - /* TODO: Replace this with index eval function */ - queryBounds->requiresRuntimeRecheck = true; + RegexData *regexData = (RegexData *) palloc0(sizeof(RegexData)); + if (queryElement->bsonValue.value_type == BSON_TYPE_REGEX) + { + regexData->regex = queryElement->bsonValue.value.v_regex.regex; + regexData->options = queryElement->bsonValue.value.v_regex.options; + } + else + { + regexData->regex = queryElement->bsonValue.value.v_utf8.str; + regexData->options = NULL; + } + + regexData->pcreData = RegexCompile(regexData->regex, + regexData->options); + + IndexRecheckArgs *args = palloc0(sizeof(IndexRecheckArgs)); + args->queryDatum = (Pointer) regexData; + args->queryStrategy = BSON_INDEX_STRATEGY_DOLLAR_REGEX; + queryBounds->indexRecheckFunctions = + lappend(queryBounds->indexRecheckFunctions, args); break; } @@ -684,7 +970,7 @@ SetSingleRangeBoundsFromStrategy(pgbsonelement *queryElement, SetLowerBound(&queryBounds->lowerBound, &equalsBounds); SetUpperBound(&queryBounds->upperBound, &equalsBounds); - /* TODO: Replace this with index eval function */ + /* TODO: Should we replace this with index eval function? */ queryBounds->requiresRuntimeRecheck = true; } @@ -699,8 +985,18 @@ SetSingleRangeBoundsFromStrategy(pgbsonelement *queryElement, bounds = GetTypeUpperBound(BSON_TYPE_ARRAY); SetUpperBound(&queryBounds->upperBound, &bounds); - /* TODO: Replace this with index eval function */ - queryBounds->requiresRuntimeRecheck = true; + BsonElemMatchIndexExprState *state = + (BsonElemMatchIndexExprState *) palloc0( + sizeof(BsonElemMatchIndexExprState)); + state->expression = GetExpressionEvalState( + &queryElement->bsonValue, + CurrentMemoryContext); + state->isEmptyExpression = IsBsonValueEmptyDocument(&queryElement->bsonValue); + IndexRecheckArgs *args = palloc0(sizeof(IndexRecheckArgs)); + args->queryDatum = (Pointer) state; + args->queryStrategy = BSON_INDEX_STRATEGY_DOLLAR_ELEMMATCH; + queryBounds->indexRecheckFunctions = + lappend(queryBounds->indexRecheckFunctions, args); break; } @@ -712,7 +1008,15 @@ SetSingleRangeBoundsFromStrategy(pgbsonelement *queryElement, bounds = GetTypeUpperBound(BSON_TYPE_ARRAY); SetUpperBound(&queryBounds->upperBound, &bounds); - /* TODO: Replace this with index eval function */ + int64_t *size = palloc(sizeof(int64_t)); + *size = BsonValueAsInt64(&queryElement->bsonValue); + IndexRecheckArgs *args = palloc0(sizeof(IndexRecheckArgs)); + args->queryDatum = (Pointer) size; + args->queryStrategy = BSON_INDEX_STRATEGY_DOLLAR_SIZE; + queryBounds->indexRecheckFunctions = + lappend(queryBounds->indexRecheckFunctions, args); + + /* Needs a runtime recheck since we don't know about nested arrays of arrays */ queryBounds->requiresRuntimeRecheck = true; break; } @@ -725,8 +1029,13 @@ SetSingleRangeBoundsFromStrategy(pgbsonelement *queryElement, bounds = GetTypeUpperBound(BSON_TYPE_DOUBLE); SetUpperBound(&queryBounds->upperBound, &bounds); - /* TODO: Replace this with index eval function */ - queryBounds->requiresRuntimeRecheck = true; + bson_value_t *modFilter = palloc(sizeof(bson_value_t)); + *modFilter = queryElement->bsonValue; + IndexRecheckArgs *args = palloc0(sizeof(IndexRecheckArgs)); + args->queryDatum = (Pointer) modFilter; + args->queryStrategy = BSON_INDEX_STRATEGY_DOLLAR_MOD; + queryBounds->indexRecheckFunctions = + lappend(queryBounds->indexRecheckFunctions, args); break; } @@ -765,6 +1074,7 @@ SetSingleRangeBoundsFromStrategy(pgbsonelement *queryElement, bounds = GetTypeUpperBound(typeValue); SetUpperBound(&queryBounds->upperBound, &bounds); + /* TODO: Why does this need a runtime recheck */ queryBounds->requiresRuntimeRecheck = true; break; @@ -804,7 +1114,19 @@ SetSingleRangeBoundsFromStrategy(pgbsonelement *queryElement, bounds = GetTypeUpperBound(BSON_TYPE_MAXKEY); SetUpperBound(&queryBounds->upperBound, &bounds); - /* TODO: Replace this with index eval function */ + bson_value_t *equalsValue = palloc0(sizeof(bson_value_t)); + *equalsValue = queryElement->bsonValue; + IndexRecheckArgs *args = palloc0(sizeof(IndexRecheckArgs)); + args->queryDatum = (Pointer) equalsValue; + args->queryStrategy = BSON_INDEX_STRATEGY_DOLLAR_NOT_EQUAL; + queryBounds->indexRecheckFunctions = + lappend(queryBounds->indexRecheckFunctions, args); + + /* + * For $ne (and other negation scenarios), we need to revalidate + * in the runtime since you could have a: [ 1, 2, 3 ] + * a != 2 will match for the 3rd term. + */ queryBounds->requiresRuntimeRecheck = true; break; } @@ -898,7 +1220,7 @@ AddMultiBoundaryForDollarAll(int32_t indexAttribute, &innerDocumentElement) && strcmp(innerDocumentElement.path, "$elemMatch") == 0) { - SetSingleRangeBoundsFromStrategy(&element, + SetSingleRangeBoundsFromStrategy(&innerDocumentElement, BSON_INDEX_STRATEGY_DOLLAR_ELEMMATCH, &set->bounds[index]); } @@ -909,7 +1231,7 @@ AddMultiBoundaryForDollarAll(int32_t indexAttribute, } /* TODO: Since we represet $all as a $in at the index layer, we need runtime recheck */ - set->bounds[index].requiresRuntimeRecheck = true; + set->bounds[index].requiresRuntimeRecheck = allArraySize > 1; index++; } indexBounds->variableBoundsList = lappend(indexBounds->variableBoundsList, set); @@ -944,6 +1266,12 @@ AddMultiBoundaryForDollarIn(int32_t indexAttribute, } inArraySize++; + if (arrayValue->value_type == BSON_TYPE_REGEX) + { + /* Regex has 2 boundaries */ + inArraySize++; + } + arrayHasNull = arrayHasNull || arrayValue->value_type == BSON_TYPE_NULL; } @@ -969,16 +1297,19 @@ AddMultiBoundaryForDollarIn(int32_t indexAttribute, if (element.bsonValue.value_type == BSON_TYPE_REGEX) { - SetSingleRangeBoundsFromStrategy(&element, BSON_INDEX_STRATEGY_DOLLAR_REGEX, - &set->bounds[index]); + CompositeIndexBoundsSet *regexSet = AddMultiBoundaryForDollarRegex(index, + &element, + NULL); + set->bounds[index] = regexSet->bounds[0]; + set->bounds[index + 1] = regexSet->bounds[1]; + index += 2; } else { SetSingleRangeBoundsFromStrategy(&element, BSON_INDEX_STRATEGY_DOLLAR_EQUAL, &set->bounds[index]); + index++; } - - index++; } indexBounds->variableBoundsList = lappend(indexBounds->variableBoundsList, set); } @@ -1065,23 +1396,61 @@ AddMultiBoundaryForDollarNotIn(int32_t indexAttribute, pgbsonelement *queryEleme } +static CompositeIndexBoundsSet * +AddMultiBoundaryForDollarRegex(int32_t indexAttribute, pgbsonelement *queryElement, + VariableIndexBounds *indexBounds) +{ + CompositeIndexBoundsSet *set = CreateCompositeIndexBoundsSet(2, + indexAttribute); + + SetSingleRangeBoundsFromStrategy(queryElement, + BSON_INDEX_STRATEGY_DOLLAR_REGEX, &set->bounds[0]); + + /* The second bound is an exact match on the $regex itself */ + CompositeSingleBound equalsBounds = { 0 }; + equalsBounds.bound = queryElement->bsonValue; + equalsBounds.isBoundInclusive = true; + SetLowerBound(&set->bounds[1].lowerBound, &equalsBounds); + SetUpperBound(&set->bounds[1].upperBound, &equalsBounds); + + if (indexBounds != NULL) + { + indexBounds->variableBoundsList = lappend(indexBounds->variableBoundsList, set); + } + + return set; +} + + static void -AddMultiBoundaryForBitwiseOperator(int32_t indexAttribute, pgbsonelement *queryElement, +AddMultiBoundaryForBitwiseOperator(BsonIndexStrategy strategy, + int32_t indexAttribute, pgbsonelement *queryElement, VariableIndexBounds *indexBounds) { CompositeIndexBoundsSet *set = CreateCompositeIndexBoundsSet(2, indexAttribute); + bson_value_t *modFilter = palloc(sizeof(bson_value_t)); + *modFilter = queryElement->bsonValue; + IndexRecheckArgs *args = palloc0(sizeof(IndexRecheckArgs)); + args->queryDatum = (Pointer) modFilter; + args->queryStrategy = strategy; + /* First bound is all numbers */ CompositeSingleBound bound = GetTypeLowerBound(BSON_TYPE_DOUBLE); SetLowerBound(&set->bounds[0].lowerBound, &bound); bound = GetTypeUpperBound(BSON_TYPE_DOUBLE); SetUpperBound(&set->bounds[0].upperBound, &bound); + set->bounds[0].indexRecheckFunctions = + lappend(set->bounds[0].indexRecheckFunctions, args); + /* Second bound is all binary */ bound = GetTypeLowerBound(BSON_TYPE_BINARY); SetLowerBound(&set->bounds[1].lowerBound, &bound); bound = GetTypeUpperBound(BSON_TYPE_BINARY); SetUpperBound(&set->bounds[1].upperBound, &bound); + set->bounds[1].indexRecheckFunctions = + lappend(set->bounds[1].indexRecheckFunctions, args); indexBounds->variableBoundsList = lappend(indexBounds->variableBoundsList, set); } @@ -1115,6 +1484,12 @@ AddMultiBoundaryForNotGreater(int32_t indexAttribute, pgbsonelement *queryElemen bound = GetTypeUpperBound(BSON_TYPE_MAXKEY); SetUpperBound(&set->bounds[1].upperBound, &bound); + /* + * Not functions need recheck for arrays ( given "a": [ 1, 2 ]: + * a not gt 1 will match on the first element) + */ + set->bounds[0].requiresRuntimeRecheck = true; + set->bounds[1].requiresRuntimeRecheck = true; indexBounds->variableBoundsList = lappend(indexBounds->variableBoundsList, set); } @@ -1147,6 +1522,12 @@ AddMultiBoundaryForNotLess(int32_t indexAttribute, pgbsonelement *queryElement, bound = GetTypeUpperBound(BSON_TYPE_MAXKEY); SetUpperBound(&set->bounds[1].upperBound, &bound); + /* + * Not functions need recheck for arrays ( given "a": [ 1, 2 ]: + * a not lt 2 will match on the first element) + */ + set->bounds[0].requiresRuntimeRecheck = true; + set->bounds[1].requiresRuntimeRecheck = true; indexBounds->variableBoundsList = lappend(indexBounds->variableBoundsList, set); } diff --git a/pg_documentdb/src/opclass/bson_gin_composite_entrypoint.c b/pg_documentdb/src/opclass/bson_gin_composite_entrypoint.c index bcaa78ed..133ee39c 100644 --- a/pg_documentdb/src/opclass/bson_gin_composite_entrypoint.c +++ b/pg_documentdb/src/opclass/bson_gin_composite_entrypoint.c @@ -70,6 +70,9 @@ static bytea * BuildTermForBounds(CompositeQueryRunData *runData, IndexTermCreateMetadata *compositeMetadata, bool *partialMatch); static bool ParseCompositeQuerySpec(pgbson *querySpec, pgbsonelement *singleElement); +static int32_t RunCompareOnBounds(CompositeIndexBounds *bounds, const + bson_value_t *compareValue, + bool hasEqualityPrefix, bool *priorMatchesEquality); inline static IndexTermCreateMetadata @@ -367,87 +370,114 @@ gin_bson_composite_path_compare_partial(PG_FUNCTION_ARGS) hasEqualityPrefix = hasEqualityPrefix && priorMatchesEquality; const bson_value_t *compareValue = bson_iter_value(&compareIter); - if (runData->indexBounds[compareIndex].isEqualityBound) + int32_t compareInBounds = RunCompareOnBounds( + &runData->indexBounds[compareIndex], + compareValue, + hasEqualityPrefix, + &priorMatchesEquality); + if (compareInBounds != 0) { - /* We have an equality on a term - if not equal - we can bail */ - if (!BsonValueEquals(compareValue, - &runData->indexBounds[compareIndex].lowerBound. - processedBoundValue)) - { - /* Stop the search */ - return hasEqualityPrefix ? 1 : -1; - } - - continue; + return compareInBounds; } - priorMatchesEquality = false; - if (runData->indexBounds[compareIndex].lowerBound.bound.value_type != - BSON_TYPE_EOD) + if (runData->indexBounds[compareIndex].indexRecheckFunctions != NIL) { - bool isComparisonValid = false; - int32_t compareBounds = CompareBsonValueAndType( - compareValue, - &runData->indexBounds[compareIndex].lowerBound.processedBoundValue, - &isComparisonValid); - if (!isComparisonValid) + ListCell *recheckFuncs; + foreach(recheckFuncs, + runData->indexBounds[compareIndex].indexRecheckFunctions) { - return -1; - } - - if (compareBounds == 0) - { - if (!runData->indexBounds[compareIndex].lowerBound.isBoundInclusive) + IndexRecheckArgs *recheckStrategy = lfirst(recheckFuncs); + if (!IsValidRecheckForIndexValue(compareValue, + compareTerm.isIndexTermTruncated, + recheckStrategy)) { - /* for truncated you can't be sure - let the runtime re-evaluate */ - return runData->indexBounds[compareIndex].lowerBound. - isProcessedValueTruncated ? 0 : -1; - } - else - { - continue; + return -1; } } + } + } - if (compareBounds < 0) + return 0; +} + + +/* + * When running compare_partial, we first check if the current term matches + * based purely on the lower and upper bounds. + * Returns 0 if true, -1/1 if we need to bail. + * If we do have a match, further checks can be made for scenarios like + * Index rechecks. + */ +static int32_t +RunCompareOnBounds(CompositeIndexBounds *bounds, const bson_value_t *compareValue, + bool hasEqualityPrefix, bool *priorMatchesEquality) +{ + if (bounds->isEqualityBound) + { + /* We have an equality on a term - if not equal - we can bail */ + if (!BsonValueEquals(compareValue, + &bounds->lowerBound. + processedBoundValue)) + { + /* Stop the search */ + return hasEqualityPrefix ? 1 : -1; + } + + return 0; + } + + *priorMatchesEquality = false; + if (bounds->lowerBound.bound.value_type != BSON_TYPE_EOD) + { + bool isComparisonValid = false; + int32_t compareBounds = CompareBsonValueAndType( + compareValue, + &bounds->lowerBound.processedBoundValue, + &isComparisonValid); + if (!isComparisonValid) + { + return -1; + } + + if (compareBounds == 0) + { + if (!bounds->lowerBound.isBoundInclusive && + !bounds->lowerBound.isProcessedValueTruncated) { - /* compareValue < lowerBound, not a match */ return -1; } } - - if (runData->indexBounds[compareIndex].upperBound.bound.value_type != - BSON_TYPE_EOD) + else if (compareBounds < 0) { - bool isComparisonValid = false; - int32_t compareBounds = CompareBsonValueAndType( - compareValue, - &runData->indexBounds[compareIndex].upperBound.processedBoundValue, - &isComparisonValid); - if (!isComparisonValid) + /* compareValue < lowerBound, not a match */ + return -1; + } + } + + if (bounds->upperBound.bound.value_type != BSON_TYPE_EOD) + { + bool isComparisonValid = false; + int32_t compareBounds = CompareBsonValueAndType( + compareValue, + &bounds->upperBound.processedBoundValue, + &isComparisonValid); + if (!isComparisonValid) + { + return -1; + } + + if (compareBounds == 0) + { + if (!bounds->upperBound.isBoundInclusive && + !bounds->upperBound.isProcessedValueTruncated) { return -1; } - - if (compareBounds == 0) - { - if (!runData->indexBounds[compareIndex].upperBound.isBoundInclusive) - { - /* for truncated you can't be sure - let the runtime re-evaluate */ - return runData->indexBounds[compareIndex].upperBound. - isProcessedValueTruncated ? 0 : -1; - } - else - { - continue; - } - } - - if (compareBounds > 0) - { - /* Can stop searching */ - return hasEqualityPrefix ? 1 : -1; - } + } + else if (compareBounds > 0) + { + /* Can stop searching */ + return hasEqualityPrefix ? 1 : -1; } } @@ -598,9 +628,7 @@ gin_bson_get_composite_path_generated_terms(PG_FUNCTION_ARGS) if (context->index < context->totalTermCount) { Datum next = context->terms.entries[context->index++]; - BsonIndexTerm term = { - false, false, { 0 } - }; + BsonIndexTerm term = { 0 }; bytea *serializedTerm = DatumGetByteaPP(next); InitializeBsonIndexTerm(serializedTerm, &term); @@ -988,14 +1016,15 @@ GenerateCompositeTermsCore(pgbson *bson, BsonGinCompositePathOptions *options, element.path = "$"; element.pathLength = 1; element.bsonValue = PgbsonArrayWriterGetValue(&termWriter); - BsonIndexTermSerialized serializedTerm = SerializeBsonIndexTerm( - &element, &overallMetadata); + BsonCompressableIndexTermSerialized serializedTerm = + SerializeCompositeBsonIndexTermWithCompression( + &element, &overallMetadata, hasTruncation); if (serializedTerm.isIndexTermTruncated) { hasTruncation = true; } - indexEntries[i] = PointerGetDatum(serializedTerm.indexTermVal); + indexEntries[i] = serializedTerm.indexTermDatum; } if (totalTermCount > 1) diff --git a/pg_documentdb/src/opclass/bson_gin_entrypoint.c b/pg_documentdb/src/opclass/bson_gin_entrypoint.c index c55e4132..9d36f565 100644 --- a/pg_documentdb/src/opclass/bson_gin_entrypoint.c +++ b/pg_documentdb/src/opclass/bson_gin_entrypoint.c @@ -240,12 +240,8 @@ gin_bson_compare_partial(PG_FUNCTION_ARGS) StrategyNumber strategy = PG_GETARG_UINT16(2); Pointer extraData = PG_GETARG_POINTER(3); - BsonIndexTerm queryIndexTerm = { - false, false, { 0 } - }; - BsonIndexTerm compareIndexTerm = { - false, false, { 0 } - }; + BsonIndexTerm queryIndexTerm = { 0 }; + BsonIndexTerm compareIndexTerm = { 0 }; InitializeBsonIndexTerm(queryValue, &queryIndexTerm); InitializeBsonIndexTerm(compareValue, &compareIndexTerm); @@ -449,9 +445,7 @@ gin_bson_get_single_path_generated_terms(PG_FUNCTION_ARGS) if (context->index < context->totalTermCount) { Datum next = context->terms.entries[context->index++]; - BsonIndexTerm term = { - false, false, { 0 } - }; + BsonIndexTerm term = { 0 }; bytea *serializedTerm = DatumGetByteaPP(next); InitializeBsonIndexTerm(serializedTerm, &term); bool addMetadata = PG_GETARG_BOOL(4); @@ -535,9 +529,7 @@ gin_bson_get_wildcard_project_generated_terms(PG_FUNCTION_ARGS) if (context->index < context->totalTermCount) { Datum next = context->terms.entries[context->index++]; - BsonIndexTerm term = { - false, false, { 0 } - }; + BsonIndexTerm term = { 0 }; bytea *serializedTerm = DatumGetByteaPP(next); InitializeBsonIndexTerm(serializedTerm, &term); bool addMetadata = PG_GETARG_BOOL(4); diff --git a/pg_documentdb/src/opclass/gin_index_term.c b/pg_documentdb/src/opclass/gin_index_term.c index c5a96d17..7df19bae 100644 --- a/pg_documentdb/src/opclass/gin_index_term.c +++ b/pg_documentdb/src/opclass/gin_index_term.c @@ -885,12 +885,8 @@ SerializeBsonIndexTermCore(pgbsonelement *indexElement, bool forceTruncated, bool isMetadataTerm) { - BsonIndexTermSerialized serializedTerm = { - false, false, NULL - }; - BsonIndexTerm indexTerm = { - false, false, { 0 } - }; + BsonIndexTermSerialized serializedTerm = { 0 }; + BsonIndexTerm indexTerm = { 0 }; bytea *indexTermVal = BuildSerializedIndexTerm(indexElement, createMetadata, forceTruncated, @@ -923,6 +919,24 @@ SerializeBsonIndexTerm(pgbsonelement *indexElement, const } +static Datum +CompressTermIfNeeded(bytea *inputTerm) +{ + if (VARSIZE(inputTerm) > (Size) IndexTermCompressionThreshold) + { + Datum result = toast_compress_datum(PointerGetDatum(inputTerm), + default_toast_compression); + if (result != (Datum) NULL) + { + pfree(inputTerm); + return result; + } + } + + return PointerGetDatum(inputTerm); +} + + BsonCompressableIndexTermSerialized SerializeBsonIndexTermWithCompression(pgbsonelement *indexElement, const IndexTermCreateMetadata *createMetadata) @@ -932,27 +946,13 @@ SerializeBsonIndexTermWithCompression(pgbsonelement *indexElement, bool forceTruncated = false; bool isMetadataTerm = false; - BsonIndexTerm indexTerm = { - false, false, { 0 } - }; - BsonCompressableIndexTermSerialized serializedTerm = { - false, false, (Datum) NULL - }; + BsonIndexTerm indexTerm = { 0 }; + BsonCompressableIndexTermSerialized serializedTerm = { 0 }; bytea *indexTermVal = BuildSerializedIndexTerm(indexElement, createMetadata, forceTruncated, isMetadataTerm, &indexTerm); - serializedTerm.indexTermDatum = PointerGetDatum(indexTermVal); - if (VARSIZE(indexTermVal) > (Size) IndexTermCompressionThreshold) - { - Datum result = toast_compress_datum(serializedTerm.indexTermDatum, - default_toast_compression); - if (result != (Datum) NULL) - { - pfree(indexTermVal); - serializedTerm.indexTermDatum = result; - } - } + serializedTerm.indexTermDatum = CompressTermIfNeeded(indexTermVal); serializedTerm.isIndexTermTruncated = indexTerm.isIndexTermTruncated; serializedTerm.isRootMetadataTerm = indexTerm.isIndexTermMetadata; @@ -960,6 +960,47 @@ SerializeBsonIndexTermWithCompression(pgbsonelement *indexElement, } +BsonIndexTermSerialized +SerializeCompositeBsonIndexTerm(pgbsonelement *indexElement, + const IndexTermCreateMetadata *indexMetadata, bool + hasTruncatedTerms) +{ + BsonIndexTermSerialized serializedTerm = { 0 }; + BsonIndexTerm indexTerm = { 0 }; + + bool forceTruncated = hasTruncatedTerms; + bool isMetadataTerm = false; + bytea *indexTermVal = BuildSerializedIndexTerm(indexElement, indexMetadata, + forceTruncated, + isMetadataTerm, &indexTerm); + + serializedTerm.indexTermVal = indexTermVal; + serializedTerm.isIndexTermTruncated = indexTerm.isIndexTermTruncated; + serializedTerm.isRootMetadataTerm = indexTerm.isIndexTermMetadata; + return serializedTerm; +} + + +BsonCompressableIndexTermSerialized +SerializeCompositeBsonIndexTermWithCompression(pgbsonelement *indexElement, + const IndexTermCreateMetadata * + indexMetadata, bool hasTruncatedTerms) +{ + BsonCompressableIndexTermSerialized serializedTerm = { 0 }; + BsonIndexTerm indexTerm = { 0 }; + + bool forceTruncated = hasTruncatedTerms; + bool isMetadataTerm = false; + bytea *indexTermVal = BuildSerializedIndexTerm(indexElement, indexMetadata, + forceTruncated, + isMetadataTerm, &indexTerm); + serializedTerm.indexTermDatum = CompressTermIfNeeded(indexTermVal); + serializedTerm.isIndexTermTruncated = indexTerm.isIndexTermTruncated; + serializedTerm.isRootMetadataTerm = indexTerm.isIndexTermMetadata; + return serializedTerm; +} + + /* * This is the root term that all documents get when the indexed path exists. * We pick a term that points to a path that is illegal ('') diff --git a/pg_documentdb/src/test/regress/expected/bson_composite_index_tests_insert_terms.out b/pg_documentdb/src/test/regress/expected/bson_composite_index_tests_insert_terms.out index 5329da73..c70d2f14 100644 --- a/pg_documentdb/src/test/regress/expected/bson_composite_index_tests_insert_terms.out +++ b/pg_documentdb/src/test/regress/expected/bson_composite_index_tests_insert_terms.out @@ -72,9 +72,9 @@ SELECT * FROM documentdb_test_helpers.gin_bson_get_composite_path_generated_term -- test when one gets truncated (a has 29 letters, truncation limit is 50 /2 so 25 per path) SELECT * FROM documentdb_test_helpers.gin_bson_get_composite_path_generated_terms('{ "a": "aaaaaaaaaaaaaaaaaaaaaaaaaaaa", "b": 1 }', '[ "a", "b" ]', 50, true); - gin_bson_get_composite_path_generated_terms ---------------------------------------------------------------- - { "$" : [ "aaaaaaaa", { "$numberInt" : "1" } ], "t" : false } + gin_bson_get_composite_path_generated_terms +-------------------------------------------------------------- + { "$" : [ "aaaaaaaa", { "$numberInt" : "1" } ], "t" : true } { "" : { "$maxKey" : 1 }, "t" : true } (2 rows)