diff --git a/mongoerrors.csv b/mongoerrors.csv index eb235dc0..d8483c95 100644 --- a/mongoerrors.csv +++ b/mongoerrors.csv @@ -424,6 +424,9 @@ Location5339902,5339902,419 Location5371601,5371601,454 Location5371602,5371602,455 Location5371603,5371603,456 +Location5423900,5423900,481 +Location5423901,5423901,482 +Location5423902,5423902,483 Location5429413,5429413,420 Location5429414,5429414,421 Location5429513,5429513,422 @@ -438,6 +441,9 @@ Location5439015,5439015,430 Location5439016,5439016,431 Location5439017,5439017,432 Location5439018,5439018,433 +Location5490710,5490710,484 +Location5624900,5624900,485 +Location5624901,5624901,486 Location5626500,5626500,434 Location5654600,5654600,435 Location5654601,5654601,436 @@ -478,4 +484,4 @@ Location6045000,6045000,70 Location6050106,6050106,459 Location6053600,6053600,478 Location6586400,6586400,479 -Location8993000,8993000,480 \ No newline at end of file +Location8993000,8993000,480 diff --git a/pg_helio_api/include/metadata/metadata_cache.h b/pg_helio_api/include/metadata/metadata_cache.h index 028da088..9955ec7d 100644 --- a/pg_helio_api/include/metadata/metadata_cache.h +++ b/pg_helio_api/include/metadata/metadata_cache.h @@ -283,6 +283,8 @@ Oid BsonDollarUnwindWithOptionsFunctionOid(void); Oid BsonDollarReplaceRootFunctionOid(void); Oid BsonDollarReplaceRootWithLetFunctionOid(void); Oid BsonSumAggregateFunctionOid(void); +Oid BsonIntegralAggregateFunctionOid(void); +Oid BsonDerivativeAggregateFunctionOid(void); Oid BsonAvgAggregateFunctionOid(void); Oid BsonRepathAndBuildFunctionOid(void); Oid BsonExpressionGetFunctionOid(void); diff --git a/pg_helio_api/sql/pg_helio_api--1.21-0--1.22-0.sql b/pg_helio_api/sql/pg_helio_api--1.21-0--1.22-0.sql index cd6fa139..f453afaf 100644 --- a/pg_helio_api/sql/pg_helio_api--1.21-0--1.22-0.sql +++ b/pg_helio_api/sql/pg_helio_api--1.21-0--1.22-0.sql @@ -2,6 +2,7 @@ SET search_path TO helio_api; #include "udfs/aggregation/bson_densify_functions--1.22-0.sql" #include "udfs/aggregation/window_aggregate_support--1.22-0.sql" +#include "udfs/aggregation/window_aggregates--1.22-0.sql" #include "udfs/aggregation/group_aggregates_support--1.22-0.sql" #include "udfs/aggregation/group_aggregates--1.22-0.sql" diff --git a/pg_helio_api/sql/udfs/aggregation/window_aggregate_support--1.22-0.sql b/pg_helio_api/sql/udfs/aggregation/window_aggregate_support--1.22-0.sql index 53824b3b..04906329 100644 --- a/pg_helio_api/sql/udfs/aggregation/window_aggregate_support--1.22-0.sql +++ b/pg_helio_api/sql/udfs/aggregation/window_aggregate_support--1.22-0.sql @@ -87,4 +87,22 @@ CREATE OR REPLACE FUNCTION helio_api_internal.bson_shift(__CORE_SCHEMA__.bson, i LANGUAGE c STABLE WINDOW -AS 'MODULE_PATHNAME', $function$bson_shift$function$; \ No newline at end of file +AS 'MODULE_PATHNAME', $function$bson_shift$function$; + +CREATE OR REPLACE FUNCTION helio_api_internal.bson_derivative_transition(bytea, __CORE_SCHEMA__.bson, __CORE_SCHEMA__.bson, bigint) + RETURNS bytea + LANGUAGE c + STABLE +AS 'MODULE_PATHNAME', $function$bson_derivative_transition$function$; + +CREATE OR REPLACE FUNCTION helio_api_internal.bson_integral_transition(bytea, __CORE_SCHEMA__.bson, __CORE_SCHEMA__.bson, bigint) + RETURNS bytea + LANGUAGE c + STABLE +AS 'MODULE_PATHNAME', $function$bson_integral_transition$function$; + +CREATE OR REPLACE FUNCTION helio_api_internal.bson_integral_derivative_final(bytea) + RETURNS __CORE_SCHEMA__.bson + LANGUAGE c + STABLE +AS 'MODULE_PATHNAME', $function$bson_integral_derivative_final$function$; diff --git a/pg_helio_api/sql/udfs/aggregation/window_aggregate_support--latest.sql b/pg_helio_api/sql/udfs/aggregation/window_aggregate_support--latest.sql index 53824b3b..04906329 100644 --- a/pg_helio_api/sql/udfs/aggregation/window_aggregate_support--latest.sql +++ b/pg_helio_api/sql/udfs/aggregation/window_aggregate_support--latest.sql @@ -87,4 +87,22 @@ CREATE OR REPLACE FUNCTION helio_api_internal.bson_shift(__CORE_SCHEMA__.bson, i LANGUAGE c STABLE WINDOW -AS 'MODULE_PATHNAME', $function$bson_shift$function$; \ No newline at end of file +AS 'MODULE_PATHNAME', $function$bson_shift$function$; + +CREATE OR REPLACE FUNCTION helio_api_internal.bson_derivative_transition(bytea, __CORE_SCHEMA__.bson, __CORE_SCHEMA__.bson, bigint) + RETURNS bytea + LANGUAGE c + STABLE +AS 'MODULE_PATHNAME', $function$bson_derivative_transition$function$; + +CREATE OR REPLACE FUNCTION helio_api_internal.bson_integral_transition(bytea, __CORE_SCHEMA__.bson, __CORE_SCHEMA__.bson, bigint) + RETURNS bytea + LANGUAGE c + STABLE +AS 'MODULE_PATHNAME', $function$bson_integral_transition$function$; + +CREATE OR REPLACE FUNCTION helio_api_internal.bson_integral_derivative_final(bytea) + RETURNS __CORE_SCHEMA__.bson + LANGUAGE c + STABLE +AS 'MODULE_PATHNAME', $function$bson_integral_derivative_final$function$; diff --git a/pg_helio_api/sql/udfs/aggregation/window_aggregates--1.22-0.sql b/pg_helio_api/sql/udfs/aggregation/window_aggregates--1.22-0.sql new file mode 100644 index 00000000..29b1b234 --- /dev/null +++ b/pg_helio_api/sql/udfs/aggregation/window_aggregates--1.22-0.sql @@ -0,0 +1,44 @@ +CREATE OR REPLACE AGGREGATE helio_api_internal.BSONCOVARIANCEPOP(__CORE_SCHEMA__.bson, __CORE_SCHEMA__.bson) +( + SFUNC = helio_api_internal.bson_covariance_pop_samp_transition, + FINALFUNC = helio_api_internal.bson_covariance_pop_final, + MSFUNC = helio_api_internal.bson_covariance_pop_samp_transition, + MFINALFUNC = helio_api_internal.bson_covariance_pop_final, + MINVFUNC = helio_api_internal.bson_covariance_pop_samp_invtransition, + stype = bytea, + mstype = bytea, + COMBINEFUNC = helio_api_internal.bson_covariance_pop_samp_combine, + PARALLEL = SAFE +); + + +CREATE OR REPLACE AGGREGATE helio_api_internal.BSONCOVARIANCESAMP(__CORE_SCHEMA__.bson, __CORE_SCHEMA__.bson) +( + SFUNC = helio_api_internal.bson_covariance_pop_samp_transition, + FINALFUNC = helio_api_internal.bson_covariance_samp_final, + MSFUNC = helio_api_internal.bson_covariance_pop_samp_transition, + MFINALFUNC = helio_api_internal.bson_covariance_samp_final, + MINVFUNC = helio_api_internal.bson_covariance_pop_samp_invtransition, + stype = bytea, + mstype = bytea, + COMBINEFUNC = helio_api_internal.bson_covariance_pop_samp_combine, + PARALLEL = SAFE +); + + +CREATE OR REPLACE AGGREGATE helio_api_internal.BSONDERIVATIVE(__CORE_SCHEMA__.bson, __CORE_SCHEMA__.bson, bigint) +( + SFUNC = helio_api_internal.bson_derivative_transition, + FINALFUNC = helio_api_internal.bson_integral_derivative_final, + stype = bytea, + PARALLEL = SAFE +); + + +CREATE OR REPLACE AGGREGATE helio_api_internal.BSONINTEGRAL(__CORE_SCHEMA__.bson, __CORE_SCHEMA__.bson, bigint) +( + SFUNC = helio_api_internal.bson_integral_transition, + FINALFUNC = helio_api_internal.bson_integral_derivative_final, + stype = bytea, + PARALLEL = SAFE +); \ No newline at end of file diff --git a/pg_helio_api/sql/udfs/aggregation/window_aggregates--latest.sql b/pg_helio_api/sql/udfs/aggregation/window_aggregates--latest.sql index 96ed741d..29b1b234 100644 --- a/pg_helio_api/sql/udfs/aggregation/window_aggregates--latest.sql +++ b/pg_helio_api/sql/udfs/aggregation/window_aggregates--latest.sql @@ -23,4 +23,22 @@ CREATE OR REPLACE AGGREGATE helio_api_internal.BSONCOVARIANCESAMP(__CORE_SCHEMA_ mstype = bytea, COMBINEFUNC = helio_api_internal.bson_covariance_pop_samp_combine, PARALLEL = SAFE +); + + +CREATE OR REPLACE AGGREGATE helio_api_internal.BSONDERIVATIVE(__CORE_SCHEMA__.bson, __CORE_SCHEMA__.bson, bigint) +( + SFUNC = helio_api_internal.bson_derivative_transition, + FINALFUNC = helio_api_internal.bson_integral_derivative_final, + stype = bytea, + PARALLEL = SAFE +); + + +CREATE OR REPLACE AGGREGATE helio_api_internal.BSONINTEGRAL(__CORE_SCHEMA__.bson, __CORE_SCHEMA__.bson, bigint) +( + SFUNC = helio_api_internal.bson_integral_transition, + FINALFUNC = helio_api_internal.bson_integral_derivative_final, + stype = bytea, + PARALLEL = SAFE ); \ No newline at end of file diff --git a/pg_helio_api/src/aggregation/bson_aggregation_statistics.c b/pg_helio_api/src/aggregation/bson_aggregation_statistics.c index 787f6e49..1c946c7f 100644 --- a/pg_helio_api/src/aggregation/bson_aggregation_statistics.c +++ b/pg_helio_api/src/aggregation/bson_aggregation_statistics.c @@ -55,6 +55,18 @@ enum InputValidFlags InputValidFlags_Input = 4 }; +typedef struct BsonIntegralAndDerivativeAggState +{ + /* The result value of current window */ + bson_value_t result; + + /* anchorX/anchorY is an anchor point for calculating integral or derivative. + * For $integral, anchorX is updated to the previous document of the window, + * For $derivative, anchorX is always updated to the first document of the window. + */ + bson_value_t anchorX; + bson_value_t anchorY; +} BsonIntegralAndDerivativeAggState; /* --------------------------------------------------------- */ /* Forward declaration */ @@ -103,7 +115,24 @@ static void CalculateSFuncForCovarianceOrVarianceWithYCAlgr(const bson_value_t * static bool CalculateExpMovingAvg(bson_value_t *currentValue, bson_value_t *perValue, bson_value_t *weightValue, bool isAlpha, bson_value_t *resultValue); +static bytea * AllocateBsonIntegralAndDerivativeAggState(void); +static void HandleIntegralDerivative(bson_value_t *xBsonValue, bson_value_t *yBsonValue, + long timeUnitInMs, + BsonIntegralAndDerivativeAggState *currentState, + const bool isIntegralOperator); +static void RunTimeCheckForIntegralAndDerivative(bson_value_t *xBsonValue, + bson_value_t *yBsonValue, + long timeUnitInMs, + const bool isIntegralOperator); +static bool IntegralOfTwoPointsByTrapezoidalRule(bson_value_t *xValue, + bson_value_t *yValue, + BsonIntegralAndDerivativeAggState * + currentState, + bson_value_t *timeUnitInMs); +static bool DerivativeOfTwoPoints(bson_value_t *xValue, bson_value_t *yValue, + BsonIntegralAndDerivativeAggState *currentState, + bson_value_t *timeUnitInMs); /* --------------------------------------------------------- */ /* Top level exports */ @@ -119,7 +148,9 @@ PG_FUNCTION_INFO_V1(bson_std_dev_pop_samp_combine); PG_FUNCTION_INFO_V1(bson_std_dev_pop_final); PG_FUNCTION_INFO_V1(bson_std_dev_samp_final); PG_FUNCTION_INFO_V1(bson_exp_moving_avg); - +PG_FUNCTION_INFO_V1(bson_derivative_transition); +PG_FUNCTION_INFO_V1(bson_integral_transition); +PG_FUNCTION_INFO_V1(bson_integral_derivative_final); /* * Transition function for the BSONCOVARIANCEPOP and BSONCOVARIANCESAMP aggregate. @@ -873,11 +904,196 @@ bson_exp_moving_avg(PG_FUNCTION_ARGS) } +/* transition function for the BSON_INTEGRAL aggregate + * use the trapzoidal rule to calculate the integral + */ +Datum +bson_integral_transition(PG_FUNCTION_ARGS) +{ + bytea *bytes; + bool isIntegral = true; + BsonIntegralAndDerivativeAggState *currentState; + + pgbson *xValue = PG_GETARG_MAYBE_NULL_PGBSON(1); + pgbson *yValue = PG_GETARG_MAYBE_NULL_PGBSON(2); + long timeUnitInt64 = PG_GETARG_INT64(3); + pgbsonelement xValueElement, yValueElement; + PgbsonToSinglePgbsonElement(xValue, &xValueElement); + PgbsonToSinglePgbsonElement(yValue, &yValueElement); + if (IsPgbsonEmptyDocument(xValue) || IsPgbsonEmptyDocument(yValue)) + { + PG_RETURN_NULL(); + } + RunTimeCheckForIntegralAndDerivative(&xValueElement.bsonValue, + &yValueElement.bsonValue, timeUnitInt64, + isIntegral); + if (PG_ARGISNULL(0)) + { + MemoryContext aggregateContext; + if (AggCheckCallContext(fcinfo, &aggregateContext) != AGG_CONTEXT_WINDOW) + { + ereport(ERROR, errmsg( + "window aggregate function called in non-window-aggregate context")); + } + + /* Create the aggregate state in the aggregate context. */ + MemoryContext oldContext = MemoryContextSwitchTo(aggregateContext); + + bytes = AllocateBsonIntegralAndDerivativeAggState(); + currentState = (BsonIntegralAndDerivativeAggState *) VARDATA(bytes); + currentState->result.value_type = BSON_TYPE_DOUBLE; + + /* update the anchor point with current document in window */ + currentState->anchorX = xValueElement.bsonValue; + currentState->anchorY = yValueElement.bsonValue; + + /* if xValue is a date, convert it to double */ + if (xValueElement.bsonValue.value_type == BSON_TYPE_DATE_TIME) + { + currentState->anchorX.value_type = BSON_TYPE_DOUBLE; + currentState->anchorX.value.v_double = BsonValueAsDouble( + &xValueElement.bsonValue); + } + MemoryContextSwitchTo(oldContext); + PG_RETURN_POINTER(bytes); + } + else + { + bytes = PG_GETARG_BYTEA_P(0); + currentState = (BsonIntegralAndDerivativeAggState *) VARDATA_ANY(bytes); + } + HandleIntegralDerivative(&xValueElement.bsonValue, &yValueElement.bsonValue, + timeUnitInt64, + currentState, isIntegral); + + /* update the anchor point with current document in window */ + currentState->anchorX = xValueElement.bsonValue; + currentState->anchorY = yValueElement.bsonValue; + + /* if xValue is a date, convert it to double */ + if (xValueElement.bsonValue.value_type == BSON_TYPE_DATE_TIME) + { + currentState->anchorX.value_type = BSON_TYPE_DOUBLE; + currentState->anchorX.value.v_double = BsonValueAsDouble( + &xValueElement.bsonValue); + } + PG_RETURN_POINTER(bytes); +} + + +/* transition function for the BSON_DERIVATIVE aggregate + * use dy/dx to calculate the derivative + */ +Datum +bson_derivative_transition(PG_FUNCTION_ARGS) +{ + pgbson *xValue = PG_GETARG_MAYBE_NULL_PGBSON(1); + pgbson *yValue = PG_GETARG_MAYBE_NULL_PGBSON(2); + long timeUnitInt64 = PG_GETARG_INT64(3); + pgbsonelement xValueElement, yValueElement; + PgbsonToSinglePgbsonElement(xValue, &xValueElement); + PgbsonToSinglePgbsonElement(yValue, &yValueElement); + + bytea *bytes; + bool isIntegral = false; + BsonIntegralAndDerivativeAggState *currentState; + if (IsPgbsonEmptyDocument(xValue) || IsPgbsonEmptyDocument(yValue)) + { + PG_RETURN_NULL(); + } + RunTimeCheckForIntegralAndDerivative(&xValueElement.bsonValue, + &yValueElement.bsonValue, timeUnitInt64, + isIntegral); + if (PG_ARGISNULL(0)) + { + MemoryContext aggregateContext; + if (AggCheckCallContext(fcinfo, &aggregateContext) != AGG_CONTEXT_WINDOW) + { + ereport(ERROR, errmsg( + "window aggregate function called in non-window-aggregate context")); + } + + /* Create the aggregate state in the aggregate context. */ + MemoryContext oldContext = MemoryContextSwitchTo(aggregateContext); + + bytes = AllocateBsonIntegralAndDerivativeAggState(); + currentState = (BsonIntegralAndDerivativeAggState *) VARDATA(bytes); + currentState->result.value_type = BSON_TYPE_NULL; + + /* anchor points are always the first document in the window for $derivative*/ + /* if xValue is a date, convert it to double */ + if (xValueElement.bsonValue.value_type == BSON_TYPE_DATE_TIME) + { + currentState->anchorX.value_type = BSON_TYPE_DOUBLE; + currentState->anchorX.value.v_double = BsonValueAsDouble( + &xValueElement.bsonValue); + } + else + { + currentState->anchorX = xValueElement.bsonValue; + } + currentState->anchorY = yValueElement.bsonValue; + + /* We have the first document in state and the second incoming document + * it's ready to calculate the derivative */ + MemoryContextSwitchTo(oldContext); + PG_RETURN_POINTER(bytes); + } + else + { + bytes = PG_GETARG_BYTEA_P(0); + currentState = (BsonIntegralAndDerivativeAggState *) VARDATA_ANY(bytes); + } + if (IsPgbsonEmptyDocument(xValue) || IsPgbsonEmptyDocument(yValue)) + { + PG_RETURN_POINTER(bytes); + } + HandleIntegralDerivative(&xValueElement.bsonValue, &yValueElement.bsonValue, + timeUnitInt64, + currentState, isIntegral); + PG_RETURN_POINTER(bytes); +} + + +/* final function for the BSON_INTEGRAL and BSON_DERIVATIVE aggregate + * This takes the final value created and outputs a bson "integral" or "derivative" + * with the appropriate type. + */ +Datum +bson_integral_derivative_final(PG_FUNCTION_ARGS) +{ + bytea *currentState = PG_ARGISNULL(0) ? NULL : PG_GETARG_BYTEA_P(0); + pgbsonelement finalValue; + finalValue.path = ""; + finalValue.pathLength = 0; + + if (currentState != NULL) + { + BsonIntegralAndDerivativeAggState *state = + (BsonIntegralAndDerivativeAggState *) VARDATA_ANY( + currentState); + if (state->result.value_type != BSON_TYPE_NULL) + { + finalValue.bsonValue = state->result; + } + else if (state->result.value_type == BSON_TYPE_NULL) + { + finalValue.bsonValue.value_type = BSON_TYPE_NULL; + } + } + else + { + finalValue.bsonValue.value_type = BSON_TYPE_NULL; + } + PG_RETURN_POINTER(PgbsonElementToPgbson(&finalValue)); +} + + /* --------------------------------------------------------- */ /* Private helper methods */ /* --------------------------------------------------------- */ -bytea * +static bytea * AllocateBsonCovarianceOrVarianceAggState() { int bson_size = sizeof(BsonCovarianceAndVarianceAggState) + VARHDRSZ; @@ -888,6 +1104,17 @@ AllocateBsonCovarianceOrVarianceAggState() } +static bytea * +AllocateBsonIntegralAndDerivativeAggState() +{ + int bson_size = sizeof(BsonIntegralAndDerivativeAggState) + VARHDRSZ; + bytea *combinedStateBytes = (bytea *) palloc0(bson_size); + SET_VARSIZE(combinedStateBytes, bson_size); + + return combinedStateBytes; +} + + /* * Function to calculate variance/covariance state for inverse function. * If calculating variance, we use X and Y as the same value. @@ -1647,3 +1874,194 @@ CalculateExpMovingAvg(bson_value_t *bsonCurrentValue, bson_value_t *bsonPerValue } return isDecimalOpSuccess; } + + +/* This function is used to handle the $integral and $derivative operators + * 1. Calculate the integral or derivative value + * 2. Update the result value in the currentState + */ +static void +HandleIntegralDerivative(bson_value_t *xBsonValue, bson_value_t *yBsonValue, + long timeUnitInt64, + BsonIntegralAndDerivativeAggState *currentState, + const bool isIntegralOperator) +{ + /* Intermidiate variables for calculation */ + bson_value_t timeUnitInMs, yValue, xValue; + timeUnitInMs.value_type = BSON_TYPE_DOUBLE; + timeUnitInMs.value.v_double = timeUnitInt64; + yValue = *yBsonValue; + xValue = *xBsonValue; + + /* Convert date time to double to avoid calucation error*/ + if (xBsonValue->value_type == BSON_TYPE_DATE_TIME) + { + xValue.value_type = BSON_TYPE_DOUBLE; + xValue.value.v_double = BsonValueAsDouble(xBsonValue); + } + + /* Calculation status */ + bool success = isIntegralOperator ? + IntegralOfTwoPointsByTrapezoidalRule(&xValue, &yValue, + currentState, + &timeUnitInMs) : + DerivativeOfTwoPoints(&xValue, &yValue, currentState, + &timeUnitInMs); + + /* If calculation failed, throw an error */ + if (!success) + { + char *opName = isIntegralOperator ? "$integral" : "$derivative"; + ereport(ERROR, errcode(MongoInternalError), + errmsg( + "Handling %s: yValue = %f, xValue = %f, currentState->anchorX = %f, currentState->anchorY = %f, currentState->result = %f", + opName, BsonValueAsDouble(&yValue), BsonValueAsDouble(&xValue), + BsonValueAsDouble(¤tState->anchorX), BsonValueAsDouble( + ¤tState->anchorY), BsonValueAsDouble( + ¤tState->result)), + errdetail_log( + "Handling %s: yValue = %f, xValue = %f, currentState->anchorX = %f, currentState->anchorY = %f, currentState->result = %f", + opName, BsonValueAsDouble(&yValue), BsonValueAsDouble(&xValue), + BsonValueAsDouble(¤tState->anchorX), BsonValueAsDouble( + ¤tState->anchorY), BsonValueAsDouble( + ¤tState->result))); + } +} + + +/* This function is used to check the runtime syntax, input, and unit for $integral and $derivative operators */ +static void +RunTimeCheckForIntegralAndDerivative(bson_value_t *xBsonValue, bson_value_t *yBsonValue, + long timeUnitInt64, bool isIntegralOperator) +{ + const char *opName = isIntegralOperator ? "$integral" : "$derivative"; + + /* if xBsonValue is not a date and unit is specified, throw an error */ + if (IsBsonValueDateTimeFormat(xBsonValue->value_type) || + xBsonValue->value_type == BSON_TYPE_NULL) + { + if (!timeUnitInt64) + { + int errorCode = isIntegralOperator ? ERRCODE_HELIO_LOCATION5423902 : + ERRCODE_HELIO_LOCATION5624901; + const char *errorMsg = isIntegralOperator + ? + "%s (with no 'unit') expects the sortBy field to be numeric" + : "%s where the sortBy is a Date requires an 'unit'"; + ereport(ERROR, errcode(errorCode), + errmsg(errorMsg, opName), + errdetail_log(errorMsg, opName)); + } + } + /* if xBsonValue is a number and unit is specified, throw an error */ + else if (BsonTypeIsNumber(xBsonValue->value_type)) + { + if (timeUnitInt64) + { + int errorCode = isIntegralOperator ? ERRCODE_HELIO_LOCATION5423901 : + ERRCODE_HELIO_LOCATION5624900; + const char *errorMsg = "%s with 'unit' expects the sortBy field to be a Date"; + ereport(ERROR, errcode(errorCode), + errmsg(errorMsg, opName), + errdetail_log(errorMsg, opName)); + } + } + + /* if unit is specifed but x is not a date, throw an error */ + if (timeUnitInt64 && xBsonValue->value_type != BSON_TYPE_DATE_TIME) + { + ereport(ERROR, (errcode(MongoLocation5429513), errmsg( + "Expected the sortBy field to be a Date, but it was %s", + BsonTypeName( + xBsonValue->value_type)))); + } + /* if unit is not specified and x is a date, throw an error */ + else if (!timeUnitInt64 && xBsonValue->value_type == BSON_TYPE_DATE_TIME) + { + ereport(ERROR, (errcode(MongoLocation5429513), errmsg( + "For windows that involve date or time ranges, a unit must be provided."))); + } + + /* y must be a number */ + if (!BsonTypeIsNumber(yBsonValue->value_type)) + { + ereport(ERROR, (errcode(ERRCODE_HELIO_LOCATION5423900), + errmsg( + "The input value of %s window function must be a vector" + " of 2 value, the first value must be numeric or date type " + "and the second must be numeric.", opName), + errdetail_log("Input value is: %s", + BsonTypeName(yBsonValue->value_type)))); + } +} + + +/* This function is used to calculate the integral + * of current state and current document in window by Trapezoidal Rule. + * The result will be promoted to decimal if one of the input is decimal. + */ +bool +IntegralOfTwoPointsByTrapezoidalRule(bson_value_t *xValue, + bson_value_t *yValue, + BsonIntegralAndDerivativeAggState *currentState, + bson_value_t *timeUnitInMs) +{ + bool success = true; + bson_value_t stateXValue = currentState->anchorX; + const bson_value_t stateYValue = currentState->anchorY; + + bool overflowedFromInt64, convertInt64OverflowToDouble = false; + + /* get time delta */ + success &= SubtractNumberFromBsonValue(xValue, &stateXValue, &overflowedFromInt64); + + /* add anchorY axis */ + success &= AddNumberToBsonValue(yValue, &stateYValue, &overflowedFromInt64); + + /* get area */ + success &= MultiplyWithFactorAndUpdate(yValue, xValue, convertInt64OverflowToDouble); + bson_value_t bsonValueTwo; + bsonValueTwo.value_type = BSON_TYPE_DOUBLE; + bsonValueTwo.value.v_double = 2.0; + + success &= DivideBsonValueNumbers(yValue, &bsonValueTwo); + if (timeUnitInMs->value.v_double != 0.0) + { + success &= DivideBsonValueNumbers(yValue, timeUnitInMs); + } + + success &= AddNumberToBsonValue(¤tState->result, yValue, &overflowedFromInt64); + return success; +} + + +/* This function is used to calculate the derivative + * of current state and current document in window by derivative rule. + * The result will be promoted to decimal if one of the input is decimal. + */ +bool +DerivativeOfTwoPoints(bson_value_t *xValue, bson_value_t *yValue, + BsonIntegralAndDerivativeAggState *currentState, + bson_value_t *timeUnitInMs) +{ + bool success = true; + bson_value_t stateXValue = currentState->anchorX; + const bson_value_t stateYValue = currentState->anchorY; + + bool overflowedFromInt64 = false; + + /* get time delta */ + success &= SubtractNumberFromBsonValue(xValue, &stateXValue, &overflowedFromInt64); + if (timeUnitInMs->value.v_double != 0.0) + { + success &= DivideBsonValueNumbers(xValue, timeUnitInMs); + } + + /* get value delta */ + success &= SubtractNumberFromBsonValue(yValue, &stateYValue, &overflowedFromInt64); + + /* get derivative */ + success &= DivideBsonValueNumbers(yValue, xValue); + currentState->result = *yValue; + return success; +} 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 1f755da6..8e2eabcc 100644 --- a/pg_helio_api/src/aggregation/bson_aggregation_window_operators.c +++ b/pg_helio_api/src/aggregation/bson_aggregation_window_operators.c @@ -18,6 +18,7 @@ #include #include #include +#include #include #include "aggregation/bson_aggregation_window_operators.h" @@ -116,6 +117,19 @@ typedef struct static void ParseAndSetFrameOption(const bson_value_t *value, WindowClause *windowClause, DateUnit timeUnit, int *frameOptions); +static WindowFunc * HandleDollarIntegralWindowOperator(const bson_value_t *opValue, + WindowOperatorContext *context); +static WindowFunc * HandleDollarDerivativeWindowOperator(const bson_value_t *opValue, + WindowOperatorContext *context); +static void ParseIntegralDerivativeExpression(const bson_value_t *opValue, + WindowOperatorContext *context, + Expr **xExpr, + Expr **yExpr, + long *unitInMs, + bool isIntegralOperator); +static WindowFunc * GetIntegralDerivativeWindowFunc(const bson_value_t *opValue, + WindowOperatorContext *context, + bool isIntegral); static Datum EnsureValidUnitOffsetAndGetInterval(const bson_value_t *value, DateUnit dateUnit); @@ -244,7 +258,7 @@ static const WindowOperatorDefinition WindowOperatorDefinitions[] = }, { .operatorName = "$derivative", - .windowOperatorFunc = NULL + .windowOperatorFunc = HandleDollarDerivativeWindowOperator }, { .operatorName = "$documentNumber", @@ -264,7 +278,7 @@ static const WindowOperatorDefinition WindowOperatorDefinitions[] = }, { .operatorName = "$integral", - .windowOperatorFunc = NULL + .windowOperatorFunc = HandleDollarIntegralWindowOperator }, { .operatorName = "$last", @@ -602,6 +616,7 @@ HandleSetWindowFields(const bson_value_t *existingValue, Query *query, BsonIterToPgbsonElement(&sortByIter, &element); pgbson *sortDoc = PgbsonElementToPgbson(&element); + Const *sortBson = MakeBsonConst(sortDoc); bool isAscending = ValidateOrderbyExpressionAndGetIsAscending(sortDoc); @@ -1377,6 +1392,209 @@ GetSimpleBsonExpressionGetWindowFunc(const bson_value_t *opValue, } +/* + * Handle for $integral window aggregation operator. + * Returns the WindowFunc for bson aggregate function `bsonintegral` + */ +static WindowFunc * +HandleDollarIntegralWindowOperator(const bson_value_t *opValue, + WindowOperatorContext *context) +{ + if (!(IsClusterVersionAtleastThis(1, 22, 0))) + { + ereport(ERROR, (errcode(MongoCommandNotSupported), + errmsg( + "$integral is only supported on vCore 1.22.0 and above"))); + } + return GetIntegralDerivativeWindowFunc(opValue, context, true); +} + + +/* + * Handle for $derivative window aggregation operator. + * Returns the WindowFunc for bson aggregate function `bsonderivative` + */ +static WindowFunc * +HandleDollarDerivativeWindowOperator(const bson_value_t *opValue, + WindowOperatorContext *context) +{ + if (!(IsClusterVersionAtleastThis(1, 22, 0))) + { + ereport(ERROR, (errcode(MongoCommandNotSupported), + errmsg( + "$derivative is only supported on vCore 1.22.0 and above"))); + } + return GetIntegralDerivativeWindowFunc(opValue, context, false); +} + + +/* + * Get the window function for the integral or derivative window aggregation operator. + */ +WindowFunc * +GetIntegralDerivativeWindowFunc(const bson_value_t *opValue, + WindowOperatorContext *context, + bool isIntegral) +{ + if (!(context->isWindowPresent || isIntegral)) + { + ereport(ERROR, (errcode(MongoFailedToParse), + errmsg("$derivative requires explicit window bounds"))); + } + WindowFunc *windowFunc = makeNode(WindowFunc); + windowFunc->winfnoid = isIntegral ? BsonIntegralAggregateFunctionOid() : + BsonDerivativeAggregateFunctionOid(); + windowFunc->wintype = BsonTypeId(); + windowFunc->winref = context->winRef; + windowFunc->winstar = false; + windowFunc->winagg = true; + Expr *xExpr = NULL; + Expr *yExpr = NULL; + long unitInMs = 0; + ParseIntegralDerivativeExpression(opValue, context, &xExpr, &yExpr, &unitInMs, + isIntegral); + + Const *trueConst = makeConst(BOOLOID, -1, InvalidOid, 1, BoolGetDatum(true), false, + true); + Const *unitConst = (Const *) makeConst(INT8OID, -1, InvalidOid, sizeof(int64_t), + unitInMs, false, true); + List *xArgs, *yArgs; + Oid functionOid; + if (context->variableContext != NULL) + { + functionOid = BsonExpressionGetWithLetFunctionOid(); + xArgs = list_make4(context->docExpr, xExpr, trueConst, + context->variableContext); + yArgs = list_make4(context->docExpr, yExpr, trueConst, + context->variableContext); + } + else + { + functionOid = BsonExpressionGetFunctionOid(); + xArgs = list_make3(context->docExpr, xExpr, trueConst); + yArgs = list_make3(context->docExpr, yExpr, trueConst); + } + + FuncExpr *xAccumFunc = makeFuncExpr( + functionOid, BsonTypeId(), xArgs, InvalidOid, + InvalidOid, COERCE_EXPLICIT_CALL); + FuncExpr *yAccumFunc = makeFuncExpr( + functionOid, BsonTypeId(), yArgs, InvalidOid, + InvalidOid, COERCE_EXPLICIT_CALL); + + windowFunc->args = list_make3(xAccumFunc, yAccumFunc, unitConst); + return windowFunc; +} + + +/* + * Parse the integral or derivative expression and return the expression. + */ +inline void +ParseIntegralDerivativeExpression(const bson_value_t *opValue, + WindowOperatorContext *context, + Expr **xExpr, /* Pointer to pointer */ + Expr **yExpr, /* Pointer to pointer */ + long *unitInMs, + bool isIntegralOperator) +{ + const char *operatorName = isIntegralOperator ? "$integral" : "$derivative"; + SetWindowFieldSortOption *sortField; + if (!list_length(context->sortOptions)) + { + ereport(ERROR, (errcode(MongoFailedToParse), + errmsg("%s requires a sortBy", operatorName))); + } + else if (list_length(context->sortOptions) > 1) + { + ereport(ERROR, (errcode(MongoFailedToParse), + errmsg("%s requires a non-compound sortBy", operatorName))); + } + else + { + sortField = (SetWindowFieldSortOption *) list_nth( + context->sortOptions, 0); + } + pgbson *sortSpecBson = DatumGetPgBson(sortField->sortSpecConst->constvalue); + pgbson *opValueBson = BsonValueToDocumentPgbson(opValue); + bson_iter_t iterOpValue, iterSortSpec; + + PgbsonInitIterator(opValueBson, &iterOpValue); + PgbsonInitIterator(sortSpecBson, &iterSortSpec); + while (bson_iter_next(&iterOpValue)) + { + const bson_value_t *valueUserInput = bson_iter_value(&iterOpValue); + bson_iter_t valueIter; + BsonValueInitIterator(valueUserInput, &valueIter); + while (bson_iter_next(&valueIter)) + { + const char *key = bson_iter_key(&valueIter); + const bson_value_t *value = bson_iter_value(&valueIter); + if (strcmp(key, "input") == 0) + { + *yExpr = (Expr *) MakeBsonConst(BsonValueToDocumentPgbson(value)); /* Dereference to modify the pointer */ + } + else if (strcmp(key, "unit") == 0) + { + DateUnit unit = GetDateUnitFromString(value->value.v_utf8.str); + if (unit == DateUnit_Invalid) + { + ereport(ERROR, (errcode(MongoFailedToParse), + errmsg("unknown time unit value: %s", + value->value.v_utf8.str), + errhint("unknown time unit value: %s", + value->value.v_utf8.str))); + } + else if (unit < DateUnit_Week) + { + ereport(ERROR, (errcode(ERRCODE_HELIO_LOCATION5490710), errmsg( + "unit must be 'week' or smaller"), + errdetail_log("unit must be 'week' or smaller"))); + } + *unitInMs = + ((Interval *) DatumGetIntervalP( + GetIntervalFromDateUnitAndAmount( + unit, + 1))) + ->time / 1000; + } + else + { + ereport(ERROR, (errcode(MongoFailedToParse), + errmsg("%s got unexpected argument: %s", operatorName, + key))); + } + } + } + if (!(*yExpr)) + { + ereport(ERROR, ( + errcode(MongoFailedToParse), + errmsg( + "%s requires an 'input' expression", operatorName))); + } + if (bson_iter_next(&iterSortSpec)) + { + const char *key = bson_iter_key(&iterSortSpec); + char *result; + result = (char *) palloc(strlen(key) + 1); + result[0] = '$'; + strcpy(result + 1, key); + bson_value_t resultBsonValue; + resultBsonValue.value_type = BSON_TYPE_UTF8; + resultBsonValue.value.v_utf8.len = strlen(result); + resultBsonValue.value.v_utf8.str = result; + *xExpr = (Expr *) MakeBsonConst(BsonValueToDocumentPgbson(&resultBsonValue)); /* Dereference to modify the pointer */ + pfree(result); + } + else + { + ereport(ERROR, (errcode(MongoFailedToParse), + errmsg("%s requires a non-compound sortBy", operatorName))); + } +} + + /* * Handle for $sum window aggregation operator. * Returns the WindowFunc for bson aggregate function `bsonsum` diff --git a/pg_helio_api/src/metadata/metadata_cache.c b/pg_helio_api/src/metadata/metadata_cache.c index d981af67..d5442258 100644 --- a/pg_helio_api/src/metadata/metadata_cache.c +++ b/pg_helio_api/src/metadata/metadata_cache.c @@ -671,6 +671,12 @@ typedef struct HelioApiOidCacheData /* OID of the bson_locf_fill window function */ Oid ApiCatalogBsonLocfFillFunctionOid; + /* OID of the BSONINTEGRAL aggregate function */ + Oid ApiCatalogBsonIntegralAggregateFunctionOid; + + /* OID of the BSONDERIVATIVE aggregate function */ + Oid ApiCatalogBsonDerivativeAggregateFunctionOid; + /* OID of the BSONAVERAGE aggregate function */ Oid ApiCatalogBsonAverageAggregateFunctionOid; @@ -3409,6 +3415,24 @@ BsonLocfFillFunctionOid(void) } +Oid +BsonIntegralAggregateFunctionOid(void) +{ + return GetAggregateFunctionByName( + &Cache.ApiCatalogBsonIntegralAggregateFunctionOid, + "helio_api_internal", "bsonintegral"); +} + + +Oid +BsonDerivativeAggregateFunctionOid(void) +{ + return GetAggregateFunctionByName( + &Cache.ApiCatalogBsonDerivativeAggregateFunctionOid, + "helio_api_internal", "bsonderivative"); +} + + Oid BsonAvgAggregateFunctionOid(void) { diff --git a/pg_helio_core/include/utils/helio_codes.txt b/pg_helio_core/include/utils/helio_codes.txt index fa177d20..34eb51b9 100644 --- a/pg_helio_core/include/utils/helio_codes.txt +++ b/pg_helio_core/include/utils/helio_codes.txt @@ -479,3 +479,9 @@ Location6007200,M00D8,6007200,477 Location6053600,M00D9,6053600,478 Location6586400,M00DA,6586400,479 Location8993000,M00DB,8993000,480 +Location5423900,M00DC,5423900,481 +Location5423901,M00DD,5423901,482 +Location5423902,M00DE,5423902,483 +Location5490710,M00DF,5490710,484 +Location5624900,M00DG,5624900,485 +Location5624901,M00DH,5624901,486 diff --git a/pg_helio_core/include/utils/helio_errors.h b/pg_helio_core/include/utils/helio_errors.h index bc5edaaf..184a8ce0 100644 --- a/pg_helio_core/include/utils/helio_errors.h +++ b/pg_helio_core/include/utils/helio_errors.h @@ -1503,4 +1503,22 @@ #define ERRCODE_HELIO_LOCATION8993000 MAKE_SQLSTATE('M', '0', '0', 'D', 'B') #define MONGO_CODE_LOCATION8993000 8993000 +#define ERRCODE_HELIO_LOCATION5423900 MAKE_SQLSTATE('M', '0', '0', 'D', 'C') +#define MONGO_CODE_LOCATION5423900 5423900 + +#define ERRCODE_HELIO_LOCATION5423901 MAKE_SQLSTATE('M', '0', '0', 'D', 'D') +#define MONGO_CODE_LOCATION5423901 5423901 + +#define ERRCODE_HELIO_LOCATION5423902 MAKE_SQLSTATE('M', '0', '0', 'D', 'E') +#define MONGO_CODE_LOCATION5423902 5423902 + +#define ERRCODE_HELIO_LOCATION5490710 MAKE_SQLSTATE('M', '0', '0', 'D', 'F') +#define MONGO_CODE_LOCATION5490710 5490710 + +#define ERRCODE_HELIO_LOCATION5624900 MAKE_SQLSTATE('M', '0', '0', 'D', 'G') +#define MONGO_CODE_LOCATION5624900 5624900 + +#define ERRCODE_HELIO_LOCATION5624901 MAKE_SQLSTATE('M', '0', '0', 'D', 'H') +#define MONGO_CODE_LOCATION5624901 5624901 + #endif