From 722ef60784c7663ebcd9aa999fc482bd89792baa Mon Sep 17 00:00:00 2001 From: Xing Fan Date: Fri, 10 Jan 2025 14:01:14 +0000 Subject: [PATCH] Merged PR 1479858: $percentile & $median for $group accumulator ### Does this PR have any customer impact? ### Type (Feature, Refactoring, Bugfix, DevOps, Testing, Perf, etc) ### Does it involve schema level changes? (Table, Column, Index, UDF, etc level changes) ### Are you introducing any new config? If yes, do you have tests with and without them being set? ### Release Note (Refer [Template](../docs/release_notes/pgmongo_template.md)) ### Description draft ---- #### AI description (iteration 1) #### PR Classification New feature #### PR Summary This pull request introduces new aggregation functions and support for t-digest in the project. - Added `bson_tdigest.c` to implement t-digest helper functions. - Created new SQL aggregate functions in `group_aggregates--1.23-0.sql` and `group_aggregates_support--1.23-0.sql`. - Updated `bson_aggregation_pipeline.c` to handle the new `$percentile` accumulator. - Modified `metadata_cache.c` and `metadata_cache.h` to include OID for the new `BsonPercentileAggregateFunction`. - Updated migration scripts `pg_helio_api--1.22-0--1.23-0.sql` and `pgmongo--1.22-0--1.23-0.sql` to include new SQL files. --- documentdb_errors.csv | 7 +- .../src/test/regress/basic_schedule_core | 2 +- ...ation_pipeline_tests_percentile_median.out | 215 +++ .../setwindowfields_and_group_compliance.out | 4 +- ...ation_pipeline_tests_percentile_median.sql | 84 ++ mongoerrors.csv | 5 + .../aggregation/bson_aggregation_pipeline.h | 3 + .../include/metadata/metadata_cache.h | 2 + pg_documentdb/include/utils/feature_counter.h | 4 +- pg_documentdb/sql/documentdb--0.24-0.sql | 4 +- .../aggregation/group_aggregates--0.24-0.sql | 404 ++++++ .../aggregation/group_aggregates--latest.sql | 22 + .../group_aggregates_support--0.24-0.sql | 369 +++++ .../group_aggregates_support--latest.sql | 44 +- .../aggregation/bson_aggregation_pipeline.c | 220 ++- pg_documentdb/src/aggregation/bson_tdigest.c | 1240 +++++++++++++++++ pg_documentdb/src/configs/system_configs.c | 12 + .../src/infrastructure/feature_counter.c | 2 + pg_documentdb/src/metadata/metadata_cache.c | 24 + .../regress/expected/public_api_schema.out | 15 +- .../include/utils/documentdb_codes.txt | 7 +- .../include/utils/documentdb_errors.h | 10 + .../sql/pg_helio_api--1.23-0--1.24-0.sql | 4 +- 23 files changed, 2689 insertions(+), 14 deletions(-) create mode 100644 internal/pg_helio_distributed/src/test/regress/expected/bson_aggregation_pipeline_tests_percentile_median.out create mode 100644 internal/pg_helio_distributed/src/test/regress/sql/bson_aggregation_pipeline_tests_percentile_median.sql create mode 100644 pg_documentdb/sql/udfs/aggregation/group_aggregates--0.24-0.sql create mode 100644 pg_documentdb/sql/udfs/aggregation/group_aggregates_support--0.24-0.sql create mode 100644 pg_documentdb/src/aggregation/bson_tdigest.c diff --git a/documentdb_errors.csv b/documentdb_errors.csv index 0c773944..91f06707 100644 --- a/documentdb_errors.csv +++ b/documentdb_errors.csv @@ -497,4 +497,9 @@ OrdinalPosition,ErrorName 496,UserCountLimitExceeded 497,Location55 498,Location40236 -499,Location17053 \ No newline at end of file +499,Location17053 +500,Location7429703 +501,Location7436100 +502,Location7750301 +503,Location7750302 +504,Location7750303 diff --git a/internal/pg_helio_distributed/src/test/regress/basic_schedule_core b/internal/pg_helio_distributed/src/test/regress/basic_schedule_core index 348cdf0c..0062ffce 100644 --- a/internal/pg_helio_distributed/src/test/regress/basic_schedule_core +++ b/internal/pg_helio_distributed/src/test/regress/basic_schedule_core @@ -61,7 +61,7 @@ test: bson_aggregation_type_operators_tests bson_aggregation_timestamp_operators test: bson_aggregation_stage_set_tests bson_aggregation_stage_replaceroot_tests bson_aggregation_stage_project_tests test: bson_query_projection_operator_expressions_map_tests bson_query_projection_operator_expressions_tests bson_type_comparison_tests bson_aggregation_arithmetic_operators_tests test: bson_aggregation_pipeline_operator_expMovingAvg bson_aggregation_pipeline_operator_linearFill bson_aggregation_pipeline_tests_graphlookup -test: bson_aggregation_pipeline_tests_let bson_aggregation_pipeline_tests_merge_objects_group bson_aggregation_pipeline_tests bson_aggregation_stage_inversematch_tests bson_aggregation_stage_sample_tests +test: bson_aggregation_pipeline_tests_let bson_aggregation_pipeline_tests_merge_objects_group bson_aggregation_pipeline_tests bson_aggregation_stage_inversematch_tests bson_aggregation_stage_sample_tests bson_aggregation_pipeline_tests_percentile_median test: bson_aggregation_trigonometric_operators_tests bson_base_aggregates_tests_runtime bson_get_indexes_b bson_order_aggregates_tests test: bson_query_index_selection_sharded_tests bson_query_modifier_orderby_tests_index bson_sort_index_pushdown diff --git a/internal/pg_helio_distributed/src/test/regress/expected/bson_aggregation_pipeline_tests_percentile_median.out b/internal/pg_helio_distributed/src/test/regress/expected/bson_aggregation_pipeline_tests_percentile_median.out new file mode 100644 index 00000000..396fe36c --- /dev/null +++ b/internal/pg_helio_distributed/src/test/regress/expected/bson_aggregation_pipeline_tests_percentile_median.out @@ -0,0 +1,215 @@ +-- will move to bson_aggregation_pipeline_stage_setWindowFields.sql and remove this file after window operator is done, just like $stddevopo did +SET search_path TO helio_core,helio_api,helio_api_catalog,helio_api_internal; +SET citus.next_shard_id TO 1033000; +SET helio_api.next_collection_id TO 10330; +SET helio_api.next_collection_index_id TO 10330; +SELECT helio_api.insert_one('db','testPercentileAndMedian',' { "_id" : 1, "group": 1, "dataVal": 36, "dataVal2": 36, "dataVal3": {"$numberDecimal": "36"}, "dataVal4": 36, "dataVal5": NaN }', NULL); +NOTICE: creating collection + insert_one +--------------------------------------------------------------------- + { "n" : { "$numberInt" : "1" }, "ok" : { "$numberDouble" : "1.0" } } +(1 row) + +SELECT helio_api.insert_one('db','testPercentileAndMedian',' { "_id" : 2, "group": 1, "dataVal": 22, "dataVal2": 22, "dataVal3": {"$numberDecimal": "22"}, "dataVal4": 22, "dataVal5": Infinity }', NULL); + insert_one +--------------------------------------------------------------------- + { "n" : { "$numberInt" : "1" }, "ok" : { "$numberDouble" : "1.0" } } +(1 row) + +SELECT helio_api.insert_one('db','testPercentileAndMedian',' { "_id" : 3, "group": 1, "dataVal": 67, "dataVal2": "string", "dataVal3": {"$numberDecimal": "67"}, "dataVal4": {"$numberDecimal": "2E+310"}, "dataVal5": Infinity }', NULL); + insert_one +--------------------------------------------------------------------- + { "n" : { "$numberInt" : "1" }, "ok" : { "$numberDouble" : "1.0" } } +(1 row) + +SELECT helio_api.insert_one('db','testPercentileAndMedian',' { "_id" : 4, "group": 1, "dataVal": 3, "dataVal2": 3, "dataVal3": {"$numberDecimal": "3"}, "dataVal4": 3, "dataVal5": -Infinity }', NULL); + insert_one +--------------------------------------------------------------------- + { "n" : { "$numberInt" : "1" }, "ok" : { "$numberDouble" : "1.0" } } +(1 row) + +SELECT helio_api.insert_one('db','testPercentileAndMedian',' { "_id" : 5, "group": 1, "dataVal": 55, "dataVal2": 55, "dataVal3": {"$numberDecimal": "55"}, "dataVal4": 55, "dataVal5": NaN }', NULL); + insert_one +--------------------------------------------------------------------- + { "n" : { "$numberInt" : "1" }, "ok" : { "$numberDouble" : "1.0" } } +(1 row) + +-- positive test case for percentile +SELECT document FROM helio_api_catalog.bson_aggregation_pipeline('db', '{ "aggregate": "testPercentileAndMedian", "pipeline": [ { "$group": { "_id": "$group", "percentileVal": { "$percentile": { "input": "$dataVal", "p": [ 0.95 ], "method": "approximate" } } } } ] }'); + document +--------------------------------------------------------------------- + { "_id" : { "$numberInt" : "1" }, "percentileVal" : [ { "$numberDouble" : "67.0" } ] } +(1 row) + +SELECT document FROM helio_api_catalog.bson_aggregation_pipeline('db', '{ "aggregate": "testPercentileAndMedian", "pipeline": [ { "$group": { "_id": "$group", "percentileVal": { "$percentile": { "input": "$dataVal", "p": [ 0.95, 0.5 ], "method": "approximate" } } } } ] }'); + document +--------------------------------------------------------------------- + { "_id" : { "$numberInt" : "1" }, "percentileVal" : [ { "$numberDouble" : "67.0" }, { "$numberDouble" : "36.0" } ] } +(1 row) + +SELECT document FROM helio_api_catalog.bson_aggregation_pipeline('db', '{ "aggregate": "testPercentileAndMedian", "pipeline": [ { "$group": { "_id": "$group", "percentileVal": { "$percentile": { "input": null, "p": [ 0.95 ], "method": "approximate" } } } } ] }'); + document +--------------------------------------------------------------------- + { "_id" : { "$numberInt" : "1" }, "percentileVal" : [ null ] } +(1 row) + +-- contain non-numeric value +SELECT document FROM helio_api_catalog.bson_aggregation_pipeline('db', '{ "aggregate": "testPercentileAndMedian", "pipeline": [ { "$group": { "_id": "$group", "percentileVal": { "$percentile": { "input": "$dataVal2", "p": [ 0.95 ], "method": "approximate" } } } } ] }'); + document +--------------------------------------------------------------------- + { "_id" : { "$numberInt" : "1" }, "percentileVal" : [ { "$numberDouble" : "55.0" } ] } +(1 row) + +SELECT document FROM helio_api_catalog.bson_aggregation_pipeline('db', '{ "aggregate": "testPercentileAndMedian", "pipeline": [ { "$group": { "_id": "$group", "percentileVal": { "$percentile": { "input": "$dataVal2", "p": [ 0.95, 0.5 ], "method": "approximate" } } } } ] }'); + document +--------------------------------------------------------------------- + { "_id" : { "$numberInt" : "1" }, "percentileVal" : [ { "$numberDouble" : "55.0" }, { "$numberDouble" : "22.0" } ] } +(1 row) + +-- contain decimal value +SELECT document FROM helio_api_catalog.bson_aggregation_pipeline('db', '{ "aggregate": "testPercentileAndMedian", "pipeline": [ { "$group": { "_id": "$group", "percentileVal": { "$percentile": { "input": "$dataVal3", "p": [ 0.95 ], "method": "approximate" } } } } ] }'); + document +--------------------------------------------------------------------- + { "_id" : { "$numberInt" : "1" }, "percentileVal" : [ { "$numberDouble" : "67.0" } ] } +(1 row) + +SELECT document FROM helio_api_catalog.bson_aggregation_pipeline('db', '{ "aggregate": "testPercentileAndMedian", "pipeline": [ { "$group": { "_id": "$group", "percentileVal": { "$percentile": { "input": "$dataVal3", "p": [ 0.95, 0.5 ], "method": "approximate" } } } } ] }'); + document +--------------------------------------------------------------------- + { "_id" : { "$numberInt" : "1" }, "percentileVal" : [ { "$numberDouble" : "67.0" }, { "$numberDouble" : "36.0" } ] } +(1 row) + +-- data value exceeds double range taken as infinity +SELECT document FROM helio_api_catalog.bson_aggregation_pipeline('db', '{ "aggregate": "testPercentileAndMedian", "pipeline": [ { "$group": { "_id": "$group", "percentileVal": { "$percentile": { "input": "$dataVal4", "p": [ 0.95 ], "method": "approximate" } } } } ] }'); + document +--------------------------------------------------------------------- + { "_id" : { "$numberInt" : "1" }, "percentileVal" : [ { "$numberDouble" : "Infinity" } ] } +(1 row) + +-- handle NaN and Infinity values +SELECT document FROM helio_api_catalog.bson_aggregation_pipeline('db', '{ "aggregate": "testPercentileAndMedian", "pipeline": [ { "$group": { "_id": "$group", "percentileVal": { "$percentile": { "input": "$dataVal5", "p": [ 1, 0, 0.1, 0.9, 0.4 ], "method": "approximate" } } } } ] }'); + document +--------------------------------------------------------------------- + { "_id" : { "$numberInt" : "1" }, "percentileVal" : [ { "$numberDouble" : "Infinity" }, { "$numberDouble" : "-Infinity" }, { "$numberDouble" : "-Infinity" }, { "$numberDouble" : "Infinity" }, { "$numberDouble" : "Infinity" } ] } +(1 row) + +-- with $let +SELECT document FROM helio_api_catalog.bson_aggregation_pipeline('db', '{ "aggregate": "testPercentileAndMedian", "pipeline": [{"$group": {"_id": null,"percentileVal": {"$percentile": {"p": "$$ps", "input": "$dataVal","method": "approximate"}}}}], "let": {"ps": [0.95, 0.5]}}'); + document +---------------------------------------------------------------------------------------------------- + { "_id" : null, "percentileVal" : [ { "$numberDouble" : "67.0" }, { "$numberDouble" : "36.0" } ] } +(1 row) + +-- positive test case for median +SELECT document FROM helio_api_catalog.bson_aggregation_pipeline('db', '{ "aggregate": "testPercentileAndMedian", "pipeline": [ { "$group": { "_id": "$group", "medianVal": { "$median": { "input": "$dataVal", "method": "approximate" } } } } ] }'); + document +--------------------------------------------------------------------- + { "_id" : { "$numberInt" : "1" }, "medianVal" : { "$numberDouble" : "36.0" } } +(1 row) + +SELECT document FROM helio_api_catalog.bson_aggregation_pipeline('db', '{ "aggregate": "testPercentileAndMedian", "pipeline": [ { "$group": { "_id": "$group", "medianVal": { "$median": { "input": null, "method": "approximate" } } } } ] }'); + document +--------------------------------------------------------------------- + { "_id" : { "$numberInt" : "1" }, "medianVal" : null } +(1 row) + +-- contain non-numeric value +SELECT document FROM helio_api_catalog.bson_aggregation_pipeline('db', '{ "aggregate": "testPercentileAndMedian", "pipeline": [ { "$group": { "_id": "$group", "medianVal": { "$median": { "input": "$dataVal2", "method": "approximate" } } } } ] }'); + document +--------------------------------------------------------------------- + { "_id" : { "$numberInt" : "1" }, "medianVal" : { "$numberDouble" : "22.0" } } +(1 row) + +-- contain decimal value +SELECT document FROM helio_api_catalog.bson_aggregation_pipeline('db', '{ "aggregate": "testPercentileAndMedian", "pipeline": [ { "$group": { "_id": "$group", "medianVal": { "$median": { "input": "$dataVal3", "method": "approximate" } } } } ] }'); + document +--------------------------------------------------------------------- + { "_id" : { "$numberInt" : "1" }, "medianVal" : { "$numberDouble" : "36.0" } } +(1 row) + +-- data value exceeds double range taken as infinity +SELECT document FROM helio_api_catalog.bson_aggregation_pipeline('db', '{ "aggregate": "testPercentileAndMedian", "pipeline": [ { "$group": { "_id": "$group", "medianVal": { "$median": { "input": "$dataVal4", "method": "approximate" } } } } ] }'); + document +--------------------------------------------------------------------- + { "_id" : { "$numberInt" : "1" }, "medianVal" : { "$numberDouble" : "36.0" } } +(1 row) + +-- handle NaN and Infinity values +SELECT document FROM helio_api_catalog.bson_aggregation_pipeline('db', '{ "aggregate": "testPercentileAndMedian", "pipeline": [ { "$group": { "_id": "$group", "medianVal": { "$median": { "input": "$dataVal5", "method": "approximate" } } } } ] }'); + document +--------------------------------------------------------------------- + { "_id" : { "$numberInt" : "1" }, "medianVal" : { "$numberDouble" : "Infinity" } } +(1 row) + +-- with $let +SELECT document FROM helio_api_catalog.bson_aggregation_pipeline('db', '{ "aggregate": "testPercentileAndMedian", "pipeline": [{"$group": {"_id": null,"medianVal": {"$median": {"input": "$$val","method": "approximate"}}}}], "let": {"val": 5}}'); + document +------------------------------------------------------------- + { "_id" : null, "medianVal" : { "$numberDouble" : "5.0" } } +(1 row) + +-- negative test case for percentile +-- invalid input document +SELECT document FROM helio_api_catalog.bson_aggregation_pipeline('db', '{ "aggregate": "testPercentileAndMedian", "pipeline": [ { "$group": { "_id": "$group", "percentileVal": { "$percentile": 1 } } } ] }'); +ERROR: specification must be an object; found $percentile type: int +-- unkonwn field in input document +SELECT document FROM helio_api_catalog.bson_aggregation_pipeline('db', '{ "aggregate": "testPercentileAndMedian", "pipeline": [ { "$group": { "_id": "$group", "percentileVal": { "$percentile": { "input": "$dataVal", "p": [ 0.95 ], "method": "approximate", "unknownField": "unknownValue" } } } } ] }'); +ERROR: BSON field '$$percentile.unknownField' is an unknown field. +-- p value not an array +SELECT document FROM helio_api_catalog.bson_aggregation_pipeline('db', '{ "aggregate": "testPercentileAndMedian", "pipeline": [ { "$group": { "_id": "$group", "percentileVal": { "$percentile": { "input": "$dataVal", "p": 1.5, "method": "approximate" } } } } ] }'); +ERROR: The $percentile 'p' field must be an array of numbers from [0.0, 1.0], but found: 1.5 +-- p value is an empty array +SELECT document FROM helio_api_catalog.bson_aggregation_pipeline('db', '{ "aggregate": "testPercentileAndMedian", "pipeline": [ { "$group": { "_id": "$group", "percentileVal": { "$percentile": { "input": "$dataVal", "p": [], "method": "approximate" } } } } ] }'); +ERROR: The $percentile 'p' field must be an array of numbers from [0.0, 1.0], but found: [ ] +-- p value is an array with invalid value +SELECT document FROM helio_api_catalog.bson_aggregation_pipeline('db', '{ "aggregate": "testPercentileAndMedian", "pipeline": [ { "$group": { "_id": "$group", "percentileVal": { "$percentile": { "input": "$dataVal", "p": [ 1.5 ], "method": "approximate" } } } } ] }'); +ERROR: The $percentile 'p' field must be an array of numbers from [0.0, 1.0], but found: 1.500000 +-- invalid method +SELECT document FROM helio_api_catalog.bson_aggregation_pipeline('db', '{ "aggregate": "testPercentileAndMedian", "pipeline": [ { "$group": { "_id": "$group", "percentileVal": { "$percentile": { "input": "$dataVal", "p": [ 0.95 ], "method": "invalid" } } } } ] }'); +ERROR: Currently only 'approximate' can be used as percentile 'method' +-- missing input field +SELECT document FROM helio_api_catalog.bson_aggregation_pipeline('db', '{ "aggregate": "testPercentileAndMedian", "pipeline": [ { "$group": { "_id": "$group", "percentileVal": { "$percentile": { "p": [ 0.95 ], "method": "approximate" } } } } ] }'); +ERROR: BSON field '$$percentile.input' is missing but is a required field +-- missing p field +SELECT document FROM helio_api_catalog.bson_aggregation_pipeline('db', '{ "aggregate": "testPercentileAndMedian", "pipeline": [ { "$group": { "_id": "$group", "percentileVal": { "$percentile": { "input": "$dataVal", "method": "approximate" } } } } ] }'); +ERROR: BSON field '$$percentile.p' is missing but is a required field +-- missing method field +SELECT document FROM helio_api_catalog.bson_aggregation_pipeline('db', '{ "aggregate": "testPercentileAndMedian", "pipeline": [ { "$group": { "_id": "$group", "percentileVal": { "$percentile": { "input": "$dataVal", "p": [ 0.95 ] } } } } ] }'); +ERROR: BSON field '$$percentile.method' is missing but is a required field +-- negative test case for median +-- invalid input document +SELECT document FROM helio_api_catalog.bson_aggregation_pipeline('db', '{ "aggregate": "testPercentileAndMedian", "pipeline": [ { "$group": { "_id": "$group", "medianVal": { "$median": 1 } } } ] }'); +ERROR: specification must be an object; found $median type: int +-- unkonwn field in input document +SELECT document FROM helio_api_catalog.bson_aggregation_pipeline('db', '{ "aggregate": "testPercentileAndMedian", "pipeline": [ { "$group": { "_id": "$group", "medianVal": { "$median": { "input": "$dataVal", "method": "approximate", "unknownField": "unknownValue" } } } } ] }'); +ERROR: BSON field '$$median.unknownField' is an unknown field. +-- invalid method +SELECT document FROM helio_api_catalog.bson_aggregation_pipeline('db', '{ "aggregate": "testPercentileAndMedian", "pipeline": [ { "$group": { "_id": "$group", "medianVal": { "$median": { "input": "$dataVal", "method": "invalid" } } } } ] }'); +ERROR: Currently only 'approximate' can be used as percentile 'method' +-- missing input field +SELECT document FROM helio_api_catalog.bson_aggregation_pipeline('db', '{ "aggregate": "testPercentileAndMedian", "pipeline": [ { "$group": { "_id": "$group", "medianVal": { "$median": { "method": "approximate" } } } } ] }'); +ERROR: BSON field '$$median.input' is missing but is a required field +-- missing method field +SELECT document FROM helio_api_catalog.bson_aggregation_pipeline('db', '{ "aggregate": "testPercentileAndMedian", "pipeline": [ { "$group": { "_id": "$group", "medianVal": { "$median": { "input": "$dataVal" } } } } ] }'); +ERROR: BSON field '$$median.method' is missing but is a required field +/* shard collection */ +SELECT helio_api.shard_collection('db', 'testPercentileAndMedian', '{ "_id": "hashed" }', false); + shard_collection +--------------------------------------------------------------------- + +(1 row) + +-- percentile +SELECT document FROM helio_api_catalog.bson_aggregation_pipeline('db', '{ "aggregate": "testPercentileAndMedian", "pipeline": [ { "$group": { "_id": "$group", "percentileVal": { "$percentile": { "input": "$dataVal", "p": [ 0.95, 0.5 ], "method": "approximate" } } } } ] }'); + document +--------------------------------------------------------------------- + { "_id" : { "$numberInt" : "1" }, "percentileVal" : [ { "$numberDouble" : "67.0" }, { "$numberDouble" : "36.0" } ] } +(1 row) + +-- median +SELECT document FROM helio_api_catalog.bson_aggregation_pipeline('db', '{ "aggregate": "testPercentileAndMedian", "pipeline": [ { "$group": { "_id": "$group", "medianVal": { "$median": { "input": "$dataVal", "method": "approximate" } } } } ] }'); + document +--------------------------------------------------------------------- + { "_id" : { "$numberInt" : "1" }, "medianVal" : { "$numberDouble" : "36.0" } } +(1 row) + diff --git a/internal/pg_helio_distributed/src/test/regress/expected/setwindowfields_and_group_compliance.out b/internal/pg_helio_distributed/src/test/regress/expected/setwindowfields_and_group_compliance.out index 8229b379..30bd7d5e 100644 --- a/internal/pg_helio_distributed/src/test/regress/expected/setwindowfields_and_group_compliance.out +++ b/internal/pg_helio_distributed/src/test/regress/expected/setwindowfields_and_group_compliance.out @@ -75,9 +75,9 @@ END $$; NOTICE: [TEST PASSED] Operator $bottom is supported in both $group and $setWindowFields NOTICE: [TEST PASSED] Operator $bottomN is supported in both $group and $setWindowFields NOTICE: [TEST PASSED] Operator $maxN is supported in both $group and $setWindowFields -NOTICE: [TEST PASSED] Operator $median is not supported in both $group and $setWindowFields +NOTICE: [TEST FAILED] Operator $median is not supported in $setWindowFields NOTICE: [TEST PASSED] Operator $minN is supported in both $group and $setWindowFields -NOTICE: [TEST PASSED] Operator $percentile is not supported in both $group and $setWindowFields +NOTICE: [TEST FAILED] Operator $percentile is not supported in $setWindowFields NOTICE: [TEST PASSED] Operator $stdDevSamp is supported in both $group and $setWindowFields NOTICE: [TEST PASSED] Operator $stdDevPop is supported in both $group and $setWindowFields NOTICE: [TEST PASSED] Operator $top is supported in both $group and $setWindowFields diff --git a/internal/pg_helio_distributed/src/test/regress/sql/bson_aggregation_pipeline_tests_percentile_median.sql b/internal/pg_helio_distributed/src/test/regress/sql/bson_aggregation_pipeline_tests_percentile_median.sql new file mode 100644 index 00000000..d2c95840 --- /dev/null +++ b/internal/pg_helio_distributed/src/test/regress/sql/bson_aggregation_pipeline_tests_percentile_median.sql @@ -0,0 +1,84 @@ +-- will move to bson_aggregation_pipeline_stage_setWindowFields.sql and remove this file after window operator is done, just like $stddevopo did +SET search_path TO helio_core,helio_api,helio_api_catalog,helio_api_internal; + +SET citus.next_shard_id TO 1033000; +SET helio_api.next_collection_id TO 10330; +SET helio_api.next_collection_index_id TO 10330; + +SELECT helio_api.insert_one('db','testPercentileAndMedian',' { "_id" : 1, "group": 1, "dataVal": 36, "dataVal2": 36, "dataVal3": {"$numberDecimal": "36"}, "dataVal4": 36, "dataVal5": NaN }', NULL); +SELECT helio_api.insert_one('db','testPercentileAndMedian',' { "_id" : 2, "group": 1, "dataVal": 22, "dataVal2": 22, "dataVal3": {"$numberDecimal": "22"}, "dataVal4": 22, "dataVal5": Infinity }', NULL); +SELECT helio_api.insert_one('db','testPercentileAndMedian',' { "_id" : 3, "group": 1, "dataVal": 67, "dataVal2": "string", "dataVal3": {"$numberDecimal": "67"}, "dataVal4": {"$numberDecimal": "2E+310"}, "dataVal5": Infinity }', NULL); +SELECT helio_api.insert_one('db','testPercentileAndMedian',' { "_id" : 4, "group": 1, "dataVal": 3, "dataVal2": 3, "dataVal3": {"$numberDecimal": "3"}, "dataVal4": 3, "dataVal5": -Infinity }', NULL); +SELECT helio_api.insert_one('db','testPercentileAndMedian',' { "_id" : 5, "group": 1, "dataVal": 55, "dataVal2": 55, "dataVal3": {"$numberDecimal": "55"}, "dataVal4": 55, "dataVal5": NaN }', NULL); + +-- positive test case for percentile +SELECT document FROM helio_api_catalog.bson_aggregation_pipeline('db', '{ "aggregate": "testPercentileAndMedian", "pipeline": [ { "$group": { "_id": "$group", "percentileVal": { "$percentile": { "input": "$dataVal", "p": [ 0.95 ], "method": "approximate" } } } } ] }'); +SELECT document FROM helio_api_catalog.bson_aggregation_pipeline('db', '{ "aggregate": "testPercentileAndMedian", "pipeline": [ { "$group": { "_id": "$group", "percentileVal": { "$percentile": { "input": "$dataVal", "p": [ 0.95, 0.5 ], "method": "approximate" } } } } ] }'); +SELECT document FROM helio_api_catalog.bson_aggregation_pipeline('db', '{ "aggregate": "testPercentileAndMedian", "pipeline": [ { "$group": { "_id": "$group", "percentileVal": { "$percentile": { "input": null, "p": [ 0.95 ], "method": "approximate" } } } } ] }'); +-- contain non-numeric value +SELECT document FROM helio_api_catalog.bson_aggregation_pipeline('db', '{ "aggregate": "testPercentileAndMedian", "pipeline": [ { "$group": { "_id": "$group", "percentileVal": { "$percentile": { "input": "$dataVal2", "p": [ 0.95 ], "method": "approximate" } } } } ] }'); +SELECT document FROM helio_api_catalog.bson_aggregation_pipeline('db', '{ "aggregate": "testPercentileAndMedian", "pipeline": [ { "$group": { "_id": "$group", "percentileVal": { "$percentile": { "input": "$dataVal2", "p": [ 0.95, 0.5 ], "method": "approximate" } } } } ] }'); +-- contain decimal value +SELECT document FROM helio_api_catalog.bson_aggregation_pipeline('db', '{ "aggregate": "testPercentileAndMedian", "pipeline": [ { "$group": { "_id": "$group", "percentileVal": { "$percentile": { "input": "$dataVal3", "p": [ 0.95 ], "method": "approximate" } } } } ] }'); +SELECT document FROM helio_api_catalog.bson_aggregation_pipeline('db', '{ "aggregate": "testPercentileAndMedian", "pipeline": [ { "$group": { "_id": "$group", "percentileVal": { "$percentile": { "input": "$dataVal3", "p": [ 0.95, 0.5 ], "method": "approximate" } } } } ] }'); +-- data value exceeds double range taken as infinity +SELECT document FROM helio_api_catalog.bson_aggregation_pipeline('db', '{ "aggregate": "testPercentileAndMedian", "pipeline": [ { "$group": { "_id": "$group", "percentileVal": { "$percentile": { "input": "$dataVal4", "p": [ 0.95 ], "method": "approximate" } } } } ] }'); +-- handle NaN and Infinity values +SELECT document FROM helio_api_catalog.bson_aggregation_pipeline('db', '{ "aggregate": "testPercentileAndMedian", "pipeline": [ { "$group": { "_id": "$group", "percentileVal": { "$percentile": { "input": "$dataVal5", "p": [ 1, 0, 0.1, 0.9, 0.4 ], "method": "approximate" } } } } ] }'); +-- with $let +SELECT document FROM helio_api_catalog.bson_aggregation_pipeline('db', '{ "aggregate": "testPercentileAndMedian", "pipeline": [{"$group": {"_id": null,"percentileVal": {"$percentile": {"p": "$$ps", "input": "$dataVal","method": "approximate"}}}}], "let": {"ps": [0.95, 0.5]}}'); + +-- positive test case for median +SELECT document FROM helio_api_catalog.bson_aggregation_pipeline('db', '{ "aggregate": "testPercentileAndMedian", "pipeline": [ { "$group": { "_id": "$group", "medianVal": { "$median": { "input": "$dataVal", "method": "approximate" } } } } ] }'); +SELECT document FROM helio_api_catalog.bson_aggregation_pipeline('db', '{ "aggregate": "testPercentileAndMedian", "pipeline": [ { "$group": { "_id": "$group", "medianVal": { "$median": { "input": null, "method": "approximate" } } } } ] }'); +-- contain non-numeric value +SELECT document FROM helio_api_catalog.bson_aggregation_pipeline('db', '{ "aggregate": "testPercentileAndMedian", "pipeline": [ { "$group": { "_id": "$group", "medianVal": { "$median": { "input": "$dataVal2", "method": "approximate" } } } } ] }'); +-- contain decimal value +SELECT document FROM helio_api_catalog.bson_aggregation_pipeline('db', '{ "aggregate": "testPercentileAndMedian", "pipeline": [ { "$group": { "_id": "$group", "medianVal": { "$median": { "input": "$dataVal3", "method": "approximate" } } } } ] }'); +-- data value exceeds double range taken as infinity +SELECT document FROM helio_api_catalog.bson_aggregation_pipeline('db', '{ "aggregate": "testPercentileAndMedian", "pipeline": [ { "$group": { "_id": "$group", "medianVal": { "$median": { "input": "$dataVal4", "method": "approximate" } } } } ] }'); +-- handle NaN and Infinity values +SELECT document FROM helio_api_catalog.bson_aggregation_pipeline('db', '{ "aggregate": "testPercentileAndMedian", "pipeline": [ { "$group": { "_id": "$group", "medianVal": { "$median": { "input": "$dataVal5", "method": "approximate" } } } } ] }'); +-- with $let +SELECT document FROM helio_api_catalog.bson_aggregation_pipeline('db', '{ "aggregate": "testPercentileAndMedian", "pipeline": [{"$group": {"_id": null,"medianVal": {"$median": {"input": "$$val","method": "approximate"}}}}], "let": {"val": 5}}'); + +-- negative test case for percentile +-- invalid input document +SELECT document FROM helio_api_catalog.bson_aggregation_pipeline('db', '{ "aggregate": "testPercentileAndMedian", "pipeline": [ { "$group": { "_id": "$group", "percentileVal": { "$percentile": 1 } } } ] }'); +-- unkonwn field in input document +SELECT document FROM helio_api_catalog.bson_aggregation_pipeline('db', '{ "aggregate": "testPercentileAndMedian", "pipeline": [ { "$group": { "_id": "$group", "percentileVal": { "$percentile": { "input": "$dataVal", "p": [ 0.95 ], "method": "approximate", "unknownField": "unknownValue" } } } } ] }'); +-- p value not an array +SELECT document FROM helio_api_catalog.bson_aggregation_pipeline('db', '{ "aggregate": "testPercentileAndMedian", "pipeline": [ { "$group": { "_id": "$group", "percentileVal": { "$percentile": { "input": "$dataVal", "p": 1.5, "method": "approximate" } } } } ] }'); +-- p value is an empty array +SELECT document FROM helio_api_catalog.bson_aggregation_pipeline('db', '{ "aggregate": "testPercentileAndMedian", "pipeline": [ { "$group": { "_id": "$group", "percentileVal": { "$percentile": { "input": "$dataVal", "p": [], "method": "approximate" } } } } ] }'); +-- p value is an array with invalid value +SELECT document FROM helio_api_catalog.bson_aggregation_pipeline('db', '{ "aggregate": "testPercentileAndMedian", "pipeline": [ { "$group": { "_id": "$group", "percentileVal": { "$percentile": { "input": "$dataVal", "p": [ 1.5 ], "method": "approximate" } } } } ] }'); +-- invalid method +SELECT document FROM helio_api_catalog.bson_aggregation_pipeline('db', '{ "aggregate": "testPercentileAndMedian", "pipeline": [ { "$group": { "_id": "$group", "percentileVal": { "$percentile": { "input": "$dataVal", "p": [ 0.95 ], "method": "invalid" } } } } ] }'); +-- missing input field +SELECT document FROM helio_api_catalog.bson_aggregation_pipeline('db', '{ "aggregate": "testPercentileAndMedian", "pipeline": [ { "$group": { "_id": "$group", "percentileVal": { "$percentile": { "p": [ 0.95 ], "method": "approximate" } } } } ] }'); +-- missing p field +SELECT document FROM helio_api_catalog.bson_aggregation_pipeline('db', '{ "aggregate": "testPercentileAndMedian", "pipeline": [ { "$group": { "_id": "$group", "percentileVal": { "$percentile": { "input": "$dataVal", "method": "approximate" } } } } ] }'); +-- missing method field +SELECT document FROM helio_api_catalog.bson_aggregation_pipeline('db', '{ "aggregate": "testPercentileAndMedian", "pipeline": [ { "$group": { "_id": "$group", "percentileVal": { "$percentile": { "input": "$dataVal", "p": [ 0.95 ] } } } } ] }'); + +-- negative test case for median +-- invalid input document +SELECT document FROM helio_api_catalog.bson_aggregation_pipeline('db', '{ "aggregate": "testPercentileAndMedian", "pipeline": [ { "$group": { "_id": "$group", "medianVal": { "$median": 1 } } } ] }'); +-- unkonwn field in input document +SELECT document FROM helio_api_catalog.bson_aggregation_pipeline('db', '{ "aggregate": "testPercentileAndMedian", "pipeline": [ { "$group": { "_id": "$group", "medianVal": { "$median": { "input": "$dataVal", "method": "approximate", "unknownField": "unknownValue" } } } } ] }'); +-- invalid method +SELECT document FROM helio_api_catalog.bson_aggregation_pipeline('db', '{ "aggregate": "testPercentileAndMedian", "pipeline": [ { "$group": { "_id": "$group", "medianVal": { "$median": { "input": "$dataVal", "method": "invalid" } } } } ] }'); +-- missing input field +SELECT document FROM helio_api_catalog.bson_aggregation_pipeline('db', '{ "aggregate": "testPercentileAndMedian", "pipeline": [ { "$group": { "_id": "$group", "medianVal": { "$median": { "method": "approximate" } } } } ] }'); +-- missing method field +SELECT document FROM helio_api_catalog.bson_aggregation_pipeline('db', '{ "aggregate": "testPercentileAndMedian", "pipeline": [ { "$group": { "_id": "$group", "medianVal": { "$median": { "input": "$dataVal" } } } } ] }'); + + +/* shard collection */ +SELECT helio_api.shard_collection('db', 'testPercentileAndMedian', '{ "_id": "hashed" }', false); + +-- percentile +SELECT document FROM helio_api_catalog.bson_aggregation_pipeline('db', '{ "aggregate": "testPercentileAndMedian", "pipeline": [ { "$group": { "_id": "$group", "percentileVal": { "$percentile": { "input": "$dataVal", "p": [ 0.95, 0.5 ], "method": "approximate" } } } } ] }'); +-- median +SELECT document FROM helio_api_catalog.bson_aggregation_pipeline('db', '{ "aggregate": "testPercentileAndMedian", "pipeline": [ { "$group": { "_id": "$group", "medianVal": { "$median": { "input": "$dataVal", "method": "approximate" } } } } ] }'); \ No newline at end of file diff --git a/mongoerrors.csv b/mongoerrors.csv index e47d24ae..fb1d03ac 100644 --- a/mongoerrors.csv +++ b/mongoerrors.csv @@ -497,4 +497,9 @@ MongoError,ErrorName 6050204,Location6050204 6053600,Location6053600 6586400,Location6586400 +7429703,Location7429703 +7436100,Location7436100 +7750301,Location7750301 +7750302,Location7750302 +7750303,Location7750303 8993000,Location8993000 diff --git a/pg_documentdb/include/aggregation/bson_aggregation_pipeline.h b/pg_documentdb/include/aggregation/bson_aggregation_pipeline.h index 1130a48b..cfe1ed4f 100644 --- a/pg_documentdb/include/aggregation/bson_aggregation_pipeline.h +++ b/pg_documentdb/include/aggregation/bson_aggregation_pipeline.h @@ -109,6 +109,9 @@ void ParseInputDocumentForTopAndBottom(const bson_value_t *inputDocument, bson_value_t *input, bson_value_t *elementsToFetch, bson_value_t *sortSpec, const char *opName); +void ParseInputDocumentForMedianAndPercentile(const bson_value_t *inputDocument, + bson_value_t *input, bson_value_t *p, + bson_value_t *method, bool isMedianOp); void ValidateElementForNGroupAccumulators(bson_value_t *elementsToFetch, const char *opName); void ParseInputForNGroupAccumulators(const bson_value_t *inputDocument, diff --git a/pg_documentdb/include/metadata/metadata_cache.h b/pg_documentdb/include/metadata/metadata_cache.h index 6774d194..9ebdf48a 100644 --- a/pg_documentdb/include/metadata/metadata_cache.h +++ b/pg_documentdb/include/metadata/metadata_cache.h @@ -350,6 +350,8 @@ Oid ApiIndexStatsAggregationFunctionOid(void); Oid BsonCurrentOpAggregationFunctionId(void); Oid BsonMaxNAggregateFunctionOid(void); Oid BsonMinNAggregateFunctionOid(void); +Oid BsonMedianAggregateFunctionOid(void); +Oid BsonPercentileAggregateFunctionOid(void); /* Window functions*/ Oid BsonLinearFillFunctionOid(void); diff --git a/pg_documentdb/include/utils/feature_counter.h b/pg_documentdb/include/utils/feature_counter.h index 89cb7dd7..b0433afe 100644 --- a/pg_documentdb/include/utils/feature_counter.h +++ b/pg_documentdb/include/utils/feature_counter.h @@ -15,7 +15,7 @@ #include #define MAX_FEATURE_NAME_LENGTH 255 -#define MAX_FEATURE_COUNT 256 +#define MAX_FEATURE_COUNT 258 /* Internal features that are not exposed */ #define INTERNAL_FEATURE_TYPE MAX_FEATURE_COUNT @@ -256,6 +256,8 @@ typedef enum FEATURE_STAGE_GROUP_ACC_FIRSTN_GT10, FEATURE_STAGE_GROUP_ACC_LASTN, FEATURE_STAGE_GROUP_ACC_LASTN_GT10, + FEATURE_STAGE_GROUP_ACC_MEDIAN, + FEATURE_STAGE_GROUP_ACC_PERCENTILE, FEATURE_STAGE_GROUP_ACC_TOPN, FEATURE_STAGE_INDEXSTATS, FEATURE_STAGE_INVERSEMATCH, diff --git a/pg_documentdb/sql/documentdb--0.24-0.sql b/pg_documentdb/sql/documentdb--0.24-0.sql index 7d8c1396..e978f505 100644 --- a/pg_documentdb/sql/documentdb--0.24-0.sql +++ b/pg_documentdb/sql/documentdb--0.24-0.sql @@ -108,8 +108,8 @@ CREATE SCHEMA documentdb_data; #include "udfs/aggregation/window_aggregate_support--0.22-0.sql" #include "udfs/aggregation/window_aggregates--0.22-0.sql" -#include "udfs/aggregation/group_aggregates_support--0.22-0.sql" -#include "udfs/aggregation/group_aggregates--0.22-0.sql" +#include "udfs/aggregation/group_aggregates_support--0.24-0.sql" +#include "udfs/aggregation/group_aggregates--0.24-0.sql" #include "udfs/aggregation/bson_unwind_functions--0.10-0.sql" #include "udfs/aggregation/bson_lookup_functions--0.23-0.sql" diff --git a/pg_documentdb/sql/udfs/aggregation/group_aggregates--0.24-0.sql b/pg_documentdb/sql/udfs/aggregation/group_aggregates--0.24-0.sql new file mode 100644 index 00000000..407bced7 --- /dev/null +++ b/pg_documentdb/sql/udfs/aggregation/group_aggregates--0.24-0.sql @@ -0,0 +1,404 @@ + +CREATE OR REPLACE AGGREGATE __API_CATALOG_SCHEMA__.BSONSUM(__CORE_SCHEMA__.bson) +( + SFUNC = __API_CATALOG_SCHEMA__.bson_sum_avg_transition, + FINALFUNC = __API_CATALOG_SCHEMA__.bson_sum_final, + stype = bytea, + COMBINEFUNC = __API_CATALOG_SCHEMA__.bson_sum_avg_combine, + mstype = bytea, + MSFUNC = __API_CATALOG_SCHEMA__.bson_sum_avg_transition, + MFINALFUNC = __API_CATALOG_SCHEMA__.bson_sum_final, + MINVFUNC = __API_SCHEMA_INTERNAL_V2__.bson_sum_avg_minvtransition, + PARALLEL = SAFE +); + +CREATE OR REPLACE AGGREGATE __API_CATALOG_SCHEMA__.BSONAVERAGE(__CORE_SCHEMA__.bson) +( + SFUNC = __API_CATALOG_SCHEMA__.bson_sum_avg_transition, + FINALFUNC = __API_CATALOG_SCHEMA__.bson_avg_final, + stype = bytea, + COMBINEFUNC = __API_CATALOG_SCHEMA__.bson_sum_avg_combine, + mstype = bytea, + MSFUNC = __API_CATALOG_SCHEMA__.bson_sum_avg_transition, + MFINALFUNC = __API_CATALOG_SCHEMA__.bson_avg_final, + MINVFUNC = __API_SCHEMA_INTERNAL_V2__.bson_sum_avg_minvtransition, + PARALLEL = SAFE +); + +CREATE OR REPLACE AGGREGATE __API_CATALOG_SCHEMA__.BSONMAX(__CORE_SCHEMA__.bson) +( + SFUNC = __API_CATALOG_SCHEMA__.bson_max_transition, + FINALFUNC = __API_CATALOG_SCHEMA__.bson_min_max_final, + stype = __CORE_SCHEMA__.bson, + COMBINEFUNC = __API_CATALOG_SCHEMA__.bson_max_combine, + PARALLEL = SAFE +); + +CREATE OR REPLACE AGGREGATE __API_CATALOG_SCHEMA__.BSONMIN(__CORE_SCHEMA__.bson) +( + SFUNC = __API_CATALOG_SCHEMA__.bson_min_transition, + FINALFUNC = __API_CATALOG_SCHEMA__.bson_min_max_final, + stype = __CORE_SCHEMA__.bson, + COMBINEFUNC = __API_CATALOG_SCHEMA__.bson_min_combine, + PARALLEL = SAFE +); + + +/* +* __API_CATALOG_SCHEMA__.bsonFIRST and __API_CATALOG_SCHEMA__.bsonLAST are the custom aggregation for first() and +* last() accumulators when sorting/ordering operation can be pushed +* down to the worker nodes. +* +* Worker nodes will apply the transition function on their share of +* the data to generate one partial AGGREGATE __API_CATALOG_SCHEMA__.per group per worker. +* The coordinator will then combine the partial aggregates using +* the combine function. Finally the finalfunc will be called on the +* intermediate result for each group. +* +* Note that __API_CATALOG_SCHEMA__.bsonFIRST() and __API_CATALOG_SCHEMA__.bsonLAST() has a __API_CATALOG_SCHEMA__.bson[] as the second +* argument which is an array of sort order specs of the form +* document |-<> '{ "sorkeypath1":1}'. The worker nodes will use +* these sort keys to order the documents while applying the transition +* function. +*/ +CREATE OR REPLACE AGGREGATE __API_CATALOG_SCHEMA__.BSONFIRST(__CORE_SCHEMA__.bson, __CORE_SCHEMA__.bson[]) +( + SFUNC = __API_CATALOG_SCHEMA__.bson_first_transition, + FINALFUNC = __API_CATALOG_SCHEMA__.bson_first_last_final, + stype = bytea, + COMBINEFUNC = __API_CATALOG_SCHEMA__.bson_first_combine, + PARALLEL = SAFE +); + +/* +* See summary of __CORE_SCHEMA__.bsonFIRST() +*/ +CREATE OR REPLACE AGGREGATE __API_CATALOG_SCHEMA__.BSONLAST(__CORE_SCHEMA__.bson, __CORE_SCHEMA__.bson[]) +( + SFUNC = __API_CATALOG_SCHEMA__.bson_last_transition, + FINALFUNC = __API_CATALOG_SCHEMA__.bson_first_last_final, + stype = bytea, + COMBINEFUNC = __API_CATALOG_SCHEMA__.bson_last_combine, + PARALLEL = SAFE +); + +/* +* __CORE_SCHEMA__.bsonFIRSTONSORTED and __CORE_SCHEMA__.bsonLASTONSORTED are the custom aggregation +* functions for first() and last() accumulators when the input to +* the group by stage is pre-sorted. +* +* In this case the aggregation is not pushed down to the worker node. +* All the data will be pulled at the coordinator and the transition +* function will be called on that data. +* +* Note the missing COMBINEFUNC. Since the work will be done at the +* coordinator, we won't need that. +*/ +CREATE OR REPLACE AGGREGATE __API_CATALOG_SCHEMA__.BSONFIRSTONSORTED(__CORE_SCHEMA__.bson) +( + SFUNC = __API_CATALOG_SCHEMA__.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 __API_CATALOG_SCHEMA__.BSONLASTONSORTED(__CORE_SCHEMA__.bson) +( + SFUNC = __API_CATALOG_SCHEMA__.bson_last_transition_on_sorted, + FINALFUNC = __API_CATALOG_SCHEMA__.bson_first_last_final_on_sorted, + stype = bytea, + PARALLEL = SAFE +); + +/* +* __CORE_SCHEMA__.bsonFIRSTN and __CORE_SCHEMA__.bsonLASTN are the custom aggregation for firstN() and +* lastN() accumulators when sorting/ordering operation can be pushed +* down to the worker nodes. +* +* Worker nodes will apply the transition function on their share of +* the data to generate one partial AGGREGATE __API_CATALOG_SCHEMA__.per group per worker. +* The coordinator will then combine the partial aggregates using +* the combine function. Finally the finalfunc will be called on the +* intermediate result for each group. +* +* Second argument is the number of results to return or 'n'. +* +* Note that __CORE_SCHEMA__.bsonFIRSTN() and __CORE_SCHEMA__.bsonLASTN() has a __CORE_SCHEMA__.bson[] as the third +* argument which is an array of sort order specs of the form +* document | -<> '{ "sorkeypath1":1}'. The worker nodes will use +* these sort keys to order the documents while applying the transition +* function. +*/ +CREATE OR REPLACE AGGREGATE __API_CATALOG_SCHEMA__.BSONFIRSTN(__CORE_SCHEMA__.bson, bigint, __CORE_SCHEMA__.bson[]) +( + SFUNC = __API_CATALOG_SCHEMA__.bson_firstn_transition, + FINALFUNC = __API_CATALOG_SCHEMA__.bson_firstn_lastn_final, + stype = bytea, + COMBINEFUNC = __API_CATALOG_SCHEMA__.bson_firstn_combine, + PARALLEL = SAFE +); + +/* +* See summary of __CORE_SCHEMA__.bsonFIRSTN() +*/ +CREATE OR REPLACE AGGREGATE __API_CATALOG_SCHEMA__.BSONLASTN(__CORE_SCHEMA__.bson, bigint, __CORE_SCHEMA__.bson[]) +( + SFUNC = __API_CATALOG_SCHEMA__.bson_lastn_transition, + FINALFUNC = __API_CATALOG_SCHEMA__.bson_firstn_lastn_final, + stype = bytea, + COMBINEFUNC = __API_CATALOG_SCHEMA__.bson_lastn_combine, + PARALLEL = SAFE +); + +/* +* __CORE_SCHEMA__.bsonFIRSTNONSORTED and __CORE_SCHEMA__.bsonLASTNONSORTED are the custom aggregation +* functions for firstn() and lastn() accumulators when the input to +* the group by stage is pre-sorted. +* +* In this case the aggregation is not pushed down to the worker node. +* All the data will be pulled at the coordinator and the transition +* function will be called on that data. +* +* Note the missing COMBINEFUNC. Since the work will be done at the +* coordinator, we won\'t need that. +*/ +CREATE OR REPLACE AGGREGATE __API_CATALOG_SCHEMA__.BSONFIRSTNONSORTED(__CORE_SCHEMA__.bson, bigint) +( + SFUNC = __API_CATALOG_SCHEMA__.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 __API_CATALOG_SCHEMA__.BSONLASTNONSORTED(__CORE_SCHEMA__.bson, bigint) +( + SFUNC = __API_CATALOG_SCHEMA__.bson_lastn_transition_on_sorted, + FINALFUNC = __API_CATALOG_SCHEMA__.bson_firstn_lastn_final_on_sorted, + stype = bytea, + PARALLEL = SAFE +); + +CREATE OR REPLACE AGGREGATE __API_CATALOG_SCHEMA__.BSON_ARRAY_AGG(__CORE_SCHEMA__.bson, text) +( + SFUNC = __API_CATALOG_SCHEMA__.bson_array_agg_transition, + FINALFUNC = __API_CATALOG_SCHEMA__.bson_array_agg_final, + stype = bytea, + PARALLEL = SAFE +); + +CREATE OR REPLACE AGGREGATE __API_CATALOG_SCHEMA__.BSON_OBJECT_AGG(__CORE_SCHEMA__.bson) +( + SFUNC = __API_CATALOG_SCHEMA__.bson_object_agg_transition, + FINALFUNC = __API_CATALOG_SCHEMA__.bson_object_agg_final, + stype = bytea, + PARALLEL = SAFE +); + +CREATE OR REPLACE AGGREGATE __API_CATALOG_SCHEMA__.BSON_OUT(__CORE_SCHEMA__.bson, text, text, text, text) +( + SFUNC = __API_CATALOG_SCHEMA__.bson_out_transition, + FINALFUNC = __API_CATALOG_SCHEMA__.bson_out_final, + stype = bytea +); + +/* + * Implementation of the bson_array_agg aggregator with the addition of a boolean + * field that indicates whether to treat { "": value } as an object or value. + */ +CREATE OR REPLACE AGGREGATE __API_CATALOG_SCHEMA__.BSON_ARRAY_AGG(__CORE_SCHEMA__.bson, text, boolean) +( + SFUNC = __API_CATALOG_SCHEMA__.bson_array_agg_transition, + FINALFUNC = __API_CATALOG_SCHEMA__.bson_array_agg_final, + stype = bytea, + mstype = bytea, + MSFUNC = __API_CATALOG_SCHEMA__.bson_array_agg_transition, + MFINALFUNC = __API_CATALOG_SCHEMA__.bson_array_agg_final, + MINVFUNC = __API_SCHEMA_INTERNAL_V2__.bson_array_agg_minvtransition, + PARALLEL = SAFE +); + +CREATE OR REPLACE AGGREGATE __API_SCHEMA_INTERNAL_V2__.BSON_ADD_TO_SET(__CORE_SCHEMA_V2__.bson) +( + SFUNC = __API_SCHEMA_INTERNAL_V2__.bson_add_to_set_transition, + FINALFUNC = __API_SCHEMA_INTERNAL_V2__.bson_add_to_set_final, + stype = bytea, + PARALLEL = SAFE +); + +CREATE OR REPLACE AGGREGATE __API_SCHEMA_INTERNAL_V2__.BSON_MERGE_OBJECTS_ON_SORTED(__CORE_SCHEMA_V2__.bson) +( + SFUNC = __API_SCHEMA_INTERNAL_V2__.bson_merge_objects_transition_on_sorted, + FINALFUNC = __API_CATALOG_SCHEMA__.bson_object_agg_final, + stype = bytea, + PARALLEL = SAFE +); + +/* + * This can't use __CORE_SCHEMA_V2__.bson due to citus type checks. We can migrate once the underlying tuples use the new types. + */ +CREATE OR REPLACE AGGREGATE __API_SCHEMA_INTERNAL_V2__.BSON_MERGE_OBJECTS(__CORE_SCHEMA__.bson, bigint, __CORE_SCHEMA__.bson[], __CORE_SCHEMA__.bson) +( + SFUNC = __API_SCHEMA_INTERNAL_V2__.bson_merge_objects_transition, + FINALFUNC = __API_SCHEMA_INTERNAL_V2__.bson_merge_objects_final, + stype = bytea, + COMBINEFUNC = __API_CATALOG_SCHEMA__.bson_firstn_combine, + PARALLEL = SAFE +); + +CREATE OR REPLACE AGGREGATE __API_SCHEMA_INTERNAL_V2__.BSONSTDDEVPOP(__CORE_SCHEMA__.bson) +( + SFUNC = __API_SCHEMA_INTERNAL_V2__.bson_std_dev_pop_samp_transition, + FINALFUNC = __API_SCHEMA_INTERNAL_V2__.bson_std_dev_pop_final, + MSFUNC = __API_SCHEMA_INTERNAL_V2__.bson_std_dev_pop_samp_transition, + MFINALFUNC = __API_SCHEMA_INTERNAL_V2__.bson_std_dev_pop_winfunc_final, + MINVFUNC = __API_SCHEMA_INTERNAL_V2__.bson_std_dev_pop_samp_winfunc_invtransition, + stype = bytea, + mstype = bytea, + COMBINEFUNC = __API_SCHEMA_INTERNAL_V2__.bson_std_dev_pop_samp_combine, + PARALLEL = SAFE +); + +CREATE OR REPLACE AGGREGATE __API_SCHEMA_INTERNAL_V2__.BSONSTDDEVSAMP(__CORE_SCHEMA__.bson) +( + SFUNC = __API_SCHEMA_INTERNAL_V2__.bson_std_dev_pop_samp_transition, + FINALFUNC = __API_SCHEMA_INTERNAL_V2__.bson_std_dev_samp_final, + MSFUNC = __API_SCHEMA_INTERNAL_V2__.bson_std_dev_pop_samp_transition, + MFINALFUNC = __API_SCHEMA_INTERNAL_V2__.bson_std_dev_samp_winfunc_final, + MINVFUNC = __API_SCHEMA_INTERNAL_V2__.bson_std_dev_pop_samp_winfunc_invtransition, + stype = bytea, + mstype = bytea, + COMBINEFUNC = __API_SCHEMA_INTERNAL_V2__.bson_std_dev_pop_samp_combine, + PARALLEL = SAFE +); + +/* + * Additional argument to BSONFIRST corresponding to input expression for $top operator + */ +CREATE OR REPLACE AGGREGATE __API_SCHEMA_INTERNAL_V2__.BSONFIRST(__CORE_SCHEMA__.bson, __CORE_SCHEMA__.bson[], __CORE_SCHEMA__.bson) +( + SFUNC = __API_SCHEMA_INTERNAL_V2__.bson_first_transition, + FINALFUNC = __API_CATALOG_SCHEMA__.bson_first_last_final, + stype = bytea, + COMBINEFUNC = __API_CATALOG_SCHEMA__.bson_first_combine, + PARALLEL = SAFE +); + +/* + * Additional argument to BSONLAST corresponding to input expression for $bottom operator + */ +CREATE OR REPLACE AGGREGATE __API_SCHEMA_INTERNAL_V2__.BSONLAST(__CORE_SCHEMA__.bson, __CORE_SCHEMA__.bson[], __CORE_SCHEMA__.bson) +( + SFUNC = __API_SCHEMA_INTERNAL_V2__.bson_last_transition, + FINALFUNC = __API_CATALOG_SCHEMA__.bson_first_last_final, + stype = bytea, + COMBINEFUNC = __API_CATALOG_SCHEMA__.bson_last_combine, + PARALLEL = SAFE +); + +/* + * Additional argument to BSONFIRSTN corresponding to input expression for $topN operator + */ +CREATE OR REPLACE AGGREGATE __API_SCHEMA_INTERNAL_V2__.BSONFIRSTN(__CORE_SCHEMA__.bson, bigint, __CORE_SCHEMA__.bson[], __CORE_SCHEMA__.bson) +( + SFUNC = __API_SCHEMA_INTERNAL_V2__.bson_firstn_transition, + FINALFUNC = __API_CATALOG_SCHEMA__.bson_firstn_lastn_final, + stype = bytea, + COMBINEFUNC = __API_CATALOG_SCHEMA__.bson_firstn_combine, + PARALLEL = SAFE +); + +/* + * Additional argument to BSONLASTN corresponding to input expression for $bottomN operator + */ +CREATE OR REPLACE AGGREGATE __API_SCHEMA_INTERNAL_V2__.BSONLASTN(__CORE_SCHEMA__.bson, bigint, __CORE_SCHEMA__.bson[], __CORE_SCHEMA__.bson) +( + SFUNC = __API_SCHEMA_INTERNAL_V2__.bson_lastn_transition, + FINALFUNC = __API_CATALOG_SCHEMA__.bson_firstn_lastn_final, + stype = bytea, + COMBINEFUNC = __API_CATALOG_SCHEMA__.bson_lastn_combine, + PARALLEL = SAFE +); + +CREATE OR REPLACE AGGREGATE __API_SCHEMA_INTERNAL_V2__.BSONMAXN(__CORE_SCHEMA__.bson) +( + SFUNC = __API_SCHEMA_INTERNAL_V2__.bson_maxn_transition, + FINALFUNC = __API_SCHEMA_INTERNAL_V2__.bson_maxminn_final, + stype = bytea, + COMBINEFUNC = __API_SCHEMA_INTERNAL_V2__.bson_maxminn_combine, + PARALLEL = SAFE +); + +CREATE OR REPLACE AGGREGATE __API_SCHEMA_INTERNAL_V2__.BSONMINN(__CORE_SCHEMA__.bson) +( + SFUNC = __API_SCHEMA_INTERNAL_V2__.bson_minn_transition, + FINALFUNC = __API_SCHEMA_INTERNAL_V2__.bson_maxminn_final, + stype = bytea, + COMBINEFUNC = __API_SCHEMA_INTERNAL_V2__.bson_maxminn_combine, + PARALLEL = SAFE +); + +CREATE OR REPLACE AGGREGATE __API_SCHEMA_INTERNAL_V2__.BSONFIRSTONSORTED(__CORE_SCHEMA__.bson, __CORE_SCHEMA__.bson) +( + SFUNC = __API_SCHEMA_INTERNAL_V2__.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 __API_SCHEMA_INTERNAL_V2__.BSONLASTONSORTED(__CORE_SCHEMA__.bson, __CORE_SCHEMA__.bson) +( + SFUNC = __API_SCHEMA_INTERNAL_V2__.bson_last_transition_on_sorted, + FINALFUNC = __API_CATALOG_SCHEMA__.bson_first_last_final_on_sorted, + stype = bytea, + PARALLEL = SAFE +); + +CREATE OR REPLACE AGGREGATE __API_SCHEMA_INTERNAL_V2__.BSONFIRSTNONSORTED(__CORE_SCHEMA__.bson, bigint, __CORE_SCHEMA__.bson) +( + SFUNC = __API_SCHEMA_INTERNAL_V2__.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 __API_SCHEMA_INTERNAL_V2__.BSONLASTNONSORTED(__CORE_SCHEMA__.bson, bigint, __CORE_SCHEMA__.bson) +( + SFUNC = __API_SCHEMA_INTERNAL_V2__.bson_lastn_transition_on_sorted, + FINALFUNC = __API_CATALOG_SCHEMA__.bson_firstn_lastn_final_on_sorted, + stype = bytea, + PARALLEL = SAFE +); + +CREATE OR REPLACE AGGREGATE __API_SCHEMA_INTERNAL_V2__.BSONPERCENTILE(__CORE_SCHEMA__.bson, int4, __CORE_SCHEMA__.bson) +( + SFUNC = __API_SCHEMA_INTERNAL_V2__.tdigest_add_double_array, + stype = internal, + FINALFUNC = __API_SCHEMA_INTERNAL_V2__.tdigest_array_percentiles, + SERIALFUNC = __API_SCHEMA_INTERNAL_V2__.tdigest_serial, + DESERIALFUNC = __API_SCHEMA_INTERNAL_V2__.tdigest_deserial, + COMBINEFUNC = __API_SCHEMA_INTERNAL_V2__.tdigest_combine, + PARALLEL = SAFE +); + +CREATE OR REPLACE AGGREGATE __API_SCHEMA_INTERNAL_V2__.BSONMEDIAN(__CORE_SCHEMA__.bson, int4, __CORE_SCHEMA__.bson) +( + SFUNC = __API_SCHEMA_INTERNAL_V2__.tdigest_add_double, + stype = internal, + FINALFUNC = __API_SCHEMA_INTERNAL_V2__.tdigest_percentile, + SERIALFUNC = __API_SCHEMA_INTERNAL_V2__.tdigest_serial, + DESERIALFUNC = __API_SCHEMA_INTERNAL_V2__.tdigest_deserial, + COMBINEFUNC = __API_SCHEMA_INTERNAL_V2__.tdigest_combine, + PARALLEL = SAFE +); \ No newline at end of file diff --git a/pg_documentdb/sql/udfs/aggregation/group_aggregates--latest.sql b/pg_documentdb/sql/udfs/aggregation/group_aggregates--latest.sql index f3fcc7aa..407bced7 100644 --- a/pg_documentdb/sql/udfs/aggregation/group_aggregates--latest.sql +++ b/pg_documentdb/sql/udfs/aggregation/group_aggregates--latest.sql @@ -379,4 +379,26 @@ CREATE OR REPLACE AGGREGATE __API_SCHEMA_INTERNAL_V2__.BSONLASTNONSORTED(__CORE_ FINALFUNC = __API_CATALOG_SCHEMA__.bson_firstn_lastn_final_on_sorted, stype = bytea, PARALLEL = SAFE +); + +CREATE OR REPLACE AGGREGATE __API_SCHEMA_INTERNAL_V2__.BSONPERCENTILE(__CORE_SCHEMA__.bson, int4, __CORE_SCHEMA__.bson) +( + SFUNC = __API_SCHEMA_INTERNAL_V2__.tdigest_add_double_array, + stype = internal, + FINALFUNC = __API_SCHEMA_INTERNAL_V2__.tdigest_array_percentiles, + SERIALFUNC = __API_SCHEMA_INTERNAL_V2__.tdigest_serial, + DESERIALFUNC = __API_SCHEMA_INTERNAL_V2__.tdigest_deserial, + COMBINEFUNC = __API_SCHEMA_INTERNAL_V2__.tdigest_combine, + PARALLEL = SAFE +); + +CREATE OR REPLACE AGGREGATE __API_SCHEMA_INTERNAL_V2__.BSONMEDIAN(__CORE_SCHEMA__.bson, int4, __CORE_SCHEMA__.bson) +( + SFUNC = __API_SCHEMA_INTERNAL_V2__.tdigest_add_double, + stype = internal, + FINALFUNC = __API_SCHEMA_INTERNAL_V2__.tdigest_percentile, + SERIALFUNC = __API_SCHEMA_INTERNAL_V2__.tdigest_serial, + DESERIALFUNC = __API_SCHEMA_INTERNAL_V2__.tdigest_deserial, + COMBINEFUNC = __API_SCHEMA_INTERNAL_V2__.tdigest_combine, + PARALLEL = SAFE ); \ No newline at end of file diff --git a/pg_documentdb/sql/udfs/aggregation/group_aggregates_support--0.24-0.sql b/pg_documentdb/sql/udfs/aggregation/group_aggregates_support--0.24-0.sql new file mode 100644 index 00000000..2cc950f0 --- /dev/null +++ b/pg_documentdb/sql/udfs/aggregation/group_aggregates_support--0.24-0.sql @@ -0,0 +1,369 @@ + +CREATE OR REPLACE FUNCTION __API_CATALOG_SCHEMA__.bson_sum_avg_transition(bytea, __CORE_SCHEMA__.bson) + RETURNS bytea + LANGUAGE c + STABLE +AS 'MODULE_PATHNAME', $function$bson_sum_avg_transition$function$; + +CREATE OR REPLACE FUNCTION __API_CATALOG_SCHEMA__.bson_sum_avg_combine(bytea, bytea) + RETURNS bytea + LANGUAGE c + STABLE +AS 'MODULE_PATHNAME', $function$bson_sum_avg_combine$function$; + +CREATE OR REPLACE FUNCTION __API_CATALOG_SCHEMA__.bson_sum_final(bytea) + RETURNS __CORE_SCHEMA__.bson + LANGUAGE c + STABLE +AS 'MODULE_PATHNAME', $function$bson_sum_final$function$; + +CREATE OR REPLACE FUNCTION __API_CATALOG_SCHEMA__.bson_avg_final(bytea) + RETURNS __CORE_SCHEMA__.bson + LANGUAGE c + STABLE +AS 'MODULE_PATHNAME', $function$bson_avg_final$function$; + +CREATE OR REPLACE FUNCTION __API_CATALOG_SCHEMA__.bson_min_max_final(__CORE_SCHEMA__.bson) + RETURNS __CORE_SCHEMA__.bson + LANGUAGE c + STABLE +AS 'MODULE_PATHNAME', $function$bson_min_max_final$function$; + +CREATE OR REPLACE FUNCTION __API_CATALOG_SCHEMA__.bson_max_transition(__CORE_SCHEMA__.bson, __CORE_SCHEMA__.bson) + RETURNS __CORE_SCHEMA__.bson + LANGUAGE c + STABLE +AS 'MODULE_PATHNAME', $function$bson_max_transition$function$; + +CREATE OR REPLACE FUNCTION __API_CATALOG_SCHEMA__.bson_min_transition(__CORE_SCHEMA__.bson, __CORE_SCHEMA__.bson) + RETURNS __CORE_SCHEMA__.bson + LANGUAGE c + STABLE +AS 'MODULE_PATHNAME', $function$bson_min_transition$function$; + +CREATE OR REPLACE FUNCTION __API_CATALOG_SCHEMA__.bson_min_combine(__CORE_SCHEMA__.bson, __CORE_SCHEMA__.bson) + RETURNS __CORE_SCHEMA__.bson + LANGUAGE c + STABLE +AS 'MODULE_PATHNAME', $function$bson_min_combine$function$; + +CREATE OR REPLACE FUNCTION __API_CATALOG_SCHEMA__.bson_max_combine(__CORE_SCHEMA__.bson, __CORE_SCHEMA__.bson) + RETURNS __CORE_SCHEMA__.bson + LANGUAGE c + STABLE +AS 'MODULE_PATHNAME', $function$bson_max_combine$function$; + +CREATE OR REPLACE FUNCTION __API_CATALOG_SCHEMA__.bson_first_transition(bytea, __CORE_SCHEMA__.bson, __CORE_SCHEMA__.bson[]) + RETURNS bytea + LANGUAGE c + STABLE +AS 'MODULE_PATHNAME', $function$bson_first_transition$function$; + +CREATE OR REPLACE FUNCTION __API_CATALOG_SCHEMA__.bson_last_transition(bytea, __CORE_SCHEMA__.bson, __CORE_SCHEMA__.bson[]) + RETURNS bytea + LANGUAGE c + STABLE +AS 'MODULE_PATHNAME', $function$bson_last_transition$function$; + +CREATE OR REPLACE FUNCTION __API_CATALOG_SCHEMA__.bson_first_transition_on_sorted(bytea, __CORE_SCHEMA__.bson) + RETURNS bytea + LANGUAGE c + STABLE +AS 'MODULE_PATHNAME', $function$bson_first_transition_on_sorted$function$; + +CREATE OR REPLACE FUNCTION __API_CATALOG_SCHEMA__.bson_last_transition_on_sorted(bytea, __CORE_SCHEMA__.bson) + RETURNS bytea + LANGUAGE c + STABLE +AS 'MODULE_PATHNAME', $function$bson_last_transition_on_sorted$function$; + +CREATE OR REPLACE FUNCTION __API_CATALOG_SCHEMA__.bson_first_last_final_on_sorted(bytea) + RETURNS __CORE_SCHEMA__.bson + LANGUAGE c + STABLE +AS 'MODULE_PATHNAME', $function$bson_first_last_final_on_sorted$function$; + +CREATE OR REPLACE FUNCTION __API_CATALOG_SCHEMA__.bson_first_combine(bytea, bytea) + RETURNS bytea + LANGUAGE c + STABLE STRICT +AS 'MODULE_PATHNAME', $function$bson_first_combine$function$; + +CREATE OR REPLACE FUNCTION __API_CATALOG_SCHEMA__.bson_last_combine(bytea, bytea) + RETURNS bytea + LANGUAGE c + STABLE STRICT +AS 'MODULE_PATHNAME', $function$bson_last_combine$function$; + +CREATE OR REPLACE FUNCTION __API_CATALOG_SCHEMA__.bson_first_last_final(bytea) + RETURNS __CORE_SCHEMA__.bson + LANGUAGE c + STABLE +AS 'MODULE_PATHNAME', $function$bson_first_last_final$function$; + +/* + * TODO: Replace this in favor of the new approach below. + */ +CREATE OR REPLACE FUNCTION __API_CATALOG_SCHEMA__.bson_array_agg_transition(bytea, __CORE_SCHEMA__.bson, text) + RETURNS bytea + LANGUAGE c + STABLE +AS 'MODULE_PATHNAME', $function$bson_array_agg_transition$function$; + +CREATE OR REPLACE FUNCTION __API_CATALOG_SCHEMA__.bson_array_agg_transition(bytea, __CORE_SCHEMA__.bson, text, boolean) + RETURNS bytea + LANGUAGE c + STABLE +AS 'MODULE_PATHNAME', $function$bson_array_agg_transition$function$; + +CREATE OR REPLACE FUNCTION __API_CATALOG_SCHEMA__.bson_array_agg_final(bytea) + RETURNS __CORE_SCHEMA__.bson + LANGUAGE c + STABLE +AS 'MODULE_PATHNAME', $function$bson_array_agg_final$function$; + +CREATE OR REPLACE FUNCTION __API_CATALOG_SCHEMA__.bson_object_agg_transition(bytea, __CORE_SCHEMA__.bson) + RETURNS bytea + LANGUAGE c + STABLE +AS 'MODULE_PATHNAME', $function$bson_object_agg_transition$function$; + +CREATE OR REPLACE FUNCTION __API_CATALOG_SCHEMA__.bson_object_agg_final(bytea) + RETURNS __CORE_SCHEMA__.bson + LANGUAGE c + STABLE +AS 'MODULE_PATHNAME', $function$bson_object_agg_final$function$; + +CREATE OR REPLACE FUNCTION __API_CATALOG_SCHEMA__.bson_out_transition(bytea, __CORE_SCHEMA__.bson, text, text, text, text) + RETURNS bytea + LANGUAGE c + VOLATILE +AS 'MODULE_PATHNAME', $function$bson_out_transition$function$; + +CREATE OR REPLACE FUNCTION __API_CATALOG_SCHEMA__.bson_out_final(bytea) + RETURNS __CORE_SCHEMA__.bson + LANGUAGE c + VOLATILE +AS 'MODULE_PATHNAME', $function$bson_out_final$function$; + +CREATE OR REPLACE FUNCTION __API_CATALOG_SCHEMA__.bson_firstn_transition(bytea, __CORE_SCHEMA__.bson, bigint, __CORE_SCHEMA__.bson[]) + RETURNS bytea + LANGUAGE c + STABLE +AS 'MODULE_PATHNAME', $function$bson_firstn_transition$function$; + +CREATE OR REPLACE FUNCTION __API_CATALOG_SCHEMA__.bson_lastn_transition(bytea, __CORE_SCHEMA__.bson, bigint, __CORE_SCHEMA__.bson[]) + RETURNS bytea + LANGUAGE c + STABLE +AS 'MODULE_PATHNAME', $function$bson_lastn_transition$function$; + +CREATE OR REPLACE FUNCTION __API_CATALOG_SCHEMA__.bson_firstn_combine(bytea, bytea) + RETURNS bytea + LANGUAGE c + STABLE +AS 'MODULE_PATHNAME', $function$bson_firstn_combine$function$; + +CREATE OR REPLACE FUNCTION __API_CATALOG_SCHEMA__.bson_lastn_combine(bytea, bytea) + RETURNS bytea + LANGUAGE c + STABLE +AS 'MODULE_PATHNAME', $function$bson_lastn_combine$function$; + +CREATE OR REPLACE FUNCTION __API_CATALOG_SCHEMA__.bson_firstn_lastn_final(bytea) + RETURNS __CORE_SCHEMA__.bson + LANGUAGE c + STABLE +AS 'MODULE_PATHNAME', $function$bson_firstn_lastn_final$function$; + +CREATE OR REPLACE FUNCTION __API_CATALOG_SCHEMA__.bson_firstn_transition_on_sorted(bytea, __CORE_SCHEMA__.bson, bigint) + RETURNS bytea + LANGUAGE c + STABLE +AS 'MODULE_PATHNAME', $function$bson_firstn_transition_on_sorted$function$; + +CREATE OR REPLACE FUNCTION __API_CATALOG_SCHEMA__.bson_lastn_transition_on_sorted(bytea, __CORE_SCHEMA__.bson, bigint) + RETURNS bytea + LANGUAGE c + STABLE +AS 'MODULE_PATHNAME', $function$bson_lastn_transition_on_sorted$function$; + +CREATE OR REPLACE FUNCTION __API_CATALOG_SCHEMA__.bson_firstn_lastn_final_on_sorted(bytea) + RETURNS __CORE_SCHEMA__.bson + LANGUAGE c + STABLE +AS 'MODULE_PATHNAME', $function$bson_firstn_lastn_final_on_sorted$function$; + +CREATE OR REPLACE FUNCTION __API_SCHEMA_INTERNAL_V2__.bson_add_to_set_transition(bytea, __CORE_SCHEMA_V2__.bson) + RETURNS bytea + LANGUAGE c + STABLE +AS 'MODULE_PATHNAME', $function$bson_add_to_set_transition$function$; + +CREATE OR REPLACE FUNCTION __API_SCHEMA_INTERNAL_V2__.bson_add_to_set_final(bytea) + RETURNS __CORE_SCHEMA_V2__.bson + LANGUAGE c + STABLE +AS 'MODULE_PATHNAME', $function$bson_add_to_set_final$function$; + +CREATE OR REPLACE FUNCTION __API_SCHEMA_INTERNAL_V2__.bson_merge_objects_transition_on_sorted(bytea, __CORE_SCHEMA_V2__.bson) + RETURNS bytea + LANGUAGE c + STABLE +AS 'MODULE_PATHNAME', $function$bson_merge_objects_transition_on_sorted$function$; + +/* + * This can't use __CORE_SCHEMA_V2__.bson due to citus type checks. We can migrate once the underlying tuples use the new types. + */ +CREATE OR REPLACE FUNCTION __API_SCHEMA_INTERNAL_V2__.bson_merge_objects_transition(bytea, __CORE_SCHEMA__.bson, bigint, __CORE_SCHEMA__.bson[], __CORE_SCHEMA__.bson) + RETURNS bytea + LANGUAGE c + STABLE +AS 'MODULE_PATHNAME', $function$bson_merge_objects_transition$function$; + +/* + * This can't use __CORE_SCHEMA_V2__.bson due to citus type checks. We can migrate once the underlying tuples use the new types. + */ +CREATE OR REPLACE FUNCTION __API_SCHEMA_INTERNAL_V2__.bson_merge_objects_final(bytea) + RETURNS __CORE_SCHEMA__.bson + LANGUAGE c + STABLE +AS 'MODULE_PATHNAME', $function$bson_merge_objects_final$function$; + +CREATE OR REPLACE FUNCTION __API_SCHEMA_INTERNAL_V2__.bson_std_dev_pop_samp_transition(bytea, __CORE_SCHEMA__.bson) + RETURNS bytea + LANGUAGE c + STABLE +AS 'MODULE_PATHNAME', $function$bson_std_dev_pop_samp_transition$function$; + +CREATE OR REPLACE FUNCTION __API_SCHEMA_INTERNAL_V2__.bson_std_dev_pop_samp_combine(bytea, bytea) + RETURNS bytea + LANGUAGE c + STABLE +AS 'MODULE_PATHNAME', $function$bson_std_dev_pop_samp_combine$function$; + +CREATE OR REPLACE FUNCTION __API_SCHEMA_INTERNAL_V2__.bson_std_dev_pop_final(bytea) + RETURNS __CORE_SCHEMA__.bson + LANGUAGE c + STABLE +AS 'MODULE_PATHNAME', $function$bson_std_dev_pop_final$function$; + +CREATE OR REPLACE FUNCTION __API_SCHEMA_INTERNAL_V2__.bson_std_dev_samp_final(bytea) + RETURNS __CORE_SCHEMA__.bson + LANGUAGE c + STABLE +AS 'MODULE_PATHNAME', $function$bson_std_dev_samp_final$function$; + +CREATE OR REPLACE FUNCTION __API_SCHEMA_INTERNAL_V2__.bson_first_transition(bytea, __CORE_SCHEMA__.bson, __CORE_SCHEMA__.bson[], __CORE_SCHEMA__.bson DEFAULT NULL) + RETURNS bytea + LANGUAGE c + STABLE +AS 'MODULE_PATHNAME', $function$bson_first_transition$function$; + +CREATE OR REPLACE FUNCTION __API_SCHEMA_INTERNAL_V2__.bson_last_transition(bytea, __CORE_SCHEMA__.bson, __CORE_SCHEMA__.bson[], __CORE_SCHEMA__.bson DEFAULT NULL) + RETURNS bytea + LANGUAGE c + STABLE +AS 'MODULE_PATHNAME', $function$bson_last_transition$function$; + +CREATE OR REPLACE FUNCTION __API_SCHEMA_INTERNAL_V2__.bson_firstn_transition(bytea, __CORE_SCHEMA__.bson, bigint, __CORE_SCHEMA__.bson[], __CORE_SCHEMA__.bson DEFAULT NULL) + RETURNS bytea + LANGUAGE c + STABLE +AS 'MODULE_PATHNAME', $function$bson_firstn_transition$function$; + +CREATE OR REPLACE FUNCTION __API_SCHEMA_INTERNAL_V2__.bson_lastn_transition(bytea, __CORE_SCHEMA__.bson, bigint, __CORE_SCHEMA__.bson[], __CORE_SCHEMA__.bson DEFAULT NULL) + RETURNS bytea + LANGUAGE c + STABLE +AS 'MODULE_PATHNAME', $function$bson_lastn_transition$function$; + +CREATE OR REPLACE FUNCTION __API_SCHEMA_INTERNAL_V2__.bson_maxn_transition(bytea, __CORE_SCHEMA__.bson) + RETURNS bytea + LANGUAGE c + STABLE +AS 'MODULE_PATHNAME', $function$bson_maxn_transition$function$; + +CREATE OR REPLACE FUNCTION __API_SCHEMA_INTERNAL_V2__.bson_minn_transition(bytea, __CORE_SCHEMA__.bson) + RETURNS bytea + LANGUAGE c + STABLE +AS 'MODULE_PATHNAME', $function$bson_minn_transition$function$; + +CREATE OR REPLACE FUNCTION __API_SCHEMA_INTERNAL_V2__.bson_maxminn_final(bytea) + RETURNS __CORE_SCHEMA__.bson + LANGUAGE c + STABLE +AS 'MODULE_PATHNAME', $function$bson_maxminn_final$function$; + +CREATE OR REPLACE FUNCTION __API_SCHEMA_INTERNAL_V2__.bson_maxminn_combine(bytea, bytea) + RETURNS bytea + LANGUAGE c + STABLE +AS 'MODULE_PATHNAME', $function$bson_maxminn_combine$function$; + +CREATE OR REPLACE FUNCTION __API_SCHEMA_INTERNAL_V2__.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 __API_SCHEMA_INTERNAL_V2__.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 __API_SCHEMA_INTERNAL_V2__.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 __API_SCHEMA_INTERNAL_V2__.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$; + +CREATE OR REPLACE FUNCTION __API_SCHEMA_INTERNAL_V2__.tdigest_add_double(internal, __CORE_SCHEMA__.bson, int4, __CORE_SCHEMA__.bson) + RETURNS internal + LANGUAGE c + IMMUTABLE +AS 'MODULE_PATHNAME', $function$tdigest_add_double$function$; + +CREATE OR REPLACE FUNCTION __API_SCHEMA_INTERNAL_V2__.tdigest_add_double_array(internal, __CORE_SCHEMA__.bson, int4, __CORE_SCHEMA__.bson) + RETURNS internal + LANGUAGE c + IMMUTABLE +AS 'MODULE_PATHNAME', $function$tdigest_add_double_array$function$; + +CREATE OR REPLACE FUNCTION __API_SCHEMA_INTERNAL_V2__.tdigest_percentile(internal) + RETURNS __CORE_SCHEMA__.bson + LANGUAGE c + IMMUTABLE +AS 'MODULE_PATHNAME', $function$tdigest_percentile$function$; + +CREATE OR REPLACE FUNCTION __API_SCHEMA_INTERNAL_V2__.tdigest_array_percentiles(internal) + RETURNS __CORE_SCHEMA__.bson + LANGUAGE c + IMMUTABLE +AS 'MODULE_PATHNAME', $function$tdigest_array_percentiles$function$; + +CREATE OR REPLACE FUNCTION __API_SCHEMA_INTERNAL_V2__.tdigest_combine(internal, internal) + RETURNS internal + LANGUAGE c + IMMUTABLE +AS 'MODULE_PATHNAME', $function$tdigest_combine$function$; + +CREATE OR REPLACE FUNCTION __API_SCHEMA_INTERNAL_V2__.tdigest_serial(internal) + RETURNS bytea + LANGUAGE c + IMMUTABLE STRICT +AS 'MODULE_PATHNAME', $function$tdigest_serial$function$; + +CREATE OR REPLACE FUNCTION __API_SCHEMA_INTERNAL_V2__.tdigest_deserial(bytea, internal) + RETURNS internal + LANGUAGE c + IMMUTABLE STRICT +AS 'MODULE_PATHNAME', $function$tdigest_deserial$function$; \ No newline at end of file diff --git a/pg_documentdb/sql/udfs/aggregation/group_aggregates_support--latest.sql b/pg_documentdb/sql/udfs/aggregation/group_aggregates_support--latest.sql index 00f34268..2cc950f0 100644 --- a/pg_documentdb/sql/udfs/aggregation/group_aggregates_support--latest.sql +++ b/pg_documentdb/sql/udfs/aggregation/group_aggregates_support--latest.sql @@ -324,4 +324,46 @@ CREATE OR REPLACE FUNCTION __API_SCHEMA_INTERNAL_V2__.bson_lastn_transition_on_s RETURNS bytea LANGUAGE c STABLE -AS 'MODULE_PATHNAME', $function$bson_lastn_transition_on_sorted$function$; \ No newline at end of file +AS 'MODULE_PATHNAME', $function$bson_lastn_transition_on_sorted$function$; + +CREATE OR REPLACE FUNCTION __API_SCHEMA_INTERNAL_V2__.tdigest_add_double(internal, __CORE_SCHEMA__.bson, int4, __CORE_SCHEMA__.bson) + RETURNS internal + LANGUAGE c + IMMUTABLE +AS 'MODULE_PATHNAME', $function$tdigest_add_double$function$; + +CREATE OR REPLACE FUNCTION __API_SCHEMA_INTERNAL_V2__.tdigest_add_double_array(internal, __CORE_SCHEMA__.bson, int4, __CORE_SCHEMA__.bson) + RETURNS internal + LANGUAGE c + IMMUTABLE +AS 'MODULE_PATHNAME', $function$tdigest_add_double_array$function$; + +CREATE OR REPLACE FUNCTION __API_SCHEMA_INTERNAL_V2__.tdigest_percentile(internal) + RETURNS __CORE_SCHEMA__.bson + LANGUAGE c + IMMUTABLE +AS 'MODULE_PATHNAME', $function$tdigest_percentile$function$; + +CREATE OR REPLACE FUNCTION __API_SCHEMA_INTERNAL_V2__.tdigest_array_percentiles(internal) + RETURNS __CORE_SCHEMA__.bson + LANGUAGE c + IMMUTABLE +AS 'MODULE_PATHNAME', $function$tdigest_array_percentiles$function$; + +CREATE OR REPLACE FUNCTION __API_SCHEMA_INTERNAL_V2__.tdigest_combine(internal, internal) + RETURNS internal + LANGUAGE c + IMMUTABLE +AS 'MODULE_PATHNAME', $function$tdigest_combine$function$; + +CREATE OR REPLACE FUNCTION __API_SCHEMA_INTERNAL_V2__.tdigest_serial(internal) + RETURNS bytea + LANGUAGE c + IMMUTABLE STRICT +AS 'MODULE_PATHNAME', $function$tdigest_serial$function$; + +CREATE OR REPLACE FUNCTION __API_SCHEMA_INTERNAL_V2__.tdigest_deserial(bytea, internal) + RETURNS internal + LANGUAGE c + IMMUTABLE STRICT +AS 'MODULE_PATHNAME', $function$tdigest_deserial$function$; \ No newline at end of file diff --git a/pg_documentdb/src/aggregation/bson_aggregation_pipeline.c b/pg_documentdb/src/aggregation/bson_aggregation_pipeline.c index ee55f65c..8d041f9f 100644 --- a/pg_documentdb/src/aggregation/bson_aggregation_pipeline.c +++ b/pg_documentdb/src/aggregation/bson_aggregation_pipeline.c @@ -79,6 +79,9 @@ extern bool EnableCollation; extern bool EnableFastPathPointLookupPlanner; extern bool DefaultInlineWriteOperations; +/* GUC to config tdigest compression */ +extern int TdigestCompressionAccuracy; + /* * The mutation function that modifies a given query with a pipeline stage's value. */ @@ -1267,8 +1270,13 @@ GenerateAggregationQuery(Datum database, pgbson *aggregationSpec, QueryData *que } else if (StringViewEqualsCString(&keyView, "let")) { - EnsureTopLevelFieldType("let", &aggregationIterator, BSON_TYPE_DOCUMENT); - let = *value; + bool hasValue = EnsureTopLevelFieldTypeNullOkUndefinedOK("let", + &aggregationIterator, + BSON_TYPE_DOCUMENT); + if (hasValue) + { + let = *value; + } } else if (StringViewEqualsCString(&keyView, "collectionUUID")) { @@ -2388,6 +2396,94 @@ ParseInputDocumentForTopAndBottom(const bson_value_t *inputDocument, bson_value_ } +/** + * Parses the input document for $median and $percentile accumulator operator, extracts input, p and methods. + * @param inputDocument: input document for the operator + * @param input: this is a pointer which after parsing will hold input expression + * @param p: this is a pointer which after parsing will hold the p, i.e. the percentile array value + * @param method: this is a pointer which after parsing will hold method + * @param isMedianOp: this contains the name of the operator for error msg formatting purposes. This value is supposed to be $firstN/$lastN. + */ +void +ParseInputDocumentForMedianAndPercentile(const bson_value_t *inputDocument, + bson_value_t *input, + bson_value_t *p, bson_value_t *method, + bool isMedianOp) +{ + const char *opName = isMedianOp ? "$median" : "$percentile"; + if (inputDocument->value_type != BSON_TYPE_DOCUMENT) + { + int errorcode = isMedianOp ? ERRCODE_DOCUMENTDB_LOCATION7436100 : + ERRCODE_DOCUMENTDB_LOCATION7429703; + ereport(ERROR, (errcode(errorcode), + errmsg("specification must be an object; found %s type: %s", + opName, BsonTypeName(inputDocument->value_type)), + errdetail_log( + "%s specification must be an object", opName))); + } + 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, "method") == 0) + { + *method = *bson_iter_value(&docIter); + } + /* only evaluate p for $percentile */ + else if (!isMedianOp && strcmp(key, "p") == 0) + { + *p = *bson_iter_value(&docIter); + } + else + { + ereport(ERROR, (errcode(ERRCODE_DOCUMENTDB_UNKNOWNBSONFIELD), errmsg( + "BSON field '$%s.%s' is an unknown field.", opName, key), + errdetail_log("%s found an unknown argument", opName))); + } + } + + /* check required fields are present */ + char *keyName; + if (((input->value_type == BSON_TYPE_EOD) && (keyName = "input")) || + (!isMedianOp && (p->value_type == BSON_TYPE_EOD) && (keyName = "p")) || + ((method->value_type == BSON_TYPE_EOD) && (keyName = "method"))) + { + ereport(ERROR, (errcode(ERRCODE_DOCUMENTDB_LOCATION40414), errmsg( + "BSON field '$%s.%s' is missing but is a required field", + opName, keyName))); + } + + /* validate method: can only be 'approximate' for now */ + if (method->value_type != BSON_TYPE_UTF8) + { + ereport(ERROR, (errcode(ERRCODE_DOCUMENTDB_TYPEMISMATCH), errmsg( + "BSON field '$%s.method' is the wrong type %s, expected type 'string'", + opName, BsonTypeName(method->value_type)), + errdetail_log( + "BSON field '$%s.method' expects type 'string'", opName))); + } + if (strcmp(method->value.v_utf8.str, "approximate") != 0) + { + /* Same error message for both $median and $percentile */ + ereport(ERROR, (errcode(ERRCODE_DOCUMENTDB_BADVALUE), errmsg( + "Currently only 'approximate' can be used as percentile 'method'"))); + } + + /* set p for $median to 0.5 */ + if (isMedianOp) + { + p->value_type = BSON_TYPE_DOUBLE; + p->value.v_double = 0.5; + } +} + + /** * 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 */ @@ -4931,6 +5027,92 @@ AddMaxMinNGroupAccumulator(Query *query, const bson_value_t *accumulatorValue, } +/* + * Function used to support percentile/median accumulator. + */ +inline static List * +AddPercentileMedianGroupAccumulator(Query *query, const bson_value_t *accumulatorValue, + List *repathArgs, Const *accumulatorText, + ParseState *parseState, char *identifiers, + Expr *documentExpr, StringView *accumulatorName, + Expr *variableSpec, bool isMedianOp) +{ + bson_value_t input = { 0 }; + bson_value_t p = { 0 }; + bson_value_t method = { 0 }; + + ParseInputDocumentForMedianAndPercentile(accumulatorValue, &input, &p, &method, + isMedianOp); + + /* construct expression to get input and p */ + List *inputFuncArgs; + List *pFuncArgs; + Oid bsonExpressionGetFunction; + + Expr *inputConstValue = (Expr *) MakeBsonConst(BsonValueToDocumentPgbson(&input)); + Const *accuracyConstValue = makeConst(INT4OID, -1, InvalidOid, sizeof(int32_t), + Int32GetDatum(TdigestCompressionAccuracy), + false, true); + Expr *pConstValue = (Expr *) MakeBsonConst(BsonValueToDocumentPgbson(&p)); + Const *trueConst = makeConst(BOOLOID, -1, InvalidOid, 1, BoolGetDatum(true), false, + true); + if (variableSpec != NULL) + { + bsonExpressionGetFunction = BsonExpressionGetWithLetFunctionOid(); + inputFuncArgs = list_make4(documentExpr, inputConstValue, trueConst, + variableSpec); + pFuncArgs = list_make4(documentExpr, pConstValue, trueConst, variableSpec); + } + else + { + bsonExpressionGetFunction = BsonExpressionGetFunctionOid(); + inputFuncArgs = list_make3(documentExpr, inputConstValue, trueConst); + pFuncArgs = list_make3(documentExpr, pConstValue, trueConst); + } + + FuncExpr *inputAccumFunc = makeFuncExpr(bsonExpressionGetFunction, BsonTypeId(), + inputFuncArgs, InvalidOid, + InvalidOid, COERCE_EXPLICIT_CALL); + FuncExpr *pAccumFunc = makeFuncExpr(bsonExpressionGetFunction, BsonTypeId(), + pFuncArgs, InvalidOid, + InvalidOid, COERCE_EXPLICIT_CALL); + + if (EnableLetSupport && BsonTypeId() != DocumentDBCoreBsonTypeId() && + IsClusterVersionAtleast(DocDB_V0, 24, 0)) + { + inputAccumFunc = makeFuncExpr( + DocumentDBCoreBsonToBsonFunctionOId(), BsonTypeId(), list_make1( + inputAccumFunc), + InvalidOid, + InvalidOid, COERCE_EXPLICIT_CALL); + pAccumFunc = makeFuncExpr( + DocumentDBCoreBsonToBsonFunctionOId(), BsonTypeId(), list_make1(pAccumFunc), + InvalidOid, + InvalidOid, COERCE_EXPLICIT_CALL); + } + + Oid aggregateFunctionOid = isMedianOp ? BsonMedianAggregateFunctionOid() : + BsonPercentileAggregateFunctionOid(); + Aggref *aggref = CreateMultiArgAggregate(aggregateFunctionOid, list_make3( + (Expr *) inputAccumFunc, + accuracyConstValue, (Expr *) pAccumFunc), + list_make3_oid( + BsonTypeId(), + accuracyConstValue->consttype, + BsonTypeId()), parseState); + + repathArgs = lappend(repathArgs, AddGroupExpression((Expr *) accumulatorText, + parseState, identifiers, query, + TEXTOID, NULL)); + + repathArgs = lappend(repathArgs, AddGroupExpression((Expr *) aggref, parseState, + identifiers, query, BsonTypeId(), + NULL)); + + return repathArgs; +} + + /* * Handles the $group stage. * Creates a subquery. @@ -5497,6 +5679,40 @@ HandleGroup(const bson_value_t *existingValue, Query *query, &accumulatorName, context->variableSpec); } + else if (StringViewEqualsCString(&accumulatorName, "$median")) + { + if (!(IsClusterVersionAtleast(DocDB_V0, 24, 0))) + { + ereport(ERROR, (errcode(ERRCODE_DOCUMENTDB_COMMANDNOTSUPPORTED), + errmsg("Accumulator $median is not supported yet"))); + } + repathArgs = AddPercentileMedianGroupAccumulator(query, + &accumulatorElement.bsonValue, + repathArgs, + accumulatorText, parseState, + identifiers, + origEntry->expr, + &accumulatorName, + context->variableSpec, true); + } + else if (StringViewEqualsCString(&accumulatorName, "$percentile")) + { + if (!(IsClusterVersionAtleast(DocDB_V0, 24, 0))) + { + ereport(ERROR, (errcode(ERRCODE_DOCUMENTDB_COMMANDNOTSUPPORTED), + errmsg( + "Accumulator $percentile is not supported yet"))); + } + repathArgs = AddPercentileMedianGroupAccumulator(query, + &accumulatorElement.bsonValue, + repathArgs, + accumulatorText, parseState, + identifiers, + origEntry->expr, + &accumulatorName, + context->variableSpec, + false); + } else { ereport(ERROR, (errcode(ERRCODE_DOCUMENTDB_LOCATION15952), diff --git a/pg_documentdb/src/aggregation/bson_tdigest.c b/pg_documentdb/src/aggregation/bson_tdigest.c new file mode 100644 index 00000000..a0b4bb41 --- /dev/null +++ b/pg_documentdb/src/aggregation/bson_tdigest.c @@ -0,0 +1,1240 @@ +/*------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * + * src/aggregation/tdigest_utils.c + * + * Helper functions to implement t-digest. + * + * + * This code contains modifications from the t-digest implementation by Tomas Vondra + * (Copyright (C) Tomas Vondra, 2019) + * The original code can be found at: https://github.com/tvondra/tdigest + *------------------------------------------------------------------------- + */ + + +#include +#include +#include +#include +#include +#include + +#include "utils/documentdb_errors.h" +#include "io/bson_core.h" + +/* + * A centroid, used both for in-memory and on-disk storage. + */ +typedef struct centroid_t +{ + double mean; + int64 count; +} centroid_t; + +/* + * On-disk representation of the t-digest. + */ +typedef struct tdigest_t +{ + int32 vl_len_; /* varlena header (do not touch directly!) */ + int32 flags; /* reserved for future use (versioning, ...) */ + int64 count; /* number of items added to the t-digest */ + int compression; /* compression used to build the digest */ + int ncentroids; /* number of cetroids in the array */ + centroid_t centroids[FLEXIBLE_ARRAY_MEMBER]; +} tdigest_t; + +/* + * Centroids used to store (sum,count), but we want to store (mean,count) + * because that allows us to prevent rounding errors e.g. when merging + * centroids with the same mean, or adding the same value to the centroid. + * + * To handle existing tdigest data in backwards-compatible way, we have + * a flag marking the new ones with mean, and we convert the old values. + */ +#define TDIGEST_STORES_MEAN 0x0001 + +/* + * An aggregate state, representing the t-digest and some additional info + * (requested percentiles, ...). + * + * When adding new values to the t-digest, we add them as centroids into a + * separate "uncompacted" part of the array. While centroids need more space + * than plain points (24B vs. 8B), making the aggregate state quite a bit + * larger, it does simplify the code quite a bit as it only needs to deal + * with single struct type instead of two (centroids + points). But maybe + * we should separate those two things in the future. + * + * XXX We only ever use one of values/percentiles, never both at the same + * time. In the future the values may use a different data types than double + * (e.g. numeric), so we keep both fields. + */ +typedef struct tdigest_aggstate_t +{ + /* basic t-digest fields (centroids at the end) */ + int64 count; /* number of samples in the digest */ + int ncompactions; /* number of merges/compactions */ + int compression; /* compression algorithm */ + int ncentroids; /* number of centroids */ + int ncompacted; /* compacted part */ + /* array of requested percentiles and values */ + int npercentiles; /* number of percentiles */ + int nvalues; /* number of values */ + double trim_low; /* low threshold (for trimmed aggs) */ + double trim_high; /* high threshold (for trimmed aggs) */ + double *percentiles; /* array of percentiles (if any) */ + double *values; /* array of values (if any) */ + centroid_t *centroids; /* centroids for the digest */ +} tdigest_aggstate_t; + +static int centroid_cmp(const void *a, const void *b); + +#define PG_GETARG_TDIGEST(x) (tdigest_t *) PG_DETOAST_DATUM(PG_GETARG_DATUM(x)) + +/* + * Size of buffer for incoming data, as a multiple of the compression value. + * Quoting from the t-digest paper: + * + * The constant of proportionality should be determined by experiment, but + * micro-benchmarks indicate that C2/C1 is in the range from 5 to 20 for + * a single core of an Intel i7 processor. In these micro-benchmarks, + * increasing the buffer size to (10 * delta) dramatically improves the + * average speed but further buffer size increases have much less effect. + * + * XXX Maybe make the coefficient user-defined, with some reasonable limits + * (say 2 - 20), so that users can pick the right trade-off between speed + * and memory usage. + */ +#define BUFFER_SIZE(compression) (10 * (compression)) +#define AssertBounds(index, length) Assert((index) >= 0 && (index) < (length)) + +#define MIN_COMPRESSION 10 +#define MAX_COMPRESSION 10000 + + +/* prototypes */ +PG_FUNCTION_INFO_V1(tdigest_add_double); +PG_FUNCTION_INFO_V1(tdigest_add_double_array); +PG_FUNCTION_INFO_V1(tdigest_percentile); +PG_FUNCTION_INFO_V1(tdigest_array_percentiles); + +PG_FUNCTION_INFO_V1(tdigest_serial); +PG_FUNCTION_INFO_V1(tdigest_deserial); +PG_FUNCTION_INFO_V1(tdigest_combine); + +Datum tdigest_add_double(PG_FUNCTION_ARGS); +Datum tdigest_add_double_array(PG_FUNCTION_ARGS); +Datum tdigest_percentile(PG_FUNCTION_ARGS); +Datum tdigest_array_percentiles(PG_FUNCTION_ARGS); + +Datum tdigest_serial(PG_FUNCTION_ARGS); +Datum tdigest_deserial(PG_FUNCTION_ARGS); +Datum tdigest_combine(PG_FUNCTION_ARGS); + +static Datum double_array_to_bson_array(FunctionCallInfo fcinfo, double *darray, int len); +static double * bson_to_double_array(FunctionCallInfo fcinfo, bson_value_t *barray, + int *len); + + +static void +reverse_centroids(centroid_t *centroids, int ncentroids) +{ + int start = 0, + end = (ncentroids - 1); + + while (start < end) + { + centroid_t tmp = centroids[start]; + centroids[start] = centroids[end]; + centroids[end] = tmp; + + start++; + end--; + } +} + + +static void +rebalance_centroids(centroid_t *centroids, int ncentroids, + int64 weight_before, int64 weight_after) +{ + double ratio = weight_before / (double) weight_after; + int64 count_before = 0; + int64 count_after = 0; + int start = 0; + int end = (ncentroids - 1); + int i; + + centroid_t *scratch = palloc(sizeof(centroid_t) * ncentroids); + + i = 0; + while (i < ncentroids) + { + while (i < ncentroids) + { + scratch[start] = centroids[i]; + count_before += centroids[i].count; + i++; + start++; + + if (count_before > count_after * ratio) + { + break; + } + } + + while (i < ncentroids) + { + scratch[end] = centroids[i]; + count_after += centroids[i].count; + i++; + end--; + + if (count_before < count_after * ratio) + { + break; + } + } + } + + memcpy(centroids, scratch, sizeof(centroid_t) * ncentroids); + pfree(scratch); +} + + +/* + * Sort centroids in the digest. + * + * We have to sort the whole array, because we don't just simply sort the + * centroids - we do the rebalancing of items with the same mean too. + */ +static void +tdigest_sort(tdigest_aggstate_t *state) +{ + int i; + int64 count_so_far; + int64 next_group; + int64 median_count; + + /* do qsort on the non-sorted part */ + pg_qsort(state->centroids, + state->ncentroids, + sizeof(centroid_t), centroid_cmp); + + /* + * The centroids are sorted by (mean,count). That's fine for centroids up + * to median, but above median this ordering is incorrect for centroids + * with the same mean (or for groups crossing the median boundary). To fix + * this we 'rebalance' those groups. Those entirely above median can be + * simply sorted in the opposite order, while those crossing the median + * need to be rebalanced depending on what part is below/above median. + */ + count_so_far = 0; + next_group = 0; /* includes count_so_far */ + median_count = (state->count / 2); + + /* + * Split the centroids into groups with the same mean, process each group + * depending on whether it falls before/after median. + */ + i = 0; + while (i < state->ncentroids) + { + int j = i; + int group_size = 0; + + /* determine the end of the group */ + while ((j < state->ncentroids) && + (state->centroids[i].mean == state->centroids[j].mean)) + { + next_group += state->centroids[j].count; + group_size++; + j++; + } + + /* + * We can ignore groups of size 1 (number of centroids, not counts), as + * those are trivially sorted. + */ + if (group_size > 1) + { + if (count_so_far >= median_count) + { + /* group fully above median - reverse the order */ + reverse_centroids(&state->centroids[i], group_size); + } + else if (next_group >= median_count) /* group split by median */ + { + rebalance_centroids(&state->centroids[i], group_size, + median_count - count_so_far, + next_group - median_count); + } + } + + i = j; + count_so_far = next_group; + } +} + + +/* + * Perform compaction of the t-digest, i.e. merge the centroids as required + * by the compression parameter. + * + * We always keep the data sorted in ascending order. This way we can reuse + * the sort between compactions, and also when computing the quantiles. + * + * XXX Switch the direction regularly, to eliminate possible bias and improve + * accuracy, as mentioned in the paper. + * + * XXX This initially used the k1 scale function, but the implementation was + * not limiting the number of centroids for some reason (it might have been + * a bug in the implementation, of course). The current code is a modified + * copy from ajwerner [1], and AFAIK it's the k2 function, it's much simpler + * and generally works quite nicely. + * + * [1] https://github.com/ajwerner/tdigestc/blob/master/go/tdigest.c + */ +static void +tdigest_compact(tdigest_aggstate_t *state) +{ + int i; + + int cur; /* current centroid */ + int64 count_so_far; + int64 total_count; + double denom; + double normalizer; + int start; + int step; + int n; + + /* if the digest is fully compacted, it's been already compacted */ + if (state->ncompacted == state->ncentroids) + { + return; + } + + tdigest_sort(state); + + state->ncompactions++; + + if (state->ncompactions % 2 == 0) + { + start = 0; + step = 1; + } + else + { + start = state->ncentroids - 1; + step = -1; + } + + total_count = state->count; + denom = 2 * M_PI * total_count * log(total_count); + normalizer = state->compression / denom; + + cur = start; + count_so_far = 0; + n = 1; + + for (i = start + step; (i >= 0) && (i < state->ncentroids); i += step) + { + int64 proposed_count; + double q0; + double q2; + double z; + bool should_add; + + proposed_count = state->centroids[cur].count + state->centroids[i].count; + + z = proposed_count * normalizer; + q0 = count_so_far / (double) total_count; + q2 = (count_so_far + proposed_count) / (double) total_count; + + should_add = (z <= (q0 * (1 - q0))) && (z <= (q2 * (1 - q2))); + + if (should_add) + { + /* + * If both centroids have the same mean, don't calculate it again. + * The recaulculation may cause rounding errors, so that the means + * would drift apart over time. We want to keep them equal for as + * long as possible. + */ + if (state->centroids[cur].mean != state->centroids[i].mean) + { + double sum; + int64 count; + + sum = state->centroids[i].count * state->centroids[i].mean; + sum += state->centroids[cur].count * state->centroids[cur].mean; + + count = state->centroids[i].count; + count += state->centroids[cur].count; + + state->centroids[cur].mean = (sum / count); + } + + /* XXX Do this after possibly recalculating the mean. */ + state->centroids[cur].count += state->centroids[i].count; + } + else + { + count_so_far += state->centroids[cur].count; + cur += step; + n++; + state->centroids[cur] = state->centroids[i]; + } + + if (cur != i) + { + state->centroids[i].count = 0; + state->centroids[i].mean = 0; + } + } + + state->ncentroids = n; + state->ncompacted = state->ncentroids; + + if (step < 0) + { + memmove(state->centroids, &state->centroids[cur], n * sizeof(centroid_t)); + } + + Assert(state->ncentroids < BUFFER_SIZE(state->compression)); +} + + +/* + * Estimate requested quantiles from the t-digest agg state. + */ +static void +tdigest_compute_quantiles(tdigest_aggstate_t *state, double *result) +{ + int i, j; + + /* + * Trigger a compaction, which also sorts the data. + * + * XXX maybe just do a sort here, which should give us a bit more accurate + * results, probably. + */ + tdigest_compact(state); + + for (i = 0; i < state->npercentiles; i++) + { + double count; + double delta; + double goal = (state->percentiles[i] * state->count); + bool on_the_right; + centroid_t *prev, *next; + centroid_t *c = NULL; + double slope; + + /* first centroid for percentile 1.0 */ + if (state->percentiles[i] == 0.0) + { + c = &state->centroids[0]; + result[i] = c->mean; + continue; + } + + /* last centroid for percentile 1.0 */ + if (state->percentiles[i] == 1.0) + { + c = &state->centroids[state->ncentroids - 1]; + result[i] = c->mean; + continue; + } + + /* walk throught the centroids and count number of items */ + count = 0; + bool perfect_match = false; + for (j = 0; j < state->ncentroids; j++) + { + c = &state->centroids[j]; + + /* have we exceeded the expected count? */ + if (count + c->count > goal) + { + break; + } + else if (count + c->count == goal && c->count == 1) + { + result[i] = c->mean; + perfect_match = true; + break; + } + + /* account for the centroid */ + count += c->count; + } + + delta = goal - count - (c->count / 2.0); + + if (perfect_match) + { + continue; + } + + /* + * double arithmetics, so don't compare to 0.0 direcly, it's enough + * to be "close enough" + */ + if (fabs(delta) < 0.000000001) + { + result[i] = c->mean; + continue; + } + + on_the_right = (delta > 0.0); + + /* + * for extreme percentiles we might end on the right of the last node or on the + * left of the first node, instead of interpolating we return the mean of the node + */ + if ((on_the_right && (j + 1) >= state->ncentroids) || + (!on_the_right && (j - 1) < 0)) + { + result[i] = c->mean; + continue; + } + + if (on_the_right) + { + prev = &state->centroids[j]; + AssertBounds(j + 1, state->ncentroids); + next = &state->centroids[j + 1]; + count += (prev->count / 2.0); + } + else + { + AssertBounds(j - 1, state->ncentroids); + prev = &state->centroids[j - 1]; + next = &state->centroids[j]; + count -= (prev->count / 2.0); + } + + /* handle infinity and -infinity cases to prevent nan results */ + if (isinf(prev->mean) && isinf(next->mean)) + { + /* if both are infinity, return infinity depending on the goal is on the right or left */ + result[i] = (goal - count) > 0.5 ? next->mean : prev->mean; + continue; + } + else if (isinf(prev->mean)) + { + /* if prev is infinity, return infinity */ + result[i] = prev->mean; + continue; + } + else if (isinf(next->mean)) + { + /* if next is infinity, return infinity */ + result[i] = next->mean; + continue; + } + + slope = (next->mean - prev->mean) / (next->count / 2.0 + prev->count / 2.0); + + result[i] = prev->mean + slope * (goal - count); + } +} + + +/* add a value to the t-digest, trigger a compaction if full */ +static void +tdigest_add(tdigest_aggstate_t *state, double v) +{ + int compression = state->compression; + int ncentroids = state->ncentroids; + + /* make sure we have space for the value */ + Assert(state->ncentroids < BUFFER_SIZE(compression)); + + /* for a single point, the value is both sum and mean */ + state->centroids[ncentroids].count = 1; + state->centroids[ncentroids].mean = v; + state->ncentroids++; + state->count++; + + Assert(state->ncentroids <= BUFFER_SIZE(compression)); + + /* if the buffer got full, trigger compaction here so that next + * insert has free space */ + if (state->ncentroids == BUFFER_SIZE(compression)) + { + tdigest_compact(state); + } +} + + +/* + * allocate a tdigest aggregate state, along with space for percentile(s) + * and value(s) requested when calling the aggregate function + */ +static tdigest_aggstate_t * +tdigest_aggstate_allocate(int npercentiles, int nvalues, int compression) +{ + Size len; + tdigest_aggstate_t *state; + char *ptr; + + /* at least one of those values is 0 */ + Assert(nvalues == 0 || npercentiles == 0); + + /* + * We allocate a single chunk for the struct including percentiles and + * centroids (including extra buffer for new data). + */ + len = MAXALIGN(sizeof(tdigest_aggstate_t)) + + MAXALIGN(sizeof(double) * npercentiles) + + MAXALIGN(sizeof(double) * nvalues) + + (BUFFER_SIZE(compression) * sizeof(centroid_t)); + + ptr = palloc0(len); + + state = (tdigest_aggstate_t *) ptr; + ptr += MAXALIGN(sizeof(tdigest_aggstate_t)); + + state->nvalues = nvalues; + state->npercentiles = npercentiles; + state->compression = compression; + + if (npercentiles > 0) + { + state->percentiles = (double *) ptr; + ptr += MAXALIGN(sizeof(double) * npercentiles); + } + + if (nvalues > 0) + { + state->values = (double *) ptr; + ptr += MAXALIGN(sizeof(double) * nvalues); + } + + state->centroids = (centroid_t *) ptr; + ptr += (BUFFER_SIZE(compression) * sizeof(centroid_t)); + + Assert(ptr == (char *) state + len); + + return state; +} + + +/* check that the requested percentiles are valid */ +static void +check_percentiles(double *percentiles, int npercentiles) +{ + int i; + + for (i = 0; i < npercentiles; i++) + { + if ((percentiles[i] < 0.0) || (percentiles[i] > 1.0)) + { + elog(ERROR, "invalid percentile value %f, should be in [0.0, 1.0]", + percentiles[i]); + } + } +} + + +static void +check_compression(int compression) +{ + if (compression < MIN_COMPRESSION || compression > MAX_COMPRESSION) + { + elog(ERROR, "invalid compression value %d", compression); + } +} + + +/* + * Add a value to the tdigest (create one if needed). Transition function + * for tdigest aggregate with a single percentile. + */ +Datum +tdigest_add_double(PG_FUNCTION_ARGS) +{ + tdigest_aggstate_t *state; + + MemoryContext aggcontext; + + /* cannot be called directly because of internal-type argument */ + if (!AggCheckCallContext(fcinfo, &aggcontext)) + { + elog(ERROR, "tdigest_add_double called in non-aggregate context"); + } + + /* + * We want to skip NULL values altogether - we return either the existing + * t-digest (if it already exists) or NULL. + */ + if (PG_ARGISNULL(1)) + { + if (PG_ARGISNULL(0)) + { + PG_RETURN_NULL(); + } + + /* if there already is a state accumulated, don't forget it */ + PG_RETURN_DATUM(PG_GETARG_DATUM(0)); + } + + /* if there's no digest allocated, create it now */ + if (PG_ARGISNULL(0)) + { + int compression = PG_GETARG_INT32(2); + int npercentiles = 1; + MemoryContext oldcontext; + + check_compression(compression); + + oldcontext = MemoryContextSwitchTo(aggcontext); + + pgbson *percentilesPgbson = PG_GETARG_MAYBE_NULL_PGBSON(3); + if (percentilesPgbson == NULL || IsPgbsonEmptyDocument(percentilesPgbson)) + { + PG_RETURN_NULL(); + } + pgbsonelement percentilesPgbsonElement; + PgbsonToSinglePgbsonElement(percentilesPgbson, &percentilesPgbsonElement); + double percentile = percentilesPgbsonElement.bsonValue.value.v_double; + + state = tdigest_aggstate_allocate(npercentiles, 0, compression); + + state->percentiles[0] = percentile; + + MemoryContextSwitchTo(oldcontext); + } + else + { + state = (tdigest_aggstate_t *) PG_GETARG_POINTER(0); + } + + pgbson *inputPgbson = PG_GETARG_MAYBE_NULL_PGBSON(1); + if (inputPgbson == NULL || IsPgbsonEmptyDocument(inputPgbson)) + { + PG_RETURN_NULL(); + } + pgbsonelement inputPgbsonElement; + PgbsonToSinglePgbsonElement(inputPgbson, &inputPgbsonElement); + if (BsonValueIsNumber(&inputPgbsonElement.bsonValue) && !IsBsonValueNaN( + &inputPgbsonElement.bsonValue)) + { + /* doesn't throw error if data exceeds the range of double */ + /* take overflow and underflow as infinity */ + double value = BsonValueAsDoubleQuiet(&inputPgbsonElement.bsonValue); + tdigest_add(state, value); + } + + PG_RETURN_POINTER(state); +} + + +/* + * Add a value to the tdigest (create one if needed). Transition function + * for tdigest aggregate with an array of percentiles. + */ +Datum +tdigest_add_double_array(PG_FUNCTION_ARGS) +{ + tdigest_aggstate_t *state; + + MemoryContext aggcontext; + + /* cannot be called directly because of internal-type argument */ + if (!AggCheckCallContext(fcinfo, &aggcontext)) + { + elog(ERROR, "tdigest_add_double_array called in non-aggregate context"); + } + + /* + * We want to skip NULL values altogether - we return either the existing + * t-digest or NULL. + */ + if (PG_ARGISNULL(1)) + { + if (PG_ARGISNULL(0)) + { + PG_RETURN_NULL(); + } + + /* if there already is a state accumulated, don't forget it */ + PG_RETURN_DATUM(PG_GETARG_DATUM(0)); + } + + /* if there's no digest allocated, create it now */ + if (PG_ARGISNULL(0)) + { + int compression = PG_GETARG_INT32(2); + double *percentiles; + int npercentiles; + MemoryContext oldcontext; + + check_compression(compression); + + oldcontext = MemoryContextSwitchTo(aggcontext); + + pgbson *percentilesPgbson = PG_GETARG_MAYBE_NULL_PGBSON(3); + if (percentilesPgbson == NULL || IsPgbsonEmptyDocument(percentilesPgbson)) + { + PG_RETURN_NULL(); + } + pgbsonelement percentilesPgbsonElement; + PgbsonToSinglePgbsonElement(percentilesPgbson, &percentilesPgbsonElement); + + percentiles = bson_to_double_array(fcinfo, &percentilesPgbsonElement.bsonValue, + &npercentiles); + + check_percentiles(percentiles, npercentiles); + + state = tdigest_aggstate_allocate(npercentiles, 0, compression); + + memcpy(state->percentiles, percentiles, sizeof(double) * npercentiles); + + pfree(percentiles); + + MemoryContextSwitchTo(oldcontext); + } + else + { + state = (tdigest_aggstate_t *) PG_GETARG_POINTER(0); + } + + pgbson *inputPgbson = PG_GETARG_MAYBE_NULL_PGBSON(1); + if (inputPgbson == NULL || IsPgbsonEmptyDocument(inputPgbson)) + { + PG_RETURN_NULL(); + } + pgbsonelement inputPgbsonElement; + PgbsonToSinglePgbsonElement(inputPgbson, &inputPgbsonElement); + if (BsonValueIsNumber(&inputPgbsonElement.bsonValue) && !IsBsonValueNaN( + &inputPgbsonElement.bsonValue)) + { + /* doesn't throw error if data exceeds the range of double */ + /* take overflow and underflow as infinity */ + double value = BsonValueAsDoubleQuiet(&inputPgbsonElement.bsonValue); + tdigest_add(state, value); + } + + PG_RETURN_POINTER(state); +} + + +/* + * Compute percentile from a tdigest. Final function for tdigest aggregate + * with a single percentile. + */ +Datum +tdigest_percentile(PG_FUNCTION_ARGS) +{ + tdigest_aggstate_t *state; + MemoryContext aggcontext; + double result; + + /* cannot be called directly because of internal-type argument */ + if (!AggCheckCallContext(fcinfo, &aggcontext)) + { + elog(ERROR, "tdigest_percentile called in non-aggregate context"); + } + + /* if there's no digest, return NULL */ + if (PG_ARGISNULL(0)) + { + PG_RETURN_NULL(); + } + + state = (tdigest_aggstate_t *) PG_GETARG_POINTER(0); + + pgbsonelement finalValue; + finalValue.path = ""; + finalValue.pathLength = 0; + + /* return null bson if no numeric data was added */ + if (state->count == 0) + { + finalValue.bsonValue.value_type = BSON_TYPE_NULL; + PG_RETURN_POINTER(PgbsonElementToPgbson(&finalValue)); + } + + tdigest_compute_quantiles(state, &result); + + finalValue.bsonValue.value_type = BSON_TYPE_DOUBLE; + finalValue.bsonValue.value.v_double = result; + + PG_RETURN_POINTER(PgbsonElementToPgbson(&finalValue)); +} + + +/* + * Compute percentiles from a tdigest. Final function for tdigest aggregate + * with an array of percentiles. + */ +Datum +tdigest_array_percentiles(PG_FUNCTION_ARGS) +{ + double *result; + MemoryContext aggcontext; + + tdigest_aggstate_t *state; + + /* cannot be called directly because of internal-type argument */ + if (!AggCheckCallContext(fcinfo, &aggcontext)) + { + elog(ERROR, "tdigest_array_percentiles called in non-aggregate context"); + } + + if (PG_ARGISNULL(0)) + { + PG_RETURN_NULL(); + } + + state = (tdigest_aggstate_t *) PG_GETARG_POINTER(0); + + /* return null bson if no numeric data was added */ + if (state->count == 0) + { + pgbson_writer writer; + PgbsonWriterInit(&writer); + + pgbson_array_writer arrayWriter; + PgbsonWriterStartArray(&writer, "", 0, &arrayWriter); + for (int i = 0; i < state->npercentiles; i++) + { + bson_value_t val = { + .value_type = BSON_TYPE_NULL + }; + PgbsonArrayWriterWriteValue(&arrayWriter, &val); + } + + PgbsonWriterEndArray(&writer, &arrayWriter); + PG_RETURN_POINTER(PgbsonWriterGetPgbson(&writer)); + } + + result = palloc0(state->npercentiles * sizeof(double)); + + tdigest_compute_quantiles(state, result); + + return double_array_to_bson_array(fcinfo, result, state->npercentiles); +} + + +Datum +tdigest_serial(PG_FUNCTION_ARGS) +{ + bytea *v; + tdigest_aggstate_t *state; + Size len; + char *ptr; + + state = (tdigest_aggstate_t *) PG_GETARG_POINTER(0); + + len = offsetof(tdigest_aggstate_t, percentiles) + + state->npercentiles * sizeof(double) + + state->nvalues * sizeof(double) + + state->ncentroids * sizeof(centroid_t); + + v = palloc(len + VARHDRSZ); + + SET_VARSIZE(v, len + VARHDRSZ); + ptr = VARDATA(v); + + memcpy(ptr, state, offsetof(tdigest_aggstate_t, percentiles)); + ptr += offsetof(tdigest_aggstate_t, percentiles); + + if (state->npercentiles > 0) + { + memcpy(ptr, state->percentiles, sizeof(double) * state->npercentiles); + ptr += sizeof(double) * state->npercentiles; + } + + if (state->nvalues > 0) + { + memcpy(ptr, state->values, sizeof(double) * state->nvalues); + ptr += sizeof(double) * state->nvalues; + } + + /* FIXME maybe don't serialize full centroids, but just sum/count */ + memcpy(ptr, state->centroids, + sizeof(centroid_t) * state->ncentroids); + ptr += sizeof(centroid_t) * state->ncentroids; + + Assert(VARDATA(v) + len == ptr); + + PG_RETURN_POINTER(v); +} + + +Datum +tdigest_deserial(PG_FUNCTION_ARGS) +{ + bytea *v = (bytea *) PG_GETARG_POINTER(0); + char *ptr = VARDATA_ANY(v); + tdigest_aggstate_t tmp; + tdigest_aggstate_t *state; + double *percentiles = NULL; + double *values = NULL; + + /* copy aggstate header into a local variable */ + memcpy(&tmp, ptr, offsetof(tdigest_aggstate_t, percentiles)); + ptr += offsetof(tdigest_aggstate_t, percentiles); + + /* allocate and copy percentiles */ + if (tmp.npercentiles > 0) + { + percentiles = palloc(tmp.npercentiles * sizeof(double)); + memcpy(percentiles, ptr, tmp.npercentiles * sizeof(double)); + ptr += tmp.npercentiles * sizeof(double); + } + + /* allocate and copy values */ + if (tmp.nvalues > 0) + { + values = palloc(tmp.nvalues * sizeof(double)); + memcpy(values, ptr, tmp.nvalues * sizeof(double)); + ptr += tmp.nvalues * sizeof(double); + } + + state = tdigest_aggstate_allocate(tmp.npercentiles, tmp.nvalues, + tmp.compression); + + if (tmp.npercentiles > 0) + { + memcpy(state->percentiles, percentiles, tmp.npercentiles * sizeof(double)); + pfree(percentiles); + } + + if (tmp.nvalues > 0) + { + memcpy(state->values, values, tmp.nvalues * sizeof(double)); + pfree(values); + } + + /* copy the data into the newly-allocated state */ + memcpy(state, &tmp, offsetof(tdigest_aggstate_t, percentiles)); + + /* we don't need to move the pointer */ + + /* copy the centroids back */ + memcpy(state->centroids, ptr, + sizeof(centroid_t) * state->ncentroids); + ptr += sizeof(centroid_t) * state->ncentroids; + + PG_RETURN_POINTER(state); +} + + +static tdigest_aggstate_t * +tdigest_copy(tdigest_aggstate_t *state) +{ + tdigest_aggstate_t *copy; + + copy = tdigest_aggstate_allocate(state->npercentiles, state->nvalues, + state->compression); + + memcpy(copy, state, offsetof(tdigest_aggstate_t, percentiles)); + + if (state->nvalues > 0) + { + memcpy(copy->values, state->values, + sizeof(double) * state->nvalues); + } + + if (state->npercentiles > 0) + { + memcpy(copy->percentiles, state->percentiles, + sizeof(double) * state->npercentiles); + } + + memcpy(copy->centroids, state->centroids, + state->ncentroids * sizeof(centroid_t)); + + return copy; +} + + +Datum +tdigest_combine(PG_FUNCTION_ARGS) +{ + tdigest_aggstate_t *src; + tdigest_aggstate_t *dst; + MemoryContext aggcontext; + MemoryContext oldcontext; + + if (!AggCheckCallContext(fcinfo, &aggcontext)) + { + elog(ERROR, "tdigest_combine called in non-aggregate context"); + } + + /* if no "merged" state yet, try creating it */ + if (PG_ARGISNULL(0)) + { + /* nope, the second argument is NULL to, so return NULL */ + if (PG_ARGISNULL(1)) + { + PG_RETURN_NULL(); + } + + /* the second argument is not NULL, so copy it */ + src = (tdigest_aggstate_t *) PG_GETARG_POINTER(1); + + /* copy the digest into the right long-lived memory context */ + oldcontext = MemoryContextSwitchTo(aggcontext); + src = tdigest_copy(src); + MemoryContextSwitchTo(oldcontext); + + PG_RETURN_POINTER(src); + } + + /* + * If the second argument is NULL, just return the first one (we know + * it's not NULL at this point). + */ + if (PG_ARGISNULL(1)) + { + PG_RETURN_DATUM(PG_GETARG_DATUM(0)); + } + + /* Now we know neither argument is NULL, so merge them. */ + src = (tdigest_aggstate_t *) PG_GETARG_POINTER(1); + dst = (tdigest_aggstate_t *) PG_GETARG_POINTER(0); + + /* + * Do a compaction on each digest, to make sure we have enough space. + * + * XXX Maybe do this only when necessary, i.e. when we can't fit the + * data into the dst digest? Also, is it really ensured this gives us + * enough free space? + */ + tdigest_compact(dst); + tdigest_compact(src); + + /* copy the second part */ + memcpy(&dst->centroids[dst->ncentroids], + src->centroids, + src->ncentroids * sizeof(centroid_t)); + + dst->ncentroids += src->ncentroids; + dst->count += src->count; + + /* mark the digest as not compacted */ + dst->ncompacted = 0; + + PG_RETURN_POINTER(dst); +} + + +/* + * Comparator, ordering the centroids by mean value. + * + * When the mean is the same, we try ordering the centroids by count. + * + * In principle, centroids with the same mean represent the same value, + * but we still need to care about the count to allow rebalancing the + * centroids later. + */ +static int +centroid_cmp(const void *a, const void *b) +{ + double ma, mb; + + centroid_t *ca = (centroid_t *) a; + centroid_t *cb = (centroid_t *) b; + + ma = ca->mean; + mb = cb->mean; + + if (ma < mb) + { + return -1; + } + else if (ma > mb) + { + return 1; + } + + if (ca->count < cb->count) + { + return -1; + } + else if (ca->count > cb->count) + { + return 1; + } + + return 0; +} + + +/* + * Transform an input bson to a plain double C array. + */ +static double * +bson_to_double_array(FunctionCallInfo fcinfo, bson_value_t *barray, int *len) +{ + if (barray->value_type != BSON_TYPE_ARRAY || BsonDocumentValueCountKeys(barray) == 0) + { + ereport(ERROR, (errcode(ERRCODE_DOCUMENTDB_LOCATION7750301), errmsg( + "The $percentile 'p' field must be an array of numbers from [0.0, 1.0], but found: %s", + BsonValueToJsonForLogging(barray)))); + } + + (*len) = BsonDocumentValueCountKeys(barray); + double *result = (double *) palloc((*len) * sizeof(double)); + bson_iter_t iter; + BsonValueInitIterator(barray, &iter); + int i = 0; + while (bson_iter_next(&iter)) + { + const bson_value_t *value = bson_iter_value(&iter); + if (!BsonValueIsNumber(value)) + { + ereport(ERROR, (errcode(ERRCODE_DOCUMENTDB_COMMANDNOTSUPPORTED), + errmsg( + "Accumulator $percentile is not implemented yet"))); + ereport(ERROR, (errcode(ERRCODE_DOCUMENTDB_LOCATION7750302), errmsg( + "The $percentile 'p' field must be an array of numbers from [0.0, 1.0], but found: %s", + BsonValueToJsonForLogging(value)))); + } + double percentile = BsonValueAsDoubleQuiet(bson_iter_value(&iter)); + if (percentile < 0 || percentile > 1) + { + ereport(ERROR, (errcode(ERRCODE_DOCUMENTDB_LOCATION7750303), errmsg( + "The $percentile 'p' field must be an array of numbers from [0.0, 1.0], but found: %lf", + percentile))); + } + result[i] = percentile; + i++; + } + + return result; +} + + +/* + * construct a bson array from a simple C double array + */ +static Datum +double_array_to_bson_array(FunctionCallInfo fcinfo, double *darray, int len) +{ + bson_value_t val = { + .value_type = BSON_TYPE_DOUBLE + }; + pgbson_writer writer; + PgbsonWriterInit(&writer); + + pgbson_array_writer arrayWriter; + PgbsonWriterStartArray(&writer, "", 0, &arrayWriter); + for (int i = 0; i < len; i++) + { + val.value.v_double = darray[i]; + PgbsonArrayWriterWriteValue(&arrayWriter, &val); + } + + PgbsonWriterEndArray(&writer, &arrayWriter); + pfree(darray); + PG_RETURN_POINTER(PgbsonWriterGetPgbson(&writer)); +} diff --git a/pg_documentdb/src/configs/system_configs.c b/pg_documentdb/src/configs/system_configs.c index 098e0afa..acbd83fa 100644 --- a/pg_documentdb/src/configs/system_configs.c +++ b/pg_documentdb/src/configs/system_configs.c @@ -71,6 +71,9 @@ int ScramDefaultSaltLen = SCRAM_DEFAULT_SALT_LEN; #define MAX_USER_LIMIT 10 int MaxUserLimit = MAX_USER_LIMIT; +#define DEFAULT_TDIGEST_COMPRESSION_ACCURACY 1500 +int TdigestCompressionAccuracy = DEFAULT_TDIGEST_COMPRESSION_ACCURACY; + #define DEFAULT_DOCUMENTDB_PG_READ_ONLY_FOR_DISK_FULL false bool DocumentDBPGReadOnlyForDiskFull = DEFAULT_DOCUMENTDB_PG_READ_ONLY_FOR_DISK_FULL; @@ -263,4 +266,13 @@ InitializeSystemConfigurations(const char *prefix, const char *newGucPrefix) PGC_SUSET, 0, NULL, NULL, NULL); + + DefineCustomIntVariable( + psprintf("%s.tdigestCompressionAccuracy", newGucPrefix), + gettext_noop("Accuracy parameter of the t-digest compression."), + gettext_noop( + "The number of maximum centroid to use in the t-digest. Range from 10 to 10000. The higher the number, the more accurate will be, but higher memory usage."), + &TdigestCompressionAccuracy, + DEFAULT_TDIGEST_COMPRESSION_ACCURACY, 10, 10000, + PGC_USERSET, 0, NULL, NULL, NULL); } diff --git a/pg_documentdb/src/infrastructure/feature_counter.c b/pg_documentdb/src/infrastructure/feature_counter.c index e69f5e3e..3aa658e7 100644 --- a/pg_documentdb/src/infrastructure/feature_counter.c +++ b/pg_documentdb/src/infrastructure/feature_counter.c @@ -270,6 +270,8 @@ static char FeatureMapping[MAX_FEATURE_COUNT][MAX_FEATURE_NAME_LENGTH] = { [FEATURE_STAGE_GROUP_ACC_FIRSTN_GT10] = "firstN_acc_GT10", [FEATURE_STAGE_GROUP_ACC_LASTN] = "lastN_acc", [FEATURE_STAGE_GROUP_ACC_LASTN_GT10] = "lastN_acc_GT10", + [FEATURE_STAGE_GROUP_ACC_MEDIAN] = "median_acc", + [FEATURE_STAGE_GROUP_ACC_PERCENTILE] = "percentile_acc", [FEATURE_STAGE_GROUP_ACC_TOPN] = "topN", [FEATURE_STAGE_INDEXSTATS] = "indexStats", [FEATURE_STAGE_INVERSEMATCH] = "inverseMatch", diff --git a/pg_documentdb/src/metadata/metadata_cache.c b/pg_documentdb/src/metadata/metadata_cache.c index 0b53d65a..2e6ffc77 100644 --- a/pg_documentdb/src/metadata/metadata_cache.c +++ b/pg_documentdb/src/metadata/metadata_cache.c @@ -799,6 +799,12 @@ typedef struct HelioApiOidCacheData /* OID of the BSONSTDDEVSAMP aggregate function */ Oid ApiCatalogBsonStdDevSampAggregateFunctionOid; + /* OID of the BSONMEDIAN aggregate function */ + Oid ApiCatalogBsonMedianAggregateFunctionOid; + + /* OID of the BSONPERCENTILE aggregate function */ + Oid ApiCatalogBsonPercentileAggregateFunctionOid; + /* OID of the pg_catalog.any_value aggregate */ Oid PostgresAnyValueFunctionOid; @@ -4036,6 +4042,24 @@ BsonStdDevSampAggregateFunctionOid(void) } +Oid +BsonMedianAggregateFunctionOid(void) +{ + return GetAggregateFunctionByName( + &Cache.ApiCatalogBsonMedianAggregateFunctionOid, + DocumentDBApiInternalSchemaName, "bsonmedian"); +} + + +Oid +BsonPercentileAggregateFunctionOid(void) +{ + return GetAggregateFunctionByName( + &Cache.ApiCatalogBsonPercentileAggregateFunctionOid, + DocumentDBApiInternalSchemaName, "bsonpercentile"); +} + + Oid BsonAddToSetAggregateFunctionOid(void) { diff --git a/pg_documentdb/src/test/regress/expected/public_api_schema.out b/pg_documentdb/src/test/regress/expected/public_api_schema.out index 4dad11e8..0fd33fc5 100644 --- a/pg_documentdb/src/test/regress/expected/public_api_schema.out +++ b/pg_documentdb/src/test/regress/expected/public_api_schema.out @@ -302,7 +302,9 @@ documentdb_api_internal | bsonlastnonsorted | documentdb_core.bson | documentdb_core.bson, bigint, documentdb_core.bson | agg documentdb_api_internal | bsonlastonsorted | documentdb_core.bson | documentdb_core.bson, documentdb_core.bson | agg documentdb_api_internal | bsonmaxn | documentdb_core.bson | documentdb_core.bson | agg + documentdb_api_internal | bsonmedian | documentdb_core.bson | documentdb_core.bson, integer, documentdb_core.bson | agg documentdb_api_internal | bsonminn | documentdb_core.bson | documentdb_core.bson | agg + documentdb_api_internal | bsonpercentile | documentdb_core.bson | documentdb_core.bson, integer, documentdb_core.bson | agg documentdb_api_internal | bsonstddevpop | documentdb_core.bson | documentdb_core.bson | agg documentdb_api_internal | bsonstddevsamp | documentdb_core.bson | documentdb_core.bson | agg documentdb_api_internal | build_index_concurrently | | IN p_job_index integer | proc @@ -354,11 +356,18 @@ documentdb_api_internal | rum_bson_text_path_options | void | internal | func documentdb_api_internal | schedule_background_index_build_workers | void | p_max_num_active_user_index_builds integer DEFAULT (current_setting(('documentdb'::text || '.maxNumActiveUsersIndexBuilds'::text)))::integer, p_user_index_build_schedule integer DEFAULT (current_setting(('documentdb'::text || '.indexBuildScheduleInSec'::text)))::integer | func documentdb_api_internal | schema_validation_against_update | boolean | p_eval_state bytea, p_target_document documentdb_core.bson, p_source_document documentdb_core.bson, p_is_moderate boolean | func + documentdb_api_internal | tdigest_add_double | internal | internal, documentdb_core.bson, integer, documentdb_core.bson | func + documentdb_api_internal | tdigest_add_double_array | internal | internal, documentdb_core.bson, integer, documentdb_core.bson | func + documentdb_api_internal | tdigest_array_percentiles | documentdb_core.bson | internal | func + documentdb_api_internal | tdigest_combine | internal | internal, internal | func + documentdb_api_internal | tdigest_deserial | internal | bytea, internal | func + documentdb_api_internal | tdigest_percentile | documentdb_core.bson | internal | func + documentdb_api_internal | tdigest_serial | bytea | internal | func documentdb_api_internal | trigger_validate_dbname | trigger | | func documentdb_api_internal | update_one | record | p_collection_id bigint, p_shard_key_value bigint, p_query documentdb_core.bson, p_update documentdb_core.bson, p_shard_key documentdb_core.bson, p_is_upsert boolean, p_sort documentdb_core.bson, p_return_old_or_new boolean, p_return_fields documentdb_core.bson, p_array_filters documentdb_core.bson, p_transaction_id text, OUT o_is_row_updated boolean, OUT o_update_skipped boolean, OUT o_is_retry boolean, OUT o_reinsert_document documentdb_core.bson, OUT o_upserted_object_id bytea, OUT o_result_document documentdb_core.bson | func documentdb_api_internal | update_worker | documentdb_core.bson | p_collection_id bigint, p_shard_key_value bigint, p_shard_oid regclass, p_update_internal_spec documentdb_core.bson, p_update_internal_docs documentdb_core.bsonsequence, p_transaction_id text | func documentdb_api_internal | validate_dbname | void | dbname text | func -(185 rows) +(194 rows) \df documentdb_data.* List of functions @@ -416,10 +425,12 @@ documentdb_api_internal | bsonlastnonsorted | documentdb_core.bson | documentdb_core.bson, bigint, documentdb_core.bson | documentdb_api_internal | bsonlastonsorted | documentdb_core.bson | documentdb_core.bson, documentdb_core.bson | documentdb_api_internal | bsonmaxn | documentdb_core.bson | documentdb_core.bson | + documentdb_api_internal | bsonmedian | documentdb_core.bson | documentdb_core.bson, integer, documentdb_core.bson | documentdb_api_internal | bsonminn | documentdb_core.bson | documentdb_core.bson | + documentdb_api_internal | bsonpercentile | documentdb_core.bson | documentdb_core.bson, integer, documentdb_core.bson | documentdb_api_internal | bsonstddevpop | documentdb_core.bson | documentdb_core.bson | documentdb_api_internal | bsonstddevsamp | documentdb_core.bson | documentdb_core.bson | -(19 rows) +(21 rows) \da+ documentdb_data.* List of aggregate functions diff --git a/pg_documentdb_core/include/utils/documentdb_codes.txt b/pg_documentdb_core/include/utils/documentdb_codes.txt index 8ff2ca22..8ebb4211 100644 --- a/pg_documentdb_core/include/utils/documentdb_codes.txt +++ b/pg_documentdb_core/include/utils/documentdb_codes.txt @@ -497,4 +497,9 @@ Location40229,M00DQ,495 UserCountLimitExceeded,M00DR,496 Location55,M00DS,497 Location40236,M00DT,498 -Location17053,M00DU,499 \ No newline at end of file +Location17053,M00DU,499 +Location7429703,M00DV,500 +Location7436100,M00DW,501 +Location7750301,M00DX,502 +Location7750302,M00DY,503 +Location7750303,M00DZ,504 diff --git a/pg_documentdb_core/include/utils/documentdb_errors.h b/pg_documentdb_core/include/utils/documentdb_errors.h index 393f1a2a..8bac7e20 100644 --- a/pg_documentdb_core/include/utils/documentdb_errors.h +++ b/pg_documentdb_core/include/utils/documentdb_errors.h @@ -1092,4 +1092,14 @@ typedef int DocumentdbErrorEreportCode; #define ERRCODE_DOCUMENTDB_LOCATION17053 MAKE_SQLSTATE('M', '0', '0', 'D', 'U') +#define ERRCODE_DOCUMENTDB_LOCATION7429703 MAKE_SQLSTATE('M', '0', '0', 'D', 'V') + +#define ERRCODE_DOCUMENTDB_LOCATION7436100 MAKE_SQLSTATE('M', '0', '0', 'D', 'W') + +#define ERRCODE_DOCUMENTDB_LOCATION7750301 MAKE_SQLSTATE('M', '0', '0', 'D', 'X') + +#define ERRCODE_DOCUMENTDB_LOCATION7750302 MAKE_SQLSTATE('M', '0', '0', 'D', 'Y') + +#define ERRCODE_DOCUMENTDB_LOCATION7750303 MAKE_SQLSTATE('M', '0', '0', 'D', 'Z') + #endif diff --git a/pg_helio_api/sql/pg_helio_api--1.23-0--1.24-0.sql b/pg_helio_api/sql/pg_helio_api--1.23-0--1.24-0.sql index 4d472dd5..91a35a18 100644 --- a/pg_helio_api/sql/pg_helio_api--1.23-0--1.24-0.sql +++ b/pg_helio_api/sql/pg_helio_api--1.23-0--1.24-0.sql @@ -19,4 +19,6 @@ SET search_path TO helio_api; #include "pg_documentdb/sql/udfs/schema_validation/schema_validation--0.24-0.sql" #include "pg_documentdb/sql/udfs/schema_mgmt/shard_collection--0.24-0.sql" #include "udfs/aggregation/bson_aggregation_redact--1.24-0.sql" -RESET search_path; +#include "pg_documentdb/sql/udfs/aggregation/group_aggregates_support--0.24-0.sql" +#include "pg_documentdb/sql/udfs/aggregation/group_aggregates--0.24-0.sql" +RESET search_path; \ No newline at end of file