From dc157bd631b9c577b8d3e2b0c5addbb583592bc1 Mon Sep 17 00:00:00 2001 From: Ujjwal Agrawal Date: Tue, 17 Sep 2024 21:08:21 +0000 Subject: [PATCH] Merged PR 1446886: $first(N) & $last(N) implementation for $setWindowFields stage ### Does this PR have any customer impact? Yes ### Type (Feature, Refactoring, Bugfix, DevOps, Testing, Perf, etc) Feature ### Does it involve schema level changes? (Table, Column, Index, UDF, etc level changes) Yes ### Are you introducing any new config? If yes, do you have tests with and without them being set? No ### Release Note (Refer [Template](../docs/release_notes/pgmongo_template.md)) ### Description ---- #### AI description (iteration 1) #### PR Classification New feature implementation for the `$setWindowFields` stage. #### PR Summary This pull request implements the `$first(N)` and `$last(N)` aggregation functions for the `$setWindowFields` stage. - Added new aggregate functions in `oss/pg_helio_api/sql/udfs/aggregation/group_aggregates--1.21-0.sql` for `BSONFIRST`, `BSONLAST`, `BSONFIRSTN`, `BSONLASTN`, and their sorted variants. Related work items: #2151585, #2151587 --- ...gation_pipeline_tests_top_bottom_group.out | 2 + ...gation_pipeline_tests_top_bottom_group.sql | 1 + mongoerrors.csv | 1 + .../aggregation/bson_aggregation_pipeline.h | 4 + .../include/metadata/metadata_cache.h | 4 + .../aggregation/group_aggregates--1.22-0.sql | 38 ++ .../aggregation/group_aggregates--latest.sql | 38 ++ .../group_aggregates_support--1.22-0.sql | 26 +- .../group_aggregates_support--latest.sql | 26 +- .../aggregation/bson_aggregation_pipeline.c | 500 +++++++++--------- .../bson_aggregation_window_operators.c | 289 +++++++++- .../src/aggregation/bson_sorted_accumulator.c | 231 +++++++- pg_helio_api/src/metadata/metadata_cache.c | 166 +++++- .../bson_expression_array_operators.c | 75 +-- pg_helio_core/include/utils/helio_codes.txt | 1 + pg_helio_core/include/utils/helio_errors.h | 3 + 16 files changed, 1034 insertions(+), 371 deletions(-) diff --git a/internal/pg_helio_distributed/src/test/regress/expected/bson_aggregation_pipeline_tests_top_bottom_group.out b/internal/pg_helio_distributed/src/test/regress/expected/bson_aggregation_pipeline_tests_top_bottom_group.out index ff22709c..4067edbf 100644 --- a/internal/pg_helio_distributed/src/test/regress/expected/bson_aggregation_pipeline_tests_top_bottom_group.out +++ b/internal/pg_helio_distributed/src/test/regress/expected/bson_aggregation_pipeline_tests_top_bottom_group.out @@ -108,6 +108,8 @@ SELECT document FROM bson_aggregation_pipeline('db', '{ "aggregate": "games", "p ERROR: 'n' must be greater than 0, found -1 SELECT document FROM bson_aggregation_pipeline('db', '{ "aggregate": "games", "pipeline": [ {"$group": {"_id": "$gameId", "playerId": {"$bottomN": {"output": [ "$playerId", "$score" ], "sortBy": { "score": 1 }, "n": 0.5}}}} ] }'); -- n is not an integer ERROR: Value for 'n' must be of integral type, but found 0.5 +SELECT document FROM bson_aggregation_pipeline('db', '{ "aggregate": "games", "pipeline": [ {"$group": {"_id": "$gameId", "playerId": {"$bottomN": {"output": [ "$playerId", "$score" ], "sortBy": 1, "n": 1}}}} ] }'); -- sortBy is not an object +ERROR: expected 'sortBy' to already be an object in the arguments to $bottomN /* $top operator with $group */ SELECT document FROM bson_aggregation_pipeline('db', '{ "aggregate": "games", "pipeline": [ {"$group": {"_id": "$gameId", "playerId": {"$top": {"output": [ "$playerId", "$score" ], "sortBy": { "score": 1 }}}}} ] }'); document diff --git a/internal/pg_helio_distributed/src/test/regress/sql/bson_aggregation_pipeline_tests_top_bottom_group.sql b/internal/pg_helio_distributed/src/test/regress/sql/bson_aggregation_pipeline_tests_top_bottom_group.sql index 1debde4f..5ba9073c 100644 --- a/internal/pg_helio_distributed/src/test/regress/sql/bson_aggregation_pipeline_tests_top_bottom_group.sql +++ b/internal/pg_helio_distributed/src/test/regress/sql/bson_aggregation_pipeline_tests_top_bottom_group.sql @@ -39,6 +39,7 @@ SELECT document FROM bson_aggregation_pipeline('db', '{ "aggregate": "games", "p SELECT document FROM bson_aggregation_pipeline('db', '{ "aggregate": "games", "pipeline": [ {"$group": {"_id": "$gameId", "playerId": {"$bottomN": {"output": [ "$playerId", "$score" ], "sortBy": { "score": 1 }, "n": {"$numberDecimal": "Infinity"}}}}} ] }'); -- n is not a number SELECT document FROM bson_aggregation_pipeline('db', '{ "aggregate": "games", "pipeline": [ {"$group": {"_id": "$gameId", "playerId": {"$bottomN": {"output": [ "$playerId", "$score" ], "sortBy": { "score": 1 }, "n": -1}}}} ] }'); -- n is negative SELECT document FROM bson_aggregation_pipeline('db', '{ "aggregate": "games", "pipeline": [ {"$group": {"_id": "$gameId", "playerId": {"$bottomN": {"output": [ "$playerId", "$score" ], "sortBy": { "score": 1 }, "n": 0.5}}}} ] }'); -- n is not an integer +SELECT document FROM bson_aggregation_pipeline('db', '{ "aggregate": "games", "pipeline": [ {"$group": {"_id": "$gameId", "playerId": {"$bottomN": {"output": [ "$playerId", "$score" ], "sortBy": 1, "n": 1}}}} ] }'); -- sortBy is not an object /* $top operator with $group */ diff --git a/mongoerrors.csv b/mongoerrors.csv index 586c3e2c..32f938fa 100644 --- a/mongoerrors.csv +++ b/mongoerrors.csv @@ -474,6 +474,7 @@ Location5788003,5788003,464 Location5788004,5788004,465 Location5788005,5788005,466 Location5788200,5788200,451 +Location5788604,5788604,489 Location5858203,5858203,452 Location5876900,5876900,474 Location5897900,5897900,475 diff --git a/pg_helio_api/include/aggregation/bson_aggregation_pipeline.h b/pg_helio_api/include/aggregation/bson_aggregation_pipeline.h index d2d4f528..cda8dd03 100644 --- a/pg_helio_api/include/aggregation/bson_aggregation_pipeline.h +++ b/pg_helio_api/include/aggregation/bson_aggregation_pipeline.h @@ -93,5 +93,9 @@ void ParseInputDocumentForTopAndBottom(const bson_value_t *inputDocument, bson_value_t *sortSpec, const char *opName); void ValidateElementForNGroupAccumulators(bson_value_t *elementsToFetch, const char *opName); +void ParseInputForNGroupAccumulators(const bson_value_t *inputDocument, + bson_value_t *input, + bson_value_t *elementsToFetch, + const char *opName); #endif diff --git a/pg_helio_api/include/metadata/metadata_cache.h b/pg_helio_api/include/metadata/metadata_cache.h index ca378e8d..a9256683 100644 --- a/pg_helio_api/include/metadata/metadata_cache.h +++ b/pg_helio_api/include/metadata/metadata_cache.h @@ -304,7 +304,9 @@ Oid BsonMergeObjectsOnSortedFunctionOid(void); Oid BsonMergeObjectsFunctionOid(void); Oid BsonDollarFacetProjectFunctionOid(void); Oid BsonFirstOnSortedAggregateFunctionOid(void); +Oid BsonFirstOnSortedAggregateAllArgsFunctionOid(void); Oid BsonLastOnSortedAggregateFunctionOid(void); +Oid BsonLastOnSortedAggregateAllArgsFunctionOid(void); Oid BsonFirstAggregateFunctionOid(void); Oid BsonFirstAggregateAllArgsFunctionOid(void); Oid BsonLastAggregateFunctionOid(void); @@ -312,9 +314,11 @@ Oid BsonLastAggregateAllArgsFunctionOid(void); Oid BsonFirstNAggregateFunctionOid(void); Oid BsonFirstNAggregateAllArgsFunctionOid(void); Oid BsonFirstNOnSortedAggregateFunctionOid(void); +Oid BsonFirstNOnSortedAggregateAllArgsFunctionOid(void); Oid BsonLastNAggregateFunctionOid(void); Oid BsonLastNAggregateAllArgsFunctionOid(void); Oid BsonLastNOnSortedAggregateFunctionOid(void); +Oid BsonLastNOnSortedAggregateAllArgsFunctionOid(void); Oid BsonAddToSetAggregateFunctionOid(void); Oid BsonStdDevPopAggregateFunctionOid(void); Oid BsonStdDevSampAggregateFunctionOid(void); diff --git a/pg_helio_api/sql/udfs/aggregation/group_aggregates--1.22-0.sql b/pg_helio_api/sql/udfs/aggregation/group_aggregates--1.22-0.sql index 00e6d40b..a1a8d176 100644 --- a/pg_helio_api/sql/udfs/aggregation/group_aggregates--1.22-0.sql +++ b/pg_helio_api/sql/udfs/aggregation/group_aggregates--1.22-0.sql @@ -341,4 +341,42 @@ CREATE OR REPLACE AGGREGATE helio_api_internal.BSONMINN(__CORE_SCHEMA__.bson) stype = bytea, COMBINEFUNC = helio_api_internal.bson_maxminn_combine, PARALLEL = SAFE +); + +CREATE OR REPLACE AGGREGATE helio_api_internal.BSONFIRSTONSORTED(__CORE_SCHEMA__.bson, __CORE_SCHEMA__.bson) +( + SFUNC = helio_api_internal.bson_first_transition_on_sorted, + FINALFUNC = __API_CATALOG_SCHEMA__.bson_first_last_final_on_sorted, + stype = bytea, + PARALLEL = SAFE +); + +/* +* See summary of __CORE_SCHEMA__.bsonFIRSTONSORTED() +*/ +CREATE OR REPLACE AGGREGATE helio_api_internal.BSONLASTONSORTED(__CORE_SCHEMA__.bson, __CORE_SCHEMA__.bson) +( + SFUNC = helio_api_internal.bson_last_transition_on_sorted, + FINALFUNC = __API_CATALOG_SCHEMA__.bson_first_last_final_on_sorted, + stype = bytea, + PARALLEL = SAFE +); + +CREATE OR REPLACE AGGREGATE helio_api_internal.BSONFIRSTNONSORTED(__CORE_SCHEMA__.bson, bigint, __CORE_SCHEMA__.bson) +( + SFUNC = helio_api_internal.bson_firstn_transition_on_sorted, + FINALFUNC = __API_CATALOG_SCHEMA__.bson_firstn_lastn_final_on_sorted, + stype = bytea, + PARALLEL = SAFE +); + +/* +* See summary of __CORE_SCHEMA__.bsonFIRSTNONSORTED() +*/ +CREATE OR REPLACE AGGREGATE helio_api_internal.BSONLASTNONSORTED(__CORE_SCHEMA__.bson, bigint, __CORE_SCHEMA__.bson) +( + SFUNC = helio_api_internal.bson_lastn_transition_on_sorted, + FINALFUNC = __API_CATALOG_SCHEMA__.bson_firstn_lastn_final_on_sorted, + stype = bytea, + PARALLEL = SAFE ); \ No newline at end of file diff --git a/pg_helio_api/sql/udfs/aggregation/group_aggregates--latest.sql b/pg_helio_api/sql/udfs/aggregation/group_aggregates--latest.sql index 00e6d40b..a1a8d176 100644 --- a/pg_helio_api/sql/udfs/aggregation/group_aggregates--latest.sql +++ b/pg_helio_api/sql/udfs/aggregation/group_aggregates--latest.sql @@ -341,4 +341,42 @@ CREATE OR REPLACE AGGREGATE helio_api_internal.BSONMINN(__CORE_SCHEMA__.bson) stype = bytea, COMBINEFUNC = helio_api_internal.bson_maxminn_combine, PARALLEL = SAFE +); + +CREATE OR REPLACE AGGREGATE helio_api_internal.BSONFIRSTONSORTED(__CORE_SCHEMA__.bson, __CORE_SCHEMA__.bson) +( + SFUNC = helio_api_internal.bson_first_transition_on_sorted, + FINALFUNC = __API_CATALOG_SCHEMA__.bson_first_last_final_on_sorted, + stype = bytea, + PARALLEL = SAFE +); + +/* +* See summary of __CORE_SCHEMA__.bsonFIRSTONSORTED() +*/ +CREATE OR REPLACE AGGREGATE helio_api_internal.BSONLASTONSORTED(__CORE_SCHEMA__.bson, __CORE_SCHEMA__.bson) +( + SFUNC = helio_api_internal.bson_last_transition_on_sorted, + FINALFUNC = __API_CATALOG_SCHEMA__.bson_first_last_final_on_sorted, + stype = bytea, + PARALLEL = SAFE +); + +CREATE OR REPLACE AGGREGATE helio_api_internal.BSONFIRSTNONSORTED(__CORE_SCHEMA__.bson, bigint, __CORE_SCHEMA__.bson) +( + SFUNC = helio_api_internal.bson_firstn_transition_on_sorted, + FINALFUNC = __API_CATALOG_SCHEMA__.bson_firstn_lastn_final_on_sorted, + stype = bytea, + PARALLEL = SAFE +); + +/* +* See summary of __CORE_SCHEMA__.bsonFIRSTNONSORTED() +*/ +CREATE OR REPLACE AGGREGATE helio_api_internal.BSONLASTNONSORTED(__CORE_SCHEMA__.bson, bigint, __CORE_SCHEMA__.bson) +( + SFUNC = helio_api_internal.bson_lastn_transition_on_sorted, + FINALFUNC = __API_CATALOG_SCHEMA__.bson_firstn_lastn_final_on_sorted, + stype = bytea, + PARALLEL = SAFE ); \ No newline at end of file diff --git a/pg_helio_api/sql/udfs/aggregation/group_aggregates_support--1.22-0.sql b/pg_helio_api/sql/udfs/aggregation/group_aggregates_support--1.22-0.sql index 779ec8b8..ce0964d5 100644 --- a/pg_helio_api/sql/udfs/aggregation/group_aggregates_support--1.22-0.sql +++ b/pg_helio_api/sql/udfs/aggregation/group_aggregates_support--1.22-0.sql @@ -300,4 +300,28 @@ CREATE OR REPLACE FUNCTION helio_api_internal.bson_maxminn_combine(bytea, bytea) RETURNS bytea LANGUAGE c STABLE -AS 'MODULE_PATHNAME', $function$bson_maxminn_combine$function$; \ No newline at end of file +AS 'MODULE_PATHNAME', $function$bson_maxminn_combine$function$; + +CREATE OR REPLACE FUNCTION helio_api_internal.bson_first_transition_on_sorted(bytea, __CORE_SCHEMA__.bson, __CORE_SCHEMA__.bson DEFAULT NULL) + RETURNS bytea + LANGUAGE c + STABLE +AS 'MODULE_PATHNAME', $function$bson_first_transition_on_sorted$function$; + +CREATE OR REPLACE FUNCTION helio_api_internal.bson_last_transition_on_sorted(bytea, __CORE_SCHEMA__.bson, __CORE_SCHEMA__.bson DEFAULT NULL) + RETURNS bytea + LANGUAGE c + STABLE +AS 'MODULE_PATHNAME', $function$bson_last_transition_on_sorted$function$; + +CREATE OR REPLACE FUNCTION helio_api_internal.bson_firstn_transition_on_sorted(bytea, __CORE_SCHEMA__.bson, bigint, __CORE_SCHEMA__.bson DEFAULT NULL) + RETURNS bytea + LANGUAGE c + STABLE +AS 'MODULE_PATHNAME', $function$bson_firstn_transition_on_sorted$function$; + +CREATE OR REPLACE FUNCTION helio_api_internal.bson_lastn_transition_on_sorted(bytea, __CORE_SCHEMA__.bson, bigint, __CORE_SCHEMA__.bson DEFAULT NULL) + RETURNS bytea + LANGUAGE c + STABLE +AS 'MODULE_PATHNAME', $function$bson_lastn_transition_on_sorted$function$; \ No newline at end of file diff --git a/pg_helio_api/sql/udfs/aggregation/group_aggregates_support--latest.sql b/pg_helio_api/sql/udfs/aggregation/group_aggregates_support--latest.sql index 779ec8b8..ce0964d5 100644 --- a/pg_helio_api/sql/udfs/aggregation/group_aggregates_support--latest.sql +++ b/pg_helio_api/sql/udfs/aggregation/group_aggregates_support--latest.sql @@ -300,4 +300,28 @@ CREATE OR REPLACE FUNCTION helio_api_internal.bson_maxminn_combine(bytea, bytea) RETURNS bytea LANGUAGE c STABLE -AS 'MODULE_PATHNAME', $function$bson_maxminn_combine$function$; \ No newline at end of file +AS 'MODULE_PATHNAME', $function$bson_maxminn_combine$function$; + +CREATE OR REPLACE FUNCTION helio_api_internal.bson_first_transition_on_sorted(bytea, __CORE_SCHEMA__.bson, __CORE_SCHEMA__.bson DEFAULT NULL) + RETURNS bytea + LANGUAGE c + STABLE +AS 'MODULE_PATHNAME', $function$bson_first_transition_on_sorted$function$; + +CREATE OR REPLACE FUNCTION helio_api_internal.bson_last_transition_on_sorted(bytea, __CORE_SCHEMA__.bson, __CORE_SCHEMA__.bson DEFAULT NULL) + RETURNS bytea + LANGUAGE c + STABLE +AS 'MODULE_PATHNAME', $function$bson_last_transition_on_sorted$function$; + +CREATE OR REPLACE FUNCTION helio_api_internal.bson_firstn_transition_on_sorted(bytea, __CORE_SCHEMA__.bson, bigint, __CORE_SCHEMA__.bson DEFAULT NULL) + RETURNS bytea + LANGUAGE c + STABLE +AS 'MODULE_PATHNAME', $function$bson_firstn_transition_on_sorted$function$; + +CREATE OR REPLACE FUNCTION helio_api_internal.bson_lastn_transition_on_sorted(bytea, __CORE_SCHEMA__.bson, bigint, __CORE_SCHEMA__.bson DEFAULT NULL) + RETURNS bytea + LANGUAGE c + STABLE +AS 'MODULE_PATHNAME', $function$bson_lastn_transition_on_sorted$function$; \ No newline at end of file diff --git a/pg_helio_api/src/aggregation/bson_aggregation_pipeline.c b/pg_helio_api/src/aggregation/bson_aggregation_pipeline.c index 629c2830..533e26f7 100644 --- a/pg_helio_api/src/aggregation/bson_aggregation_pipeline.c +++ b/pg_helio_api/src/aggregation/bson_aggregation_pipeline.c @@ -2204,6 +2204,261 @@ HandleSimpleProjectionStage(const bson_value_t *existingValue, Query *query, } +/** + * Parses the input document for FirstN and LastN group expression operator and extracts the value for input and n. + * @param inputDocument: input document for the $firstN operator + * @param input: this is a pointer which after parsing will hold array expression + * @param elementsToFetch: this is a pointer which after parsing will hold n i.e. how many elements to fetch for result + * @param opName: this contains the name of the operator for error msg formatting purposes. This value is supposed to be $firstN/$lastN. + */ +void +ParseInputForNGroupAccumulators(const bson_value_t *inputDocument, + bson_value_t *input, + bson_value_t *elementsToFetch, const char *opName) +{ + if (inputDocument->value_type != BSON_TYPE_DOCUMENT) + { + if (strcmp(opName, "$maxN") == 0 || strcmp(opName, "$minN") == 0) + { + ereport(ERROR, (errcode(ERRCODE_HELIO_LOCATION5787900), + errmsg("specification must be an object; found %s: %s", + opName, BsonValueToJsonForLogging(inputDocument)), + errdetail_log( + "specification must be an object; opname: %s type found: %s", + opName, BsonTypeName(inputDocument->value_type)))); + } + else + { + ereport(ERROR, (errcode(ERRCODE_HELIO_LOCATION5787801), + errmsg("specification must be an object; found %s :%s", + opName, BsonValueToJsonForLogging(inputDocument)), + errdetail_log( + "specification must be an object; opname: %s type found :%s", + opName, BsonTypeName(inputDocument->value_type)))); + } + } + bson_iter_t docIter; + BsonValueInitIterator(inputDocument, &docIter); + + while (bson_iter_next(&docIter)) + { + const char *key = bson_iter_key(&docIter); + if (strcmp(key, "input") == 0) + { + *input = *bson_iter_value(&docIter); + } + else if (strcmp(key, "n") == 0) + { + *elementsToFetch = *bson_iter_value(&docIter); + } + else + { + ereport(ERROR, (errcode(ERRCODE_HELIO_LOCATION5787901), + errmsg("%s found an unknown argument: %s", opName, key), + errdetail_log( + "%s found an unknown argument", opName))); + } + } + + /** + * Validation check to see if input and elements to fetch are present otherwise throw error. + */ + if (input->value_type == BSON_TYPE_EOD) + { + ereport(ERROR, (errcode(ERRCODE_HELIO_LOCATION5787907), + errmsg("%s requires an 'input' field", opName), + errdetail_log( + "%s requires an 'input' field", opName))); + } + + if (elementsToFetch->value_type == BSON_TYPE_EOD) + { + ereport(ERROR, (errcode(ERRCODE_HELIO_LOCATION5787906), + errmsg("%s requires an 'n' field", opName), + errdetail_log( + "%s requires an 'n' field", opName))); + } +} + + +/** + * Parses the input document for $top(N) and $bottom(N) group expression operator and extracts the value for output, sortBy and n. + * @param inputDocument: input document for the operator + * @param output: this is a pointer which after parsing will hold array expression + * @param sortSpec: this is a pointer which after parsing will hold the sortBy expression + * @param elementsToFetch: this is a pointer which after parsing will hold n i.e. how many elements to fetch for result + * @param opName: this contains the name of the operator for error msg formatting purposes. This value is supposed to be $firstN/$lastN. + */ +void +ParseInputDocumentForTopAndBottom(const bson_value_t *inputDocument, bson_value_t *output, + bson_value_t *elementsToFetch, bson_value_t *sortSpec, + const char *opName) +{ + if (inputDocument->value_type != BSON_TYPE_DOCUMENT) + { + ereport(ERROR, (errcode(ERRCODE_HELIO_LOCATION5788001), + errmsg("specification must be an object; found %s :%s", + opName, BsonValueToJsonForLogging(inputDocument)), + errdetail_log( + "specification must be an object; opname: %s type found :%s", + opName, BsonTypeName(inputDocument->value_type)))); + } + bson_iter_t docIter; + BsonValueInitIterator(inputDocument, &docIter); + + while (bson_iter_next(&docIter)) + { + const char *key = bson_iter_key(&docIter); + if (strcmp(key, "output") == 0) + { + *output = *bson_iter_value(&docIter); + } + else if (strcmp(key, "n") == 0) + { + *elementsToFetch = *bson_iter_value(&docIter); + } + else if (strcmp(key, "sortBy") == 0) + { + *sortSpec = *bson_iter_value(&docIter); + } + else + { + ereport(ERROR, (errcode(ERRCODE_HELIO_LOCATION5788002), + errmsg("Unknown argument to %s '%s'", opName, key), + errdetail_log( + "%s found an unknown argument", opName))); + } + } + + /** + * Validation check to see if input and elements to fetch are present otherwise throw error. + */ + if (elementsToFetch->value_type == BSON_TYPE_EOD && (strcmp(opName, "$topN") == 0 || + strcmp(opName, "$bottomN") == 0)) + { + ereport(ERROR, (errcode(ERRCODE_HELIO_LOCATION5788003), + errmsg("Missing value for 'n'"), + errdetail_log( + "%s requires an 'n' field", opName))); + } + + if (elementsToFetch->value_type != BSON_TYPE_EOD && (strcmp(opName, "$top") == 0 || + strcmp(opName, "$bottom") == 0)) + { + ereport(ERROR, (errcode(ERRCODE_HELIO_LOCATION5788002), + errmsg("Unknown argument to %s 'n'", opName), + errdetail_log( + "Unknown argument to %s 'n'", opName))); + } + + if (output->value_type == BSON_TYPE_EOD) + { + ereport(ERROR, (errcode(ERRCODE_HELIO_LOCATION5788004), + errmsg("Missing value for 'output'"), + errdetail_log( + "%s requires an 'output' field", opName))); + } + + if (sortSpec->value_type == BSON_TYPE_EOD) + { + ereport(ERROR, (errcode(ERRCODE_HELIO_LOCATION5788005), + errmsg("Missing value for 'sortBy'"), + errdetail_log( + "%s requires a 'sortBy", opName))); + } + else if (sortSpec->value_type != BSON_TYPE_DOCUMENT) + { + ereport(ERROR, (errcode(ERRCODE_HELIO_LOCATION5788604), + errmsg( + "expected 'sortBy' to already be an object in the arguments to %s", + opName), + errdetail_log( + "'sortBy' field in %s is not an object", opName))); + } +} + + +/** + * This function validates and throws error in case bson type is not a numeric > 0 and less than max value of int64 i.e. 9223372036854775807 + */ +void +ValidateElementForNGroupAccumulators(bson_value_t *elementsToFetch, const + char *opName) +{ + switch (elementsToFetch->value_type) + { + case BSON_TYPE_INT32: + case BSON_TYPE_INT64: + case BSON_TYPE_DOUBLE: + case BSON_TYPE_DECIMAL128: + { + if (IsBsonValueNaN(elementsToFetch)) + { + ereport(ERROR, (errcode(ERRCODE_HELIO_LOCATION31109), + errmsg("Can't coerce out of range value %s to long", + BsonValueToJsonForLogging(elementsToFetch)))); + } + + if (IsBsonValueInfinity(elementsToFetch) != 0) + { + ereport(ERROR, (errcode(ERRCODE_HELIO_LOCATION31109), + errmsg("Can't coerce out of range value %s to long", + BsonValueToJsonForLogging(elementsToFetch)))); + } + + if (!IsBsonValueFixedInteger(elementsToFetch)) + { + ereport(ERROR, (errcode(ERRCODE_HELIO_LOCATION5787903), + errmsg( + "Value for 'n' must be of integral type, but found %s", + BsonValueToJsonForLogging(elementsToFetch)), + errdetail_log( + "Value for 'n' must be of integral type, but found of type %s", + BsonTypeName(elementsToFetch->value_type)))); + } + + /* This is done as elements to fetch must only be int64. */ + bool throwIfFailed = true; + elementsToFetch->value.v_int64 = BsonValueAsInt64WithRoundingMode( + elementsToFetch, ConversionRoundingMode_Floor, throwIfFailed); + elementsToFetch->value_type = BSON_TYPE_INT64; + + if (elementsToFetch->value.v_int64 <= 0) + { + ereport(ERROR, (errcode(ERRCODE_HELIO_LOCATION5787908), + errmsg("'n' must be greater than 0, found %s", + BsonValueToJsonForLogging(elementsToFetch)), + errdetail_log( + "'n' must be greater than 0, found %ld", + elementsToFetch->value.v_int64))); + } + if (elementsToFetch->value.v_int64 > 10) + { + if (strncmp(opName, "$lastN", 6) == 0) + { + ReportFeatureUsage(FEATURE_STAGE_GROUP_ACC_LASTN_GT10); + } + else if ((strncmp(opName, "$firstN", 7) == 0)) + { + ReportFeatureUsage(FEATURE_STAGE_GROUP_ACC_FIRSTN_GT10); + } + } + break; + } + + default: + { + ereport(ERROR, (errcode(ERRCODE_HELIO_LOCATION5787902), + errmsg("Value for 'n' must be of integral type, but found %s", + BsonValueToJsonForLogging(elementsToFetch)), + errdetail_log( + "Value for 'n' must be of integral type, but found of type %s", + BsonTypeName(elementsToFetch->value_type)))); + } + } +} + + /* * Mutates the query for the $addFields stage */ @@ -3973,251 +4228,6 @@ AddGroupExpression(Expr *expression, ParseState *parseState, char *identifiers, } -/** - * Parses the input document for FirstN and LastN group expression operator and extracts the value for input and n. - * @param inputDocument: input document for the $firstN operator - * @param input: this is a pointer which after parsing will hold array expression - * @param elementsToFetch: this is a pointer which after parsing will hold n i.e. how many elements to fetch for result - * @param opName: this contains the name of the operator for error msg formatting purposes. This value is supposed to be $firstN/$lastN. - */ -static void -ParseInputForNGroupAccumulators(const bson_value_t *inputDocument, - bson_value_t *input, - bson_value_t *elementsToFetch, const char *opName) -{ - if (inputDocument->value_type != BSON_TYPE_DOCUMENT) - { - if (strcmp(opName, "$maxN") == 0 || strcmp(opName, "$minN") == 0) - { - ereport(ERROR, (errcode(ERRCODE_HELIO_LOCATION5787900), errmsg( - "specification must be an object; found %s: %s", - opName, BsonValueToJsonForLogging(inputDocument)), - errdetail_log( - "specification must be an object; opname: %s type found: %s", - opName, BsonTypeName(inputDocument->value_type)))); - } - else - { - ereport(ERROR, (errcode(ERRCODE_HELIO_LOCATION5787801), errmsg( - "specification must be an object; found %s :%s", - opName, BsonValueToJsonForLogging(inputDocument)), - errdetail_log( - "specification must be an object; opname: %s type found :%s", - opName, BsonTypeName(inputDocument->value_type)))); - } - } - bson_iter_t docIter; - BsonValueInitIterator(inputDocument, &docIter); - - while (bson_iter_next(&docIter)) - { - const char *key = bson_iter_key(&docIter); - if (strcmp(key, "input") == 0) - { - *input = *bson_iter_value(&docIter); - } - else if (strcmp(key, "n") == 0) - { - *elementsToFetch = *bson_iter_value(&docIter); - } - else - { - ereport(ERROR, (errcode(ERRCODE_HELIO_LOCATION5787901), errmsg( - "%s found an unknown argument: %s", opName, key), - errdetail_log( - "%s found an unknown argument", opName))); - } - } - - /** - * Validation check to see if input and elements to fetch are present otherwise throw error. - */ - if (input->value_type == BSON_TYPE_EOD) - { - ereport(ERROR, (errcode(ERRCODE_HELIO_LOCATION5787907), errmsg( - "%s requires an 'input' field", opName), - errdetail_log( - "%s requires an 'input' field", opName))); - } - - if (elementsToFetch->value_type == BSON_TYPE_EOD) - { - ereport(ERROR, (errcode(ERRCODE_HELIO_LOCATION5787906), errmsg( - "%s requires an 'n' field", opName), - errdetail_log( - "%s requires an 'n' field", opName))); - } -} - - -/** - * Parses the input document for $top(N) and $bottom(N) group expression operator and extracts the value for output, sortBy and n. - * @param inputDocument: input document for the operator - * @param output: this is a pointer which after parsing will hold array expression - * @param sortSpec: this is a pointer which after parsing will hold the sortBy expression - * @param elementsToFetch: this is a pointer which after parsing will hold n i.e. how many elements to fetch for result - * @param opName: this contains the name of the operator for error msg formatting purposes. This value is supposed to be $firstN/$lastN. - */ -void -ParseInputDocumentForTopAndBottom(const bson_value_t *inputDocument, bson_value_t *output, - bson_value_t *elementsToFetch, bson_value_t *sortSpec, - const char *opName) -{ - if (inputDocument->value_type != BSON_TYPE_DOCUMENT) - { - ereport(ERROR, (errcode(ERRCODE_HELIO_LOCATION5788001), errmsg( - "specification must be an object; found %s :%s", - opName, BsonValueToJsonForLogging(inputDocument)), - errdetail_log( - "specification must be an object; opname: %s type found :%s", - opName, BsonTypeName(inputDocument->value_type)))); - } - bson_iter_t docIter; - BsonValueInitIterator(inputDocument, &docIter); - - while (bson_iter_next(&docIter)) - { - const char *key = bson_iter_key(&docIter); - if (strcmp(key, "output") == 0) - { - *output = *bson_iter_value(&docIter); - } - else if (strcmp(key, "n") == 0) - { - *elementsToFetch = *bson_iter_value(&docIter); - } - else if (strcmp(key, "sortBy") == 0) - { - *sortSpec = *bson_iter_value(&docIter); - } - else - { - ereport(ERROR, (errcode(ERRCODE_HELIO_LOCATION5788002), errmsg( - "Unknown argument to %s '%s'", opName, key), - errdetail_log( - "%s found an unknown argument", opName))); - } - } - - /** - * Validation check to see if input and elements to fetch are present otherwise throw error. - */ - if (elementsToFetch->value_type == BSON_TYPE_EOD && (strcmp(opName, "$topN") == 0 || - strcmp(opName, "$bottomN") == 0)) - { - ereport(ERROR, (errcode(ERRCODE_HELIO_LOCATION5788003), errmsg( - "Missing value for 'n'"), - errdetail_log( - "%s requires an 'n' field", opName))); - } - - if (elementsToFetch->value_type != BSON_TYPE_EOD && (strcmp(opName, "$top") == 0 || - strcmp(opName, "$bottom") == 0)) - { - ereport(ERROR, (errcode(ERRCODE_HELIO_LOCATION5788002), errmsg( - "Unknown argument to %s 'n'", opName), - errdetail_log( - "Unknown argument to %s 'n'", opName))); - } - - if (output->value_type == BSON_TYPE_EOD) - { - ereport(ERROR, (errcode(ERRCODE_HELIO_LOCATION5788004), errmsg( - "Missing value for 'output'"), - errdetail_log( - "%s requires an 'output' field", opName))); - } - - if (sortSpec->value_type == BSON_TYPE_EOD) - { - ereport(ERROR, (errcode(ERRCODE_HELIO_LOCATION5788005), errmsg( - "Missing value for 'sortBy'"), - errdetail_log( - "%s requires a 'sortBy", opName))); - } -} - - -/** - * This function validates and throws error in case bson type is not a numeric > 0 and less than max value of int64 i.e. 9223372036854775807 - */ -void -ValidateElementForNGroupAccumulators(bson_value_t *elementsToFetch, const - char *opName) -{ - switch (elementsToFetch->value_type) - { - case BSON_TYPE_INT32: - case BSON_TYPE_INT64: - case BSON_TYPE_DOUBLE: - case BSON_TYPE_DECIMAL128: - { - if (IsBsonValueNaN(elementsToFetch)) - { - ereport(ERROR, (errcode(ERRCODE_HELIO_LOCATION31109), errmsg( - "Can't coerce out of range value %s to long", - BsonValueToJsonForLogging(elementsToFetch)))); - } - - if (IsBsonValueInfinity(elementsToFetch) != 0) - { - ereport(ERROR, (errcode(ERRCODE_HELIO_LOCATION31109), errmsg( - "Can't coerce out of range value %s to long", - BsonValueToJsonForLogging(elementsToFetch)))); - } - - if (!IsBsonValueFixedInteger(elementsToFetch)) - { - ereport(ERROR, (errcode(ERRCODE_HELIO_LOCATION5787903), errmsg( - "Value for 'n' must be of integral type, but found %s", - BsonValueToJsonForLogging(elementsToFetch)), - errdetail_log( - "Value for 'n' must be of integral type, but found of type %s", - BsonTypeName(elementsToFetch->value_type)))); - } - - /* This is done as elements to fetch must only be int64. */ - bool throwIfFailed = true; - elementsToFetch->value.v_int64 = BsonValueAsInt64WithRoundingMode( - elementsToFetch, ConversionRoundingMode_Floor, throwIfFailed); - elementsToFetch->value_type = BSON_TYPE_INT64; - - if (elementsToFetch->value.v_int64 <= 0) - { - ereport(ERROR, (errcode(ERRCODE_HELIO_LOCATION5787908), errmsg( - "'n' must be greater than 0, found %s", - BsonValueToJsonForLogging(elementsToFetch)), - errdetail_log( - "'n' must be greater than 0, found %ld", - elementsToFetch->value.v_int64))); - } - if (elementsToFetch->value.v_int64 > 10) - { - if (strncmp(opName, "$lastN", 6) == 0) - { - ReportFeatureUsage(FEATURE_STAGE_GROUP_ACC_LASTN_GT10); - } - else if ((strncmp(opName, "$firstN", 7) == 0)) - { - ReportFeatureUsage(FEATURE_STAGE_GROUP_ACC_FIRSTN_GT10); - } - } - break; - } - - default: - { - ereport(ERROR, (errcode(ERRCODE_HELIO_LOCATION5787902), errmsg( - "Value for 'n' must be of integral type, but found %s", - BsonValueToJsonForLogging(elementsToFetch)), - errdetail_log( - "Value for 'n' must be of integral type, but found of type %s", - BsonTypeName(elementsToFetch->value_type)))); - } - } -} - - /* * Simple helper method that has logic to insert a Group accumulator to a query. * This adds the group aggregate to the TargetEntry (for projection) diff --git a/pg_helio_api/src/aggregation/bson_aggregation_window_operators.c b/pg_helio_api/src/aggregation/bson_aggregation_window_operators.c index 341dbd44..406c2feb 100644 --- a/pg_helio_api/src/aggregation/bson_aggregation_window_operators.c +++ b/pg_helio_api/src/aggregation/bson_aggregation_window_operators.c @@ -172,6 +172,11 @@ static WindowFunc * HandleDollarTopBottomOperators(const bson_value_t *opValue, const char *opName, Oid aggregateFunctionOid, bool isNOperator); +static WindowFunc * HandleDollarFirstLastOperators(const bson_value_t *opValue, + WindowOperatorContext *context, + const char *opName, + Oid aggregateFunctionOid, + bool isNOperator); /*===================================*/ /* Window Operator Handler functions */ @@ -221,6 +226,14 @@ static WindowFunc * HandleDollarStdDevPopWindowOperator(const bson_value_t *opVa WindowOperatorContext *context); static WindowFunc * HandleDollarStdDevSampWindowOperator(const bson_value_t *opValue, WindowOperatorContext *context); +static WindowFunc * HandleDollarFirstWindowOperator(const bson_value_t *opValue, + WindowOperatorContext *context); +static WindowFunc * HandleDollarLastWindowOperator(const bson_value_t *opValue, + WindowOperatorContext *context); +static WindowFunc * HandleDollarFirstNWindowOperator(const bson_value_t *opValue, + WindowOperatorContext *context); +static WindowFunc * HandleDollarLastNWindowOperator(const bson_value_t *opValue, + WindowOperatorContext *context); static WindowFunc * HandleDollarMaxNWindowOperator(const bson_value_t *opValue, WindowOperatorContext *context); static WindowFunc * HandleDollarMinNWindowOperator(const bson_value_t *opValue, @@ -287,11 +300,11 @@ static const WindowOperatorDefinition WindowOperatorDefinitions[] = }, { .operatorName = "$first", - .windowOperatorFunc = NULL + .windowOperatorFunc = &HandleDollarFirstWindowOperator }, { .operatorName = "$firstN", - .windowOperatorFunc = NULL + .windowOperatorFunc = &HandleDollarFirstNWindowOperator }, { .operatorName = "$integral", @@ -299,11 +312,11 @@ static const WindowOperatorDefinition WindowOperatorDefinitions[] = }, { .operatorName = "$last", - .windowOperatorFunc = NULL + .windowOperatorFunc = &HandleDollarLastWindowOperator }, { .operatorName = "$lastN", - .windowOperatorFunc = NULL + .windowOperatorFunc = &HandleDollarLastNWindowOperator }, { .operatorName = "$linearFill", @@ -655,7 +668,6 @@ HandleSetWindowFieldsCore(const bson_value_t *existingValue, BsonIterToPgbsonElement(&sortByIter, &element); pgbson *sortDoc = PgbsonElementToPgbson(&element); - Const *sortBson = MakeBsonConst(sortDoc); bool isAscending = ValidateOrderbyExpressionAndGetIsAscending(sortDoc); @@ -1558,6 +1570,7 @@ ParseIntegralDerivativeExpression(const bson_value_t *opValue, sortField = (SetWindowFieldSortOption *) list_nth( context->sortOptions, 0); } + pgbson *sortSpecBson = DatumGetPgBson(sortField->sortSpecConst->constvalue); pgbson *opValueBson = BsonValueToDocumentPgbson(opValue); bson_iter_t iterOpValue, iterSortSpec; @@ -2363,8 +2376,16 @@ ParseInputDocumentForDollarShift(const bson_value_t *opValue, bson_value_t *outp /* - * Handle for $topN window aggregation operator. - * Returns the WindowFunc for bson aggregate function `bsontopnsetwindowfields` + * Handler for $topN window aggregation operator. + * input format: + * { + * $topN: + * { + * output: , + * n: , + * sortBy: { : , : ... }, + * } + * } */ static WindowFunc * HandleDollarTopNWindowOperator(const bson_value_t *opValue, @@ -2384,8 +2405,16 @@ HandleDollarTopNWindowOperator(const bson_value_t *opValue, /* - * Handle for $bottomN window aggregation operator. - * Returns the WindowFunc for bson aggregate function `bsonbottomnsetwindowfields` + * Handler for $bottomN window aggregation operator. + * input format: + * { + * $bottomN: + * { + * output: , + * n: , + * sortBy: { : , : ... }, + * } + * } */ static WindowFunc * HandleDollarBottomNWindowOperator(const bson_value_t *opValue, @@ -2405,8 +2434,15 @@ HandleDollarBottomNWindowOperator(const bson_value_t *opValue, /* - * Handle for $top window aggregation operator. - * Returns the WindowFunc for bson aggregate function `bsontopsetwindowfields` + * Handler for $top window aggregation operator. + * input format: + * { + * $top: + * { + * output: , + * sortBy: { : , : ... }, + * } + * } */ static WindowFunc * HandleDollarTopWindowOperator(const bson_value_t *opValue, @@ -2426,8 +2462,15 @@ HandleDollarTopWindowOperator(const bson_value_t *opValue, /* - * Handle for $bottom window aggregation operator. - * Returns the WindowFunc for bson aggregate function `bsonbottomsetwindowfields` + * Handler for $bottom window aggregation operator. + * input format: + * { + * $bottom: + * { + * output: , + * sortBy: { : , : ... }, + * } + * } */ static WindowFunc * HandleDollarBottomWindowOperator(const bson_value_t *opValue, @@ -2447,7 +2490,7 @@ HandleDollarBottomWindowOperator(const bson_value_t *opValue, /* - * Common handler for $topN and $bottomN operators. + * Common handler for $top(N) and $bottom(N) operators. * Parses the spec and generates the WindowFunc for the respective bson aggregate function. * * TODO: Support n(elementsToFetch) as an expression @@ -2719,6 +2762,224 @@ HandleDollarMinNWindowOperator(const bson_value_t *opValue, } +/* + * Handler for $first window aggregation operator. + * input format: { $first: } + */ +static WindowFunc * +HandleDollarFirstWindowOperator(const bson_value_t *opValue, + WindowOperatorContext *context) +{ + if (!IsClusterVersionAtleastThis(1, 22, 0)) + { + ereport(ERROR, (errcode(ERRCODE_HELIO_COMMANDNOTSUPPORTED), + errmsg("$first is not supported yet"))); + } + + bool isNOperator = false; + Oid functionOid; + if (context->sortOptions != NIL && list_length(context->sortOptions) > 0) + { + functionOid = BsonFirstAggregateAllArgsFunctionOid(); + } + else + { + functionOid = BsonFirstOnSortedAggregateAllArgsFunctionOid(); + } + + return HandleDollarFirstLastOperators(opValue, context, "$first", functionOid, + isNOperator); +} + + +/* + * Handler for $last window aggregation operator. + * input format: { $last: } + */ +static WindowFunc * +HandleDollarLastWindowOperator(const bson_value_t *opValue, + WindowOperatorContext *context) +{ + if (!IsClusterVersionAtleastThis(1, 22, 0)) + { + ereport(ERROR, (errcode(ERRCODE_HELIO_COMMANDNOTSUPPORTED), + errmsg("$last is not supported yet"))); + } + + bool isNOperator = false; + Oid functionOid; + if (context->sortOptions != NIL && list_length(context->sortOptions) > 0) + { + functionOid = BsonLastAggregateAllArgsFunctionOid(); + } + else + { + functionOid = BsonLastOnSortedAggregateAllArgsFunctionOid(); + } + + return HandleDollarFirstLastOperators(opValue, context, "$last", functionOid, + isNOperator); +} + + +/* + * Handler for $firstN window aggregation operator. + * input format: + * { + * $firstN: + * { + * input: , + * n: + * } + * } + */ +static WindowFunc * +HandleDollarFirstNWindowOperator(const bson_value_t *opValue, + WindowOperatorContext *context) +{ + if (!IsClusterVersionAtleastThis(1, 22, 0)) + { + ereport(ERROR, (errcode(ERRCODE_HELIO_COMMANDNOTSUPPORTED), + errmsg("$firstN is not supported yet"))); + } + + bool isNOperator = true; + Oid functionOid; + if (context->sortOptions != NIL && list_length(context->sortOptions) > 0) + { + functionOid = BsonFirstNAggregateAllArgsFunctionOid(); + } + else + { + functionOid = BsonFirstNOnSortedAggregateAllArgsFunctionOid(); + } + + return HandleDollarFirstLastOperators(opValue, context, "$firstN", functionOid, + isNOperator); +} + + +/* + * Handler for $lastN window aggregation operator. + * input format: + * { + * $lastN: + * { + * input: , + * n: + * } + * } + */ +static WindowFunc * +HandleDollarLastNWindowOperator(const bson_value_t *opValue, + WindowOperatorContext *context) +{ + if (!IsClusterVersionAtleastThis(1, 22, 0)) + { + ereport(ERROR, (errcode(ERRCODE_HELIO_COMMANDNOTSUPPORTED), + errmsg("$lastN is not supported yet"))); + } + + bool isNOperator = true; + Oid functionOid; + if (context->sortOptions != NIL && list_length(context->sortOptions) > 0) + { + functionOid = BsonLastNAggregateAllArgsFunctionOid(); + } + else + { + functionOid = BsonLastNOnSortedAggregateAllArgsFunctionOid(); + } + + return HandleDollarFirstLastOperators(opValue, context, "$lastN", functionOid, + isNOperator); +} + + +/* + * Common handler for $first(N) and $last(N) operators. + * Parses the spec and generates the WindowFunc for the respective bson aggregate function. + * + * TODO: Support n(elementsToFetch) as an expression + */ +static WindowFunc * +HandleDollarFirstLastOperators(const bson_value_t *opValue, + WindowOperatorContext *context, + const char *opName, + Oid aggregateFunctionOid, + bool isNOperator) +{ + WindowFunc *windowFunc = makeNode(WindowFunc); + windowFunc->wintype = BsonTypeId(); + windowFunc->winfnoid = aggregateFunctionOid; + windowFunc->winref = context->winRef; + windowFunc->winstar = false; + windowFunc->winagg = true; + + Const *constValue, *nConst; + if (isNOperator) + { + bson_value_t input = { 0 }; + bson_value_t elementsToFetch = { 0 }; + ParseInputForNGroupAccumulators(opValue, &input, &elementsToFetch, opName); + ValidateElementForNGroupAccumulators(&elementsToFetch, opName); + nConst = makeConst(INT8OID, -1, InvalidOid, sizeof(int64_t), + Int64GetDatum(elementsToFetch.value.v_int64), false, + true); + + constValue = MakeBsonConst(BsonValueToDocumentPgbson(&input)); + } + else + { + constValue = MakeBsonConst(BsonValueToDocumentPgbson(opValue)); + } + + if (context->sortOptions != NIL && list_length(context->sortOptions) > 0) + { + int nelems = list_length(context->sortOptions); + Datum *sortDatumArray = palloc(sizeof(Datum) * nelems); + + ListCell *lc; + int i = 0; + foreach(lc, context->sortOptions) + { + SetWindowFieldSortOption *sortOption = + (SetWindowFieldSortOption *) lfirst(lc); + sortDatumArray[i] = sortOption->sortSpecConst->constvalue; + i++; + } + + ArrayType *arrayValue = construct_array(sortDatumArray, nelems, BsonTypeId(), -1, + false, TYPALIGN_INT); + Const *sortArrayConst = makeConst(GetBsonArrayTypeOid(), -1, InvalidOid, -1, + PointerGetDatum(arrayValue), false, false); + + if (isNOperator) + { + windowFunc->args = list_make4(context->docExpr, nConst, sortArrayConst, + constValue); + } + else + { + windowFunc->args = list_make3(context->docExpr, sortArrayConst, constValue); + } + } + else + { + if (isNOperator) + { + windowFunc->args = list_make3(context->docExpr, nConst, constValue); + } + else + { + windowFunc->args = list_make2(context->docExpr, constValue); + } + } + + return windowFunc; +} + + /* * Handle for const fill window aggregation operator. * Returns the WindowFunc for bson aggregate function `bsonsum` diff --git a/pg_helio_api/src/aggregation/bson_sorted_accumulator.c b/pg_helio_api/src/aggregation/bson_sorted_accumulator.c index aaff2f6a..fe38be8e 100644 --- a/pg_helio_api/src/aggregation/bson_sorted_accumulator.c +++ b/pg_helio_api/src/aggregation/bson_sorted_accumulator.c @@ -558,25 +558,42 @@ BsonOrderTransition(PG_FUNCTION_ARGS, bool invertSort, bool isSingle, bool * The args are: * 0) The current aggregation state * 1) The document/evaluated expression which will eventually be returned - * For isSingle == 'false' + * + * For isSingle == 'true' && storeInputExpression == 'true + * 2) The input expression to be applied on the results. + * + * For isSingle == 'false' && storeInputExpression == 'true * 2) The number of documents to be returned or 'N' + * 3) The input expression to be applied on the results. */ Datum BsonOrderTransitionOnSorted(PG_FUNCTION_ARGS, bool invertSort, bool isSingle) { MemoryContext aggregateContext; - if (!AggCheckCallContext(fcinfo, &aggregateContext)) + int aggContext = AggCheckCallContext(fcinfo, &aggregateContext); + + if (!aggContext) { ereport(ERROR, (errcode(ERRCODE_INTERNAL_ERROR), errmsg( "aggregate function called in non-aggregate context"))); } + bool storeInputExpression = false; + + /* We store input expression in $setWindowFields context */ + if (aggContext == AGG_CONTEXT_WINDOW) + { + storeInputExpression = true; + } + bytea *byteArray = PG_ARGISNULL(0) ? NULL : PG_GETARG_BYTEA_P(0); pgbson *newValue = PG_GETARG_MAYBE_NULL_PGBSON(1); int64 returnCount = 1; char *sourcePtr; int64 currentCount = 0; int64 copySize = 0; + pgbson *inputExpression; + int64 inputExpressionSize = 0; /* * If no sort keys are provided, or the data is pre-sorted we do the following: @@ -584,7 +601,7 @@ BsonOrderTransitionOnSorted(PG_FUNCTION_ARGS, bool invertSort, bool isSingle) * (1.a.) keep ignoring any new element for invertSort = false * (1.b.) keep replacing the lease recent value with the new one for invertSort = true * Format is: - * VARHDR | ByteSize | ReturnCount |CurrentCount | Result 1 | Size 1 | Result 2 | Size 2 | ... + * VARHDR | ByteSize | ReturnCount | CurrentCount | InputExpressionSize | InputExpression | Result 1 | Size 1 | Result 2 | Size 2 | ... */ /* Get the current count and setup*/ @@ -597,19 +614,44 @@ BsonOrderTransitionOnSorted(PG_FUNCTION_ARGS, bool invertSort, bool isSingle) { /* The 3rd argument is number of results to return */ returnCount = PG_GETARG_INT64(2); + inputExpression = storeInputExpression ? PG_GETARG_MAYBE_NULL_PGBSON(3) : + NULL; + } + else + { + inputExpression = storeInputExpression ? PG_GETARG_MAYBE_NULL_PGBSON(2) : + NULL; + } + + if (inputExpression != NULL) + { + inputExpressionSize = VARSIZE(inputExpression); } } else { sourcePtr = (char *) VARDATA(byteArray); - /* Copy size is total size - VARHDRSZ, the 3 ints we are extracting, and ptr. */ - copySize = *(int64 *) sourcePtr - sizeof(int64) * 3 - VARHDRSZ; + /* Copy size is total size - VARHDRSZ, the 4 ints we are extracting, and ptr. */ + copySize = *(int64 *) sourcePtr - sizeof(int64) * 4 - VARHDRSZ; sourcePtr += sizeof(int64); returnCount = *(int64 *) sourcePtr; sourcePtr += sizeof(int64); currentCount = *(int64 *) sourcePtr; sourcePtr += sizeof(int64); + inputExpressionSize = *(int64 *) sourcePtr; + sourcePtr += sizeof(int64); + + if (inputExpressionSize != 0) + { + inputExpression = (pgbson *) sourcePtr; + sourcePtr += inputExpressionSize; + copySize -= inputExpressionSize; + } + else + { + inputExpression = NULL; + } if (currentCount > returnCount) { @@ -637,8 +679,8 @@ BsonOrderTransitionOnSorted(PG_FUNCTION_ARGS, bool invertSort, bool isSingle) } } - /* Output is VARHDR | ByteSize | ReturnCount | CurrentCount | values... */ - uint32 totalSize = VARHDRSZ + sizeof(int64) * 3 + copySize; + /* Output is VARHDR | ByteSize | ReturnCount | CurrentCount | InputExpressionSize | InputExpression | values... */ + uint32 totalSize = VARHDRSZ + sizeof(int64) * 4 + copySize + inputExpressionSize; /* Add in newValue to total size */ if (newValue != NULL) @@ -666,6 +708,15 @@ BsonOrderTransitionOnSorted(PG_FUNCTION_ARGS, bool invertSort, bool isSingle) returnDataPtr += sizeof(int64); *((int64 *) (returnDataPtr)) = currentCount; returnDataPtr += sizeof(int64); + *((int64 *) (returnDataPtr)) = inputExpressionSize; + returnDataPtr += sizeof(int64); + + /* Copy input expression to returnDataPtr */ + if (inputExpression != NULL) + { + memcpy(returnDataPtr, inputExpression, inputExpressionSize); + returnDataPtr += inputExpressionSize; + } /* Need to copy first so we don't overwrite with newValue if we are reusing the array. */ @@ -928,13 +979,27 @@ BsonOrderFinal(PG_FUNCTION_ARGS, bool isSingle) /* If there were no regular rows, or the last result was NULL, the result is $null */ if (returnNull) { - /* Mongo returns $null for empty sets */ - pgbsonelement finalValue; - finalValue.path = ""; - finalValue.pathLength = 0; - finalValue.bsonValue.value_type = BSON_TYPE_NULL; + pgbson *finalPgbson; - PG_RETURN_POINTER(PgbsonElementToPgbson(&finalValue)); + if (isSingle) + { + /* Mongo returns $null for empty sets */ + pgbsonelement finalValue; + finalValue.path = ""; + finalValue.pathLength = 0; + finalValue.bsonValue.value_type = BSON_TYPE_NULL; + finalPgbson = PgbsonElementToPgbson(&finalValue); + } + else + { + /* empty array */ + pgbson_writer writer; + PgbsonWriterInit(&writer); + PgbsonWriterAppendEmptyArray(&writer, "", 0); + finalPgbson = PgbsonWriterGetPgbson(&writer); + } + + PG_RETURN_POINTER(finalPgbson); } AggregationExpressionData *aggregationExpressionState = NULL; @@ -1077,10 +1142,21 @@ BsonOrderFinal(PG_FUNCTION_ARGS, bool isSingle) Datum BsonOrderFinalOnSorted(PG_FUNCTION_ARGS, bool isSingle) { + MemoryContext aggregateContext; + int aggContext = AggCheckCallContext(fcinfo, &aggregateContext); + + if (!aggContext) + { + ereport(ERROR, (errcode(ERRCODE_INTERNAL_ERROR), errmsg( + "aggregate function called in non-aggregate context"))); + } + bool returnNull = false; bytea *byteArray = PG_GETARG_BYTEA_P(0); char *sourcePtr; int64 currentCount = 0; + pgbson *inputExpression = NULL; + int64 inputExpressionSize = 0; if (byteArray == NULL) { @@ -1095,6 +1171,15 @@ BsonOrderFinalOnSorted(PG_FUNCTION_ARGS, bool isSingle) sourcePtr += sizeof(int64); currentCount = *(int64 *) sourcePtr; sourcePtr += sizeof(int64); + inputExpressionSize = *(int64 *) sourcePtr; + sourcePtr += sizeof(int64); + + /* Extract inputExpression from sourcePtr */ + if (inputExpressionSize != 0) + { + inputExpression = (pgbson *) sourcePtr; + sourcePtr += inputExpressionSize; + } if (isSingle) { @@ -1116,19 +1201,100 @@ BsonOrderFinalOnSorted(PG_FUNCTION_ARGS, bool isSingle) } } + AggregationExpressionData *aggregationExpressionState = NULL; + StringView path; + ExpressionVariableContext *variableContext = NULL; + + /* Cache aggregationExpressionState for $setWindowFields to avoid re-parsing the expression for each row/partition. + * aggregationExpressionState holds the parsed input expression which stays the same for all rows/partitions. + */ + if (aggContext == AGG_CONTEXT_WINDOW) + { + if (inputExpression != NULL) + { + pgbsonelement element; + PgbsonToSinglePgbsonElement(inputExpression, &element); + + path = (StringView) { + .length = element.pathLength, + .string = element.path, + }; + + /* + * Use numArgs as 0 as we want to return true from IsSafeToReuseFmgrFunctionExtraMultiArgs(). + * This is to avoid the check for the node being a const or a Param of type extern as the caller knows its safe to reuse + * as this is the common expression for all rows inside the bytea returned by transition function. + */ + int argPositions[1] = { 0 }; + int numArgs = 0; + ParseAggregationExpressionContext context = { 0 }; + + SetCachedFunctionStateMultiArgs( + aggregationExpressionState, + AggregationExpressionData, + argPositions, + numArgs, + ParseInputExpressionAndPersistValue, + &element.bsonValue, + &context); + + if (aggregationExpressionState == NULL) + { + aggregationExpressionState = palloc0(sizeof(AggregationExpressionData)); + ParseInputExpressionAndPersistValue( + aggregationExpressionState, + &element.bsonValue, + &context); + } + } + } + /* If there were no regular rows, or the last result was NULL, the result is $null */ if (returnNull) { - /* Mongo returns $null for empty sets */ - pgbsonelement finalValue; - finalValue.path = ""; - finalValue.pathLength = 0; - finalValue.bsonValue.value_type = BSON_TYPE_NULL; + pgbson *finalPgbson; - PG_RETURN_POINTER(PgbsonElementToPgbson(&finalValue)); + if (isSingle) + { + /* Mongo returns $null for empty sets */ + pgbsonelement finalValue; + finalValue.path = ""; + finalValue.pathLength = 0; + finalValue.bsonValue.value_type = BSON_TYPE_NULL; + finalPgbson = PgbsonElementToPgbson(&finalValue); + } + else + { + /* empty array */ + pgbson_writer writer; + PgbsonWriterInit(&writer); + PgbsonWriterAppendEmptyArray(&writer, "", 0); + finalPgbson = PgbsonWriterGetPgbson(&writer); + } + + PG_RETURN_POINTER(finalPgbson); } else if (isSingle) { + if (aggContext == AGG_CONTEXT_WINDOW) + { + if (inputExpression != NULL) + { + /* Apply the inputExpression to the result documents to calculate result for $first/$last */ + bool isNullOnEmpty = true; + pgbson_writer writer; + PgbsonWriterInit(&writer); + EvaluateAggregationExpressionDataToWriter(aggregationExpressionState, + (pgbson *) sourcePtr, + path, + &writer, + variableContext, isNullOnEmpty); + + pgbson *result = PgbsonWriterGetPgbson(&writer); + PG_RETURN_POINTER(result); + } + } + PG_RETURN_POINTER((pgbson *) sourcePtr); } else @@ -1149,7 +1315,32 @@ BsonOrderFinalOnSorted(PG_FUNCTION_ARGS, bool isSingle) } else { - PgbsonArrayWriterWriteDocument(&arrayWriter, (pgbson *) sourcePtr); + if (aggContext == AGG_CONTEXT_WINDOW) + { + if (inputExpression != NULL) + { + /* Apply the inputExpression to the result documents to calculate result for $firstN/$lastN */ + bool isNullOnEmpty = true; + pgbson_writer innerWriter; + PgbsonWriterInit(&innerWriter); + EvaluateAggregationExpressionDataToWriter( + aggregationExpressionState, + (pgbson *) sourcePtr, + path, + &innerWriter, + variableContext, + isNullOnEmpty); + pgbson *resultpg = PgbsonWriterGetPgbson(&innerWriter); + pgbsonelement element; + PgbsonToSinglePgbsonElement(resultpg, &element); + PgbsonArrayWriterWriteValue(&arrayWriter, &element.bsonValue); + } + } + else + { + PgbsonArrayWriterWriteDocument(&arrayWriter, (pgbson *) sourcePtr); + } + sourcePtr += VARSIZE(sourcePtr); sourcePtr += sizeof(uint32); } diff --git a/pg_helio_api/src/metadata/metadata_cache.c b/pg_helio_api/src/metadata/metadata_cache.c index 5ec226a7..421d248a 100644 --- a/pg_helio_api/src/metadata/metadata_cache.c +++ b/pg_helio_api/src/metadata/metadata_cache.c @@ -711,6 +711,12 @@ typedef struct HelioApiOidCacheData /* OID of the BSONLASTONSORTED aggregate function */ Oid ApiCatalogBsonLastOnSortedAggregateFunctionOid; + /* OID of the BSONFIRSTONSORTED aggregate function */ + Oid BsonFirstOnSortedAggregateAllArgsFunctionOid; + + /* OID of the BSONLASTONSORTED aggregate function */ + Oid BsonLastOnSortedAggregateAllArgsFunctionOid; + /* OID of the BSONFIRST aggregate function */ Oid ApiCatalogBsonFirstAggregateFunctionOid; @@ -718,10 +724,10 @@ typedef struct HelioApiOidCacheData Oid ApiCatalogBsonLastAggregateFunctionOid; /* OID of the BSONFIRST aggregate function with 3 args */ - Oid ApiCatalogBsonFirstAggregateAllArgsFunctionOid; + Oid BsonFirstAggregateAllArgsFunctionOid; /* OID of the BSONLAST aggregate function with 3 args */ - Oid ApiCatalogBsonLastAggregateAllArgsFunctionOid; + Oid BsonLastAggregateAllArgsFunctionOid; /* OID of the BSONFIRSTNONSORTED aggregate function */ Oid ApiCatalogBsonFirstNOnSortedAggregateFunctionOid; @@ -729,6 +735,12 @@ typedef struct HelioApiOidCacheData /* OID of the BSONLASTNONSORTED aggregate function */ Oid ApiCatalogBsonLastNOnSortedAggregateFunctionOid; + /* OID of the BSONFIRSTNONSORTED aggregate function */ + Oid BsonFirstNOnSortedAggregateAllArgsFunctionOid; + + /* OID of the BSONLASTNONSORTED aggregate function */ + Oid BsonLastNOnSortedAggregateAllArgsFunctionOid; + /* OID of the BSONFIRSTN aggregate function */ Oid ApiCatalogBsonFirstNAggregateFunctionOid; @@ -736,10 +748,10 @@ typedef struct HelioApiOidCacheData Oid ApiCatalogBsonLastNAggregateFunctionOid; /* OID of the BSONFIRSTN aggregate function with 4 args */ - Oid ApiCatalogBsonFirstNAggregateAllArgsFunctionOid; + Oid BsonFirstNAggregateAllArgsFunctionOid; /* OID of the BSONLASTN aggregate function with 4 args */ - Oid ApiCatalogBsonLastNAggregateAllArgsFunctionOid; + Oid BsonLastNAggregateAllArgsFunctionOid; /* OID of the bson_add_to_set function. */ Oid ApiCatalogBsonAddToSetAggregateFunctionOid; @@ -3692,12 +3704,93 @@ GetBsonFirstNLastNAggregateFunctionOid(Oid *function, bool allArgs, char *aggreg } +/* Returns the correct aggregate function Oid for top(N)/bottom(N)/first(N)/last(N) based on number of arguments*/ +static Oid +GetBsonFirstNLastNOnSortedAggregateFunctionOid(Oid *function, bool allArgs, + char *aggregateName) +{ + InitializeHelioApiExtensionCache(); + + String *schemaName; + if (allArgs) + { + schemaName = makeString("helio_api_internal"); + } + else + { + schemaName = makeString(ApiCatalogSchemaName); + } + + if (*function == InvalidOid) + { + ObjectWithArgs *objectWithArgs = makeNode(ObjectWithArgs); + List *functionNameList = list_make2(schemaName, + makeString(aggregateName)); + + objectWithArgs->objname = functionNameList; + + FunctionParameter *inBsonArgParam = makeNode(FunctionParameter); + inBsonArgParam->argType = ParseTypeNameCore(FullBsonTypeName); + inBsonArgParam->mode = FUNC_PARAM_IN; + + if (strcmp(aggregateName, "bsonfirstnonsorted") == 0 || + strcmp(aggregateName, "bsonlastnonsorted") == 0) + { + objectWithArgs->objargs = + list_make2(ParseTypeNameCore(FullBsonTypeName), + ParseTypeNameCore("bigint")); + + FunctionParameter *inIntArgParam = makeNode(FunctionParameter); + inIntArgParam->argType = ParseTypeNameCore("bigint"); + inIntArgParam->mode = FUNC_PARAM_IN; + + objectWithArgs->objfuncargs = list_make2(inBsonArgParam, inIntArgParam); + } + else + { + objectWithArgs->objargs = + list_make1(ParseTypeNameCore(FullBsonTypeName)); + objectWithArgs->objfuncargs = list_make1(inBsonArgParam); + } + + if (allArgs) + { + objectWithArgs->objargs = lappend(objectWithArgs->objargs, ParseTypeNameCore( + FullBsonTypeName)); + + FunctionParameter *inBsonArgExpressionParam = makeNode(FunctionParameter); + inBsonArgExpressionParam->argType = ParseTypeNameCore(FullBsonTypeName); + inBsonArgExpressionParam->mode = FUNC_PARAM_IN; + + objectWithArgs->objfuncargs = lappend(objectWithArgs->objfuncargs, + inBsonArgExpressionParam); + } + + bool missingOK = false; + *function = LookupFuncWithArgs(OBJECT_AGGREGATE, objectWithArgs, missingOK); + } + + return *function; +} + + Oid BsonFirstOnSortedAggregateFunctionOid(void) { - return GetAggregateFunctionByName( - &Cache.ApiCatalogBsonFirstOnSortedAggregateFunctionOid, - ApiCatalogSchemaName, "bsonfirstonsorted"); + bool allArgs = false; + return GetBsonFirstNLastNOnSortedAggregateFunctionOid( + &Cache.ApiCatalogBsonFirstOnSortedAggregateFunctionOid, allArgs, + "bsonfirstonsorted"); +} + + +Oid +BsonFirstOnSortedAggregateAllArgsFunctionOid(void) +{ + bool allArgs = true; + return GetBsonFirstNLastNOnSortedAggregateFunctionOid( + &Cache.BsonFirstOnSortedAggregateAllArgsFunctionOid, allArgs, + "bsonfirstonsorted"); } @@ -3715,7 +3808,7 @@ BsonFirstAggregateAllArgsFunctionOid(void) { bool allArgs = true; return GetBsonFirstNLastNAggregateFunctionOid( - &Cache.ApiCatalogBsonFirstAggregateFunctionOid, allArgs, "bsonfirst"); + &Cache.BsonFirstAggregateAllArgsFunctionOid, allArgs, "bsonfirst"); } @@ -3733,16 +3826,27 @@ BsonLastAggregateAllArgsFunctionOid(void) { bool allArgs = true; return GetBsonFirstNLastNAggregateFunctionOid( - &Cache.ApiCatalogBsonLastAggregateFunctionOid, allArgs, "bsonlast"); + &Cache.BsonLastAggregateAllArgsFunctionOid, allArgs, "bsonlast"); } Oid BsonLastOnSortedAggregateFunctionOid(void) { - return GetAggregateFunctionByName( - &Cache.ApiCatalogBsonLastOnSortedAggregateFunctionOid, - ApiCatalogSchemaName, "bsonlastonsorted"); + bool allArgs = false; + return GetBsonFirstNLastNOnSortedAggregateFunctionOid( + &Cache.ApiCatalogBsonLastOnSortedAggregateFunctionOid, allArgs, + "bsonlastonsorted"); +} + + +Oid +BsonLastOnSortedAggregateAllArgsFunctionOid(void) +{ + bool allArgs = true; + return GetBsonFirstNLastNOnSortedAggregateFunctionOid( + &Cache.BsonLastOnSortedAggregateAllArgsFunctionOid, allArgs, + "bsonlastonsorted"); } @@ -3760,16 +3864,27 @@ BsonFirstNAggregateAllArgsFunctionOid(void) { bool allArgs = true; return GetBsonFirstNLastNAggregateFunctionOid( - &Cache.ApiCatalogBsonFirstNAggregateAllArgsFunctionOid, allArgs, "bsonfirstn"); + &Cache.BsonFirstNAggregateAllArgsFunctionOid, allArgs, "bsonfirstn"); } Oid BsonFirstNOnSortedAggregateFunctionOid(void) { - return GetAggregateFunctionByName( - &Cache.ApiCatalogBsonFirstNOnSortedAggregateFunctionOid, - ApiCatalogSchemaName, "bsonfirstnonsorted"); + bool allArgs = false; + return GetBsonFirstNLastNOnSortedAggregateFunctionOid( + &Cache.ApiCatalogBsonFirstNOnSortedAggregateFunctionOid, allArgs, + "bsonfirstnonsorted"); +} + + +Oid +BsonFirstNOnSortedAggregateAllArgsFunctionOid(void) +{ + bool allArgs = true; + return GetBsonFirstNLastNOnSortedAggregateFunctionOid( + &Cache.BsonFirstNOnSortedAggregateAllArgsFunctionOid, allArgs, + "bsonfirstnonsorted"); } @@ -3787,16 +3902,27 @@ BsonLastNAggregateAllArgsFunctionOid(void) { bool allArgs = true; return GetBsonFirstNLastNAggregateFunctionOid( - &Cache.ApiCatalogBsonLastNAggregateAllArgsFunctionOid, allArgs, "bsonlastn"); + &Cache.BsonLastNAggregateAllArgsFunctionOid, allArgs, "bsonlastn"); } Oid BsonLastNOnSortedAggregateFunctionOid(void) { - return GetAggregateFunctionByName( - &Cache.ApiCatalogBsonLastNOnSortedAggregateFunctionOid, - ApiCatalogSchemaName, "bsonlastnonsorted"); + bool allArgs = false; + return GetBsonFirstNLastNOnSortedAggregateFunctionOid( + &Cache.ApiCatalogBsonLastNOnSortedAggregateFunctionOid, allArgs, + "bsonlastnonsorted"); +} + + +Oid +BsonLastNOnSortedAggregateAllArgsFunctionOid(void) +{ + bool allArgs = true; + return GetBsonFirstNLastNOnSortedAggregateFunctionOid( + &Cache.BsonLastNOnSortedAggregateAllArgsFunctionOid, allArgs, + "bsonlastnonsorted"); } diff --git a/pg_helio_api/src/operators/bson_expression_array_operators.c b/pg_helio_api/src/operators/bson_expression_array_operators.c index c3ef27ef..4b3bb5de 100644 --- a/pg_helio_api/src/operators/bson_expression_array_operators.c +++ b/pg_helio_api/src/operators/bson_expression_array_operators.c @@ -25,6 +25,7 @@ #include "utils/heap_utils.h" #include "planner/helio_planner.h" +#include "aggregation/bson_aggregation_pipeline.h" #define MAX_BUFFER_SIZE_DOLLAR_RANGE (64 * 1024 * 1024) #define EMPTY_BSON_ARRAY_SIZE_BYTES 5 /* size of empty array is fixed as 5 bytes. */ @@ -197,10 +198,6 @@ static void ParseDollarMaxMinN(const bson_value_t *argument, bool isMaxN, ParseAggregationExpressionContext *context); static pgbsonelement ParseElementFromObjectForArrayToObject(const bson_value_t *element); static pgbsonelement ParseElementFromArrayForArrayToObject(const bson_value_t *element); -static void ParseInputDocumentForFirstAndLastN(const bson_value_t *inputDocument, - bson_value_t *input, - bson_value_t *elementsToFetch, const - char *opName); static void ValidateElementForFirstAndLastN(bson_value_t *elementsToFetch, const char *opName); static void FillResultForDollarFirstAndLastN(bson_value_t *input, @@ -1452,8 +1449,8 @@ ParseDollarFirstN(const bson_value_t *inputDocument, AggregationExpressionData * data->operator.returnType = BSON_TYPE_ARRAY; - ParseInputDocumentForFirstAndLastN(inputDocument, &input, - &elementsToFetch, "$firstN"); + ParseInputForNGroupAccumulators(inputDocument, &input, + &elementsToFetch, "$firstN"); DollarFirstNLastNArguments *arguments = palloc0(sizeof(DollarFirstNLastNArguments)); @@ -1533,8 +1530,8 @@ ParseDollarLastN(const bson_value_t *inputDocument, AggregationExpressionData *d data->operator.returnType = BSON_TYPE_ARRAY; - ParseInputDocumentForFirstAndLastN(inputDocument, &input, - &elementsToFetch, "$lastN"); + ParseInputForNGroupAccumulators(inputDocument, &input, + &elementsToFetch, "$lastN"); DollarFirstNLastNArguments *arguments = palloc0(sizeof(DollarFirstNLastNArguments)); @@ -1601,68 +1598,6 @@ HandlePreParsedDollarLastN(pgbson *doc, void *arguments, } -/** - * Parses the input document for FirstN and LastN array expression operator and extracts the value for input and n. - * @param inputDocument: input document for the $firstN operator - * @param input: this is a pointer which after parsing will hold array expression - * @param elementsToFetch: this is a pointer which after parsing will hold n i.e. how many elements to fetch for result - * @param opName: this contains the name of the operator for error msg formatting purposes. This value is supposed to be $firstN/$lastN. - */ -static void -ParseInputDocumentForFirstAndLastN(const bson_value_t *inputDocument, bson_value_t *input, - bson_value_t *elementsToFetch, const char *opName) -{ - if (inputDocument->value_type != BSON_TYPE_DOCUMENT) - { - ereport(ERROR, (errcode(ERRCODE_HELIO_LOCATION5787801), errmsg( - "specification must be an object; found %s :%s", - opName, BsonValueToJsonForLogging(inputDocument)), - errdetail_log( - "specification must be an object; found opname:%s input type:%s", - opName, BsonTypeName(inputDocument->value_type)))); - } - - bson_iter_t docIter; - BsonValueInitIterator(inputDocument, &docIter); - - while (bson_iter_next(&docIter)) - { - const char *key = bson_iter_key(&docIter); - if (strcmp(key, "input") == 0) - { - *input = *bson_iter_value(&docIter); - } - else if (strcmp(key, "n") == 0) - { - *elementsToFetch = *bson_iter_value(&docIter); - } - else - { - ereport(ERROR, (errcode(ERRCODE_HELIO_LOCATION5787901), errmsg( - "%s found an unknown argument: %s", opName, key), - errdetail_log( - "%s found an unknown argument, while parsing request", - opName))); - } - } - - /** - * Validation check to see if input and elements to fetch are present otherwise throw error. - */ - if (input->value_type == BSON_TYPE_EOD) - { - ereport(ERROR, (errcode(ERRCODE_HELIO_LOCATION5787907), errmsg( - "%s requires an 'input' field", opName))); - } - - if (elementsToFetch->value_type == BSON_TYPE_EOD) - { - ereport(ERROR, (errcode(ERRCODE_HELIO_LOCATION5787906), errmsg( - "%s requires an 'n' field", opName))); - } -} - - /** * This function validates and throws error in case bson type is not a numeric > 0 and less than max value of int64 i.e. 9223372036854775807 */ diff --git a/pg_helio_core/include/utils/helio_codes.txt b/pg_helio_core/include/utils/helio_codes.txt index 770db13c..cabf82ab 100644 --- a/pg_helio_core/include/utils/helio_codes.txt +++ b/pg_helio_core/include/utils/helio_codes.txt @@ -487,3 +487,4 @@ Location5624900,M00DG,5624900,485 Location5624901,M00DH,5624901,486 Location6050202,M00DI,6050202,487 Location6050204,M00DJ,6050204,488 +Location5788604,M00DK,5788604,489 diff --git a/pg_helio_core/include/utils/helio_errors.h b/pg_helio_core/include/utils/helio_errors.h index 967a0594..527071f3 100644 --- a/pg_helio_core/include/utils/helio_errors.h +++ b/pg_helio_core/include/utils/helio_errors.h @@ -1530,4 +1530,7 @@ typedef int HelioErrorEreportCode; #define ERRCODE_HELIO_LOCATION6050204 MAKE_SQLSTATE('M', '0', '0', 'D', 'J') #define MONGO_CODE_LOCATION6050204 6050204 +#define ERRCODE_HELIO_LOCATION5788604 MAKE_SQLSTATE('M', '0', '0', 'D', 'K') +#define MONGO_CODE_LOCATION5788604 5788604 + #endif