From e3dc6c889eac6fbaebec7dc45561e19d96f4a84b Mon Sep 17 00:00:00 2001 From: Shuai Tian Date: Thu, 9 Jan 2025 10:58:45 +0000 Subject: [PATCH] Merged PR 1404676: stage implementation: redact ### Does this PR have any customer impact? yes ### Type (Feature, Refactoring, Bugfix, DevOps, Testing, Perf, etc) Feature ### Does it involve schema level changes? (Table, Column, Index, UDF, etc level changes) Yes, UDF ### Are you introducing any new config? If yes, do you have tests with and without them being set? No ### Release Note (Refer [Template](../docs/release_notes/pgmongo_template.md)) ### Description Implement for stage redact Related work items: #1798586 --- documentdb_errors.csv | 3 +- .../src/test/regress/basic_schedule_core | 2 +- ...bson_aggregation_pipeline_tests_redact.out | 595 ++++++++++++++++++ ...bson_aggregation_pipeline_tests_redact.sql | 137 ++++ mongoerrors.csv | 1 + .../bson_aggregation_pipeline_private.h | 14 + .../include/metadata/metadata_cache.h | 1 + .../include/operators/bson_expression.h | 3 + pg_documentdb/include/utils/feature_counter.h | 3 +- .../bson_aggregation_nested_pipeline.c | 7 + .../aggregation/bson_aggregation_pipeline.c | 94 ++- pg_documentdb/src/aggregation/bson_project.c | 289 ++++++++- .../src/infrastructure/feature_counter.c | 1 + pg_documentdb/src/metadata/metadata_cache.c | 15 + pg_documentdb/src/operators/bson_expression.c | 68 +- .../include/utils/documentdb_codes.txt | 1 + .../include/utils/documentdb_errors.h | 2 + .../sql/pg_helio_api--1.23-0--1.24-0.sql | 2 +- .../bson_aggregation_redact--1.24-0.sql | 5 + .../bson_aggregation_redact--latest.sql | 5 + 20 files changed, 1215 insertions(+), 33 deletions(-) create mode 100644 internal/pg_helio_distributed/src/test/regress/expected/bson_aggregation_pipeline_tests_redact.out create mode 100644 internal/pg_helio_distributed/src/test/regress/sql/bson_aggregation_pipeline_tests_redact.sql create mode 100644 pg_helio_api/sql/udfs/aggregation/bson_aggregation_redact--1.24-0.sql create mode 100644 pg_helio_api/sql/udfs/aggregation/bson_aggregation_redact--latest.sql diff --git a/documentdb_errors.csv b/documentdb_errors.csv index ea50ac0c..0c773944 100644 --- a/documentdb_errors.csv +++ b/documentdb_errors.csv @@ -496,4 +496,5 @@ OrdinalPosition,ErrorName 495,Location40229 496,UserCountLimitExceeded 497,Location55 -498,Location40236 \ No newline at end of file +498,Location40236 +499,Location17053 \ No newline at end of file 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 49aff9a0..348cdf0c 100644 --- a/internal/pg_helio_distributed/src/test/regress/basic_schedule_core +++ b/internal/pg_helio_distributed/src/test/regress/basic_schedule_core @@ -55,7 +55,7 @@ test: bson_aggregation_pipeline_tests_top_bottom_group bson_aggregation_pipeline test: bson_aggregation_array_operators_tests bson_aggregation_bitwise_operators_tests bson_aggregation_boolean_operators_tests bson_aggregation_comparison_operators_tests test: bson_aggregation_conditional_operators_tests bson_aggregation_data_size_operators_tests bson_aggregation_date_operators_tests bson_aggregation_miscellaneous_operators_tests test: bson_aggregation_object_operators_tests bson_aggregation_pipeline_tests_facet_group bson_aggregation_pipeline_tests_push_group bson_aggregation_pipeline_tests_stddevpopsamp_group -test: bson_aggregation_set_operators_tests bson_aggregation_stage_addfield_tests bson_aggregation_stage_bucket_tests bson_projection_operator_positional_tests_core +test: bson_aggregation_set_operators_tests bson_aggregation_stage_addfield_tests bson_aggregation_stage_bucket_tests bson_projection_operator_positional_tests_core bson_aggregation_pipeline_tests_redact test: bson_projection_operator_elemmatch_tests_core bson_projection_operator_dollar_slice_test bson_aggregation_stage_unwind_tests test: bson_aggregation_type_operators_tests bson_aggregation_timestamp_operators_tests bson_aggregation_string_operators_tests test: bson_aggregation_stage_set_tests bson_aggregation_stage_replaceroot_tests bson_aggregation_stage_project_tests diff --git a/internal/pg_helio_distributed/src/test/regress/expected/bson_aggregation_pipeline_tests_redact.out b/internal/pg_helio_distributed/src/test/regress/expected/bson_aggregation_pipeline_tests_redact.out new file mode 100644 index 00000000..1989a75d --- /dev/null +++ b/internal/pg_helio_distributed/src/test/regress/expected/bson_aggregation_pipeline_tests_redact.out @@ -0,0 +1,595 @@ +SET search_path TO helio_core,helio_api,helio_api_catalog,helio_api_internal; +SET citus.next_shard_id TO 5150000; +SET helio_api.next_collection_id TO 51500; +SET helio_api.next_collection_index_id TO 51500; +/* Insert data, normal case*/ +SELECT helio_api.insert_one('db','redactTest1','{ "_id": 1, "level": "public", "content": "content 1", "details": { "level": "public", "value": "content 1.1", "moreDetails": { "level": "restricted", "info": "content 1.1.1" } } }', NULL); +NOTICE: creating collection + insert_one +--------------------------------------------------------------------- + { "n" : { "$numberInt" : "1" }, "ok" : { "$numberDouble" : "1.0" } } +(1 row) + +SELECT helio_api.insert_one('db','redactTest1','{ "_id": 2, "level": "restricted", "content": "content 2", "details": { "level": "public", "value": "content 2.1", "moreDetails": { "level": "restricted", "info": "content 2.1.1" } } }', NULL); + insert_one +--------------------------------------------------------------------- + { "n" : { "$numberInt" : "1" }, "ok" : { "$numberDouble" : "1.0" } } +(1 row) + +SELECT helio_api.insert_one('db','redactTest1','{ "_id": 3, "level": "public", "content": "content 3", "details": { "level": "restricted", "value": "content 3.1", "moreDetails": { "level": "public", "info": "content 3.1.1" } } }', NULL); + insert_one +--------------------------------------------------------------------- + { "n" : { "$numberInt" : "1" }, "ok" : { "$numberDouble" : "1.0" } } +(1 row) + +SELECT helio_api.insert_one('db','redactTest1','{ "_id": 4, "content": "content 4", "details": { "level": "public", "value": "content 4.1" } }', NULL); + insert_one +--------------------------------------------------------------------- + { "n" : { "$numberInt" : "1" }, "ok" : { "$numberDouble" : "1.0" } } +(1 row) + +SELECT helio_api.insert_one('db','redactTest1','{ "_id": 5, "level": "public", "content": "content 5", "details": { "level": "public", "value": "content 5.1", "moreDetails": [{ "level": "restricted", "info": "content 5.1.1" }, { "level": "public", "info": "content 5.1.2" }] } }', NULL); + insert_one +--------------------------------------------------------------------- + { "n" : { "$numberInt" : "1" }, "ok" : { "$numberDouble" : "1.0" } } +(1 row) + +SELECT document FROM bson_aggregation_pipeline('db', + '{ "aggregate": "redactTest1", "pipeline": [ { "$redact": { "$cond": { "if": { "$eq": ["$level", "public"] }, "then": "$$KEEP", "else": "$$PRUNE" } } } ], "cursor": {} }'); + document +--------------------------------------------------------------------- + { "_id" : { "$numberInt" : "1" }, "level" : "public", "content" : "content 1", "details" : { "level" : "public", "value" : "content 1.1", "moreDetails" : { "level" : "restricted", "info" : "content 1.1.1" } } } + + { "_id" : { "$numberInt" : "3" }, "level" : "public", "content" : "content 3", "details" : { "level" : "restricted", "value" : "content 3.1", "moreDetails" : { "level" : "public", "info" : "content 3.1.1" } } } + + { "_id" : { "$numberInt" : "5" }, "level" : "public", "content" : "content 5", "details" : { "level" : "public", "value" : "content 5.1", "moreDetails" : [ { "level" : "restricted", "info" : "content 5.1.1" }, { "level" : "public", "info" : "content 5.1.2" } ] } } +(5 rows) + +SELECT document FROM bson_aggregation_pipeline('db', + '{ "aggregate": "redactTest1", "pipeline": [ { "$redact": { "$cond": { "if": { "$eq": ["$level", "public"] }, "then": "$$DESCEND", "else": "$$PRUNE" } } } ], "cursor": {} }'); + document +--------------------------------------------------------------------- + { "_id" : { "$numberInt" : "1" }, "level" : "public", "content" : "content 1", "details" : { "level" : "public", "value" : "content 1.1" } } + + { "_id" : { "$numberInt" : "3" }, "level" : "public", "content" : "content 3" } + + { "_id" : { "$numberInt" : "5" }, "level" : "public", "content" : "content 5", "details" : { "level" : "public", "value" : "content 5.1", "moreDetails" : [ { "level" : "public", "info" : "content 5.1.2" } ] } } +(5 rows) + +/* Insert data, add validation for array-nested subdocument, array of documents, array of arrays, empty document being returned, test DESCEND and PRUNE*/ +SELECT helio_api.insert_one('db','redactTest2','{ "_id": 1, "level": 1, "a": { "level": 2, "b": { "level": 4, "c": { "level": 1, "d": 8 } } }, "e": 20 }', NULL); +NOTICE: creating collection + insert_one +--------------------------------------------------------------------- + { "n" : { "$numberInt" : "1" }, "ok" : { "$numberDouble" : "1.0" } } +(1 row) + +SELECT helio_api.insert_one('db','redactTest2','{ "_id": 2, "level": 4, "a": { "level": 3, "b": [{ "level": 1, "e": 4 }] } }', NULL); + insert_one +--------------------------------------------------------------------- + { "n" : { "$numberInt" : "1" }, "ok" : { "$numberDouble" : "1.0" } } +(1 row) + +SELECT helio_api.insert_one('db','redactTest2','{ "_id": 3, "level": 2, "a": { "b": { "level": 3, "n": 12 } } }', NULL); + insert_one +--------------------------------------------------------------------- + { "n" : { "$numberInt" : "1" }, "ok" : { "$numberDouble" : "1.0" } } +(1 row) + +SELECT helio_api.insert_one('db','redactTest2','{ "_id": 4, "level": 3, "a": [{ "level": 5, "b": 20 }] }', NULL); + insert_one +--------------------------------------------------------------------- + { "n" : { "$numberInt" : "1" }, "ok" : { "$numberDouble" : "1.0" } } +(1 row) + +SELECT helio_api.insert_one('db','redactTest2','{ "_id": 5, "level": 3, "b": { "level": 3, "d": [ { "level": 1, "e": 4 }, { "level": 5, "g": 9 }, [{ "level": 1, "r": 11 }, 52, 42, 75, { "level": 5, "s": 3 }]] } }', NULL); + insert_one +--------------------------------------------------------------------- + { "n" : { "$numberInt" : "1" }, "ok" : { "$numberDouble" : "1.0" } } +(1 row) + +SELECT document FROM bson_aggregation_pipeline('db', '{ "aggregate": "redactTest2", "pipeline": [ { "$redact": { "$cond": [{"$lte": ["$level", 1]}, "$$DESCEND", "$$PRUNE"] } } ], "cursor": {} }'); + document +--------------------------------------------------------------------- + { "_id" : { "$numberInt" : "1" }, "level" : { "$numberInt" : "1" }, "e" : { "$numberInt" : "20" } } + + + + +(5 rows) + +SELECT document FROM bson_aggregation_pipeline('db', '{ "aggregate": "redactTest2", "pipeline": [ { "$redact": { "$cond": [{"$lte": ["$level", 2]}, "$$DESCEND", "$$PRUNE"] } } ], "cursor": {} }'); + document +--------------------------------------------------------------------- + { "_id" : { "$numberInt" : "1" }, "level" : { "$numberInt" : "1" }, "a" : { "level" : { "$numberInt" : "2" } }, "e" : { "$numberInt" : "20" } } + + { "_id" : { "$numberInt" : "3" }, "level" : { "$numberInt" : "2" }, "a" : { } } + + +(5 rows) + +SELECT document FROM bson_aggregation_pipeline('db', '{ "aggregate": "redactTest2", "pipeline": [ { "$redact": { "$cond": [{"$lte": ["$level", 3]}, "$$DESCEND", "$$PRUNE"] } } ], "cursor": {} }'); + document +--------------------------------------------------------------------- + { "_id" : { "$numberInt" : "1" }, "level" : { "$numberInt" : "1" }, "a" : { "level" : { "$numberInt" : "2" } }, "e" : { "$numberInt" : "20" } } + + { "_id" : { "$numberInt" : "3" }, "level" : { "$numberInt" : "2" }, "a" : { "b" : { "level" : { "$numberInt" : "3" }, "n" : { "$numberInt" : "12" } } } } + { "_id" : { "$numberInt" : "4" }, "level" : { "$numberInt" : "3" }, "a" : [ ] } + { "_id" : { "$numberInt" : "5" }, "level" : { "$numberInt" : "3" }, "b" : { "level" : { "$numberInt" : "3" }, "d" : [ { "level" : { "$numberInt" : "1" }, "e" : { "$numberInt" : "4" } }, [ { "level" : { "$numberInt" : "1" }, "r" : { "$numberInt" : "11" } }, { "$numberInt" : "52" }, { "$numberInt" : "42" }, { "$numberInt" : "75" } ] ] } } +(5 rows) + +SELECT document FROM bson_aggregation_pipeline('db', '{ "aggregate": "redactTest2", "pipeline": [ { "$redact": { "$cond": [{"$lte": ["$level", 4]}, "$$DESCEND", "$$PRUNE"] } } ], "cursor": {} }'); + document +--------------------------------------------------------------------- + { "_id" : { "$numberInt" : "1" }, "level" : { "$numberInt" : "1" }, "a" : { "level" : { "$numberInt" : "2" }, "b" : { "level" : { "$numberInt" : "4" }, "c" : { "level" : { "$numberInt" : "1" }, "d" : { "$numberInt" : "8" } } } }, "e" : { "$numberInt" : "20" } } + { "_id" : { "$numberInt" : "2" }, "level" : { "$numberInt" : "4" }, "a" : { "level" : { "$numberInt" : "3" }, "b" : [ { "level" : { "$numberInt" : "1" }, "e" : { "$numberInt" : "4" } } ] } } + { "_id" : { "$numberInt" : "3" }, "level" : { "$numberInt" : "2" }, "a" : { "b" : { "level" : { "$numberInt" : "3" }, "n" : { "$numberInt" : "12" } } } } + { "_id" : { "$numberInt" : "4" }, "level" : { "$numberInt" : "3" }, "a" : [ ] } + { "_id" : { "$numberInt" : "5" }, "level" : { "$numberInt" : "3" }, "b" : { "level" : { "$numberInt" : "3" }, "d" : [ { "level" : { "$numberInt" : "1" }, "e" : { "$numberInt" : "4" } }, [ { "level" : { "$numberInt" : "1" }, "r" : { "$numberInt" : "11" } }, { "$numberInt" : "52" }, { "$numberInt" : "42" }, { "$numberInt" : "75" } ] ] } } +(5 rows) + +SELECT document FROM bson_aggregation_pipeline('db', '{ "aggregate": "redactTest2", "pipeline": [ { "$redact": { "$cond": [{"$lte": ["$level", 5]}, "$$DESCEND", "$$PRUNE"] } } ], "cursor": {} }'); + document +--------------------------------------------------------------------- + { "_id" : { "$numberInt" : "1" }, "level" : { "$numberInt" : "1" }, "a" : { "level" : { "$numberInt" : "2" }, "b" : { "level" : { "$numberInt" : "4" }, "c" : { "level" : { "$numberInt" : "1" }, "d" : { "$numberInt" : "8" } } } }, "e" : { "$numberInt" : "20" } } + { "_id" : { "$numberInt" : "2" }, "level" : { "$numberInt" : "4" }, "a" : { "level" : { "$numberInt" : "3" }, "b" : [ { "level" : { "$numberInt" : "1" }, "e" : { "$numberInt" : "4" } } ] } } + { "_id" : { "$numberInt" : "3" }, "level" : { "$numberInt" : "2" }, "a" : { "b" : { "level" : { "$numberInt" : "3" }, "n" : { "$numberInt" : "12" } } } } + { "_id" : { "$numberInt" : "4" }, "level" : { "$numberInt" : "3" }, "a" : [ { "level" : { "$numberInt" : "5" }, "b" : { "$numberInt" : "20" } } ] } + { "_id" : { "$numberInt" : "5" }, "level" : { "$numberInt" : "3" }, "b" : { "level" : { "$numberInt" : "3" }, "d" : [ { "level" : { "$numberInt" : "1" }, "e" : { "$numberInt" : "4" } }, { "level" : { "$numberInt" : "5" }, "g" : { "$numberInt" : "9" } }, [ { "level" : { "$numberInt" : "1" }, "r" : { "$numberInt" : "11" } }, { "$numberInt" : "52" }, { "$numberInt" : "42" }, { "$numberInt" : "75" }, { "level" : { "$numberInt" : "5" }, "s" : { "$numberInt" : "3" } } ] ] } } +(5 rows) + +SELECT document FROM bson_aggregation_pipeline('db', '{ "aggregate": "redactTest2", "pipeline": [ { "$redact": { "$cond": [{"$lte": ["$level", 5]}, { "$literal" :"$$DESCEND"}, "$$PRUNE"] } } ], "cursor": {} }'); + document +--------------------------------------------------------------------- + { "_id" : { "$numberInt" : "1" }, "level" : { "$numberInt" : "1" }, "a" : { "level" : { "$numberInt" : "2" }, "b" : { "level" : { "$numberInt" : "4" }, "c" : { "level" : { "$numberInt" : "1" }, "d" : { "$numberInt" : "8" } } } }, "e" : { "$numberInt" : "20" } } + { "_id" : { "$numberInt" : "2" }, "level" : { "$numberInt" : "4" }, "a" : { "level" : { "$numberInt" : "3" }, "b" : [ { "level" : { "$numberInt" : "1" }, "e" : { "$numberInt" : "4" } } ] } } + { "_id" : { "$numberInt" : "3" }, "level" : { "$numberInt" : "2" }, "a" : { "b" : { "level" : { "$numberInt" : "3" }, "n" : { "$numberInt" : "12" } } } } + { "_id" : { "$numberInt" : "4" }, "level" : { "$numberInt" : "3" }, "a" : [ { "level" : { "$numberInt" : "5" }, "b" : { "$numberInt" : "20" } } ] } + { "_id" : { "$numberInt" : "5" }, "level" : { "$numberInt" : "3" }, "b" : { "level" : { "$numberInt" : "3" }, "d" : [ { "level" : { "$numberInt" : "1" }, "e" : { "$numberInt" : "4" } }, { "level" : { "$numberInt" : "5" }, "g" : { "$numberInt" : "9" } }, [ { "level" : { "$numberInt" : "1" }, "r" : { "$numberInt" : "11" } }, { "$numberInt" : "52" }, { "$numberInt" : "42" }, { "$numberInt" : "75" }, { "level" : { "$numberInt" : "5" }, "s" : { "$numberInt" : "3" } } ] ] } } +(5 rows) + +/* Insert data, test KEEP*/ +SELECT helio_api.insert_one('db','redactTest3','{ "_id": 1, "level": 1, "a": { "level": 1, "b": 1 }, "c": { "level": 1, "d": 1 }}', NULL); +NOTICE: creating collection + insert_one +--------------------------------------------------------------------- + { "n" : { "$numberInt" : "1" }, "ok" : { "$numberDouble" : "1.0" } } +(1 row) + +SELECT helio_api.insert_one('db','redactTest3','{ "_id": 2, "level": 2, "a": { "level": 2, "b": 2 }, "c": { "level": 2, "d": 2 }}', NULL); + insert_one +--------------------------------------------------------------------- + { "n" : { "$numberInt" : "1" }, "ok" : { "$numberDouble" : "1.0" } } +(1 row) + +SELECT helio_api.insert_one('db','redactTest3','{ "_id": 3, "level": 3, "a": { "level": 3, "b": 3 }, "c": { "level": 3, "d": 3 }}', NULL); + insert_one +--------------------------------------------------------------------- + { "n" : { "$numberInt" : "1" }, "ok" : { "$numberDouble" : "1.0" } } +(1 row) + +SELECT document FROM bson_aggregation_pipeline('db', '{ "aggregate": "redactTest3", "pipeline": [ { "$redact": { "$cond": [{"$lte": ["$level", 1]}, "$$KEEP", "$$PRUNE"] } } ], "cursor": {} }'); + document +--------------------------------------------------------------------- + { "_id" : { "$numberInt" : "1" }, "level" : { "$numberInt" : "1" }, "a" : { "level" : { "$numberInt" : "1" }, "b" : { "$numberInt" : "1" } }, "c" : { "level" : { "$numberInt" : "1" }, "d" : { "$numberInt" : "1" } } } + + +(3 rows) + +SELECT document FROM bson_aggregation_pipeline('db', '{ "aggregate": "redactTest3", "pipeline": [ { "$redact": { "$cond": [{"$lte": ["$level", 2]}, "$$KEEP", "$$PRUNE"] } } ], "cursor": {} }'); + document +--------------------------------------------------------------------- + { "_id" : { "$numberInt" : "1" }, "level" : { "$numberInt" : "1" }, "a" : { "level" : { "$numberInt" : "1" }, "b" : { "$numberInt" : "1" } }, "c" : { "level" : { "$numberInt" : "1" }, "d" : { "$numberInt" : "1" } } } + { "_id" : { "$numberInt" : "2" }, "level" : { "$numberInt" : "2" }, "a" : { "level" : { "$numberInt" : "2" }, "b" : { "$numberInt" : "2" } }, "c" : { "level" : { "$numberInt" : "2" }, "d" : { "$numberInt" : "2" } } } + +(3 rows) + +SELECT document FROM bson_aggregation_pipeline('db', '{ "aggregate": "redactTest3", "pipeline": [ { "$redact": { "$cond": [{"$lte": ["$level", 3]}, "$$KEEP", "$$PRUNE"] } } ], "cursor": {} }'); + document +--------------------------------------------------------------------- + { "_id" : { "$numberInt" : "1" }, "level" : { "$numberInt" : "1" }, "a" : { "level" : { "$numberInt" : "1" }, "b" : { "$numberInt" : "1" } }, "c" : { "level" : { "$numberInt" : "1" }, "d" : { "$numberInt" : "1" } } } + { "_id" : { "$numberInt" : "2" }, "level" : { "$numberInt" : "2" }, "a" : { "level" : { "$numberInt" : "2" }, "b" : { "$numberInt" : "2" } }, "c" : { "level" : { "$numberInt" : "2" }, "d" : { "$numberInt" : "2" } } } + { "_id" : { "$numberInt" : "3" }, "level" : { "$numberInt" : "3" }, "a" : { "level" : { "$numberInt" : "3" }, "b" : { "$numberInt" : "3" } }, "c" : { "level" : { "$numberInt" : "3" }, "d" : { "$numberInt" : "3" } } } +(3 rows) + +/*test directly systemvariable*/ +SELECT document FROM bson_aggregation_pipeline('db', '{ "aggregate": "redactTest3", "pipeline": [ { "$redact": "$$KEEP" }], "cursor": {} }'); + document +--------------------------------------------------------------------- + { "_id" : { "$numberInt" : "1" }, "level" : { "$numberInt" : "1" }, "a" : { "level" : { "$numberInt" : "1" }, "b" : { "$numberInt" : "1" } }, "c" : { "level" : { "$numberInt" : "1" }, "d" : { "$numberInt" : "1" } } } + { "_id" : { "$numberInt" : "2" }, "level" : { "$numberInt" : "2" }, "a" : { "level" : { "$numberInt" : "2" }, "b" : { "$numberInt" : "2" } }, "c" : { "level" : { "$numberInt" : "2" }, "d" : { "$numberInt" : "2" } } } + { "_id" : { "$numberInt" : "3" }, "level" : { "$numberInt" : "3" }, "a" : { "level" : { "$numberInt" : "3" }, "b" : { "$numberInt" : "3" } }, "c" : { "level" : { "$numberInt" : "3" }, "d" : { "$numberInt" : "3" } } } +(3 rows) + +SELECT document FROM bson_aggregation_pipeline('db', '{ "aggregate": "redactTest3", "pipeline": [ { "$redact": "$$PRUNE"}], "cursor": {} }'); + document +--------------------------------------------------------------------- + + + +(3 rows) + +SELECT document FROM bson_aggregation_pipeline('db', '{ "aggregate": "redactTest3", "pipeline": [ { "$redact": "$$DESCEND"}], "cursor": {} }'); + document +--------------------------------------------------------------------- + { "_id" : { "$numberInt" : "1" }, "level" : { "$numberInt" : "1" }, "a" : { "level" : { "$numberInt" : "1" }, "b" : { "$numberInt" : "1" } }, "c" : { "level" : { "$numberInt" : "1" }, "d" : { "$numberInt" : "1" } } } + { "_id" : { "$numberInt" : "2" }, "level" : { "$numberInt" : "2" }, "a" : { "level" : { "$numberInt" : "2" }, "b" : { "$numberInt" : "2" } }, "c" : { "level" : { "$numberInt" : "2" }, "d" : { "$numberInt" : "2" } } } + { "_id" : { "$numberInt" : "3" }, "level" : { "$numberInt" : "3" }, "a" : { "level" : { "$numberInt" : "3" }, "b" : { "$numberInt" : "3" } }, "c" : { "level" : { "$numberInt" : "3" }, "d" : { "$numberInt" : "3" } } } +(3 rows) + +/*switch case*/ +SELECT helio_api.insert_one('db','redactTestSwitch','{ "_id": 1, "title": "Document 1", "classification": "confidential", "content": "This is confidential content.", "metadata": { "author": "Alice", "revision": 3 } }', NULL); +NOTICE: creating collection + insert_one +--------------------------------------------------------------------- + { "n" : { "$numberInt" : "1" }, "ok" : { "$numberDouble" : "1.0" } } +(1 row) + +SELECT helio_api.insert_one('db','redactTestSwitch','{ "_id": 2, "title": "Document 2", "classification": "public", "content": "This is public content.", "metadata": { "author": "Bob", "revision": 1 } }', NULL); + insert_one +--------------------------------------------------------------------- + { "n" : { "$numberInt" : "1" }, "ok" : { "$numberDouble" : "1.0" } } +(1 row) + +SELECT helio_api.insert_one('db','redactTestSwitch','{ "_id": 3, "title": "Document 3", "classification": "restricted", "content": "This content is restricted.", "metadata": { "author": "Charlie", "revision": 2 } }', NULL); + insert_one +--------------------------------------------------------------------- + { "n" : { "$numberInt" : "1" }, "ok" : { "$numberDouble" : "1.0" } } +(1 row) + +SELECT document FROM bson_aggregation_pipeline('db', '{ "aggregate": "redactTestSwitch", "pipeline": [ { "$redact": { "$switch": { "branches": [ { "case": { "$eq": ["$classification", "confidential"] }, "then": "$$PRUNE" }, { "case": { "$eq": ["$classification", "restricted"] }, "then": { "$cond": { "if": { "$eq": ["$content", null] }, "then": "$$KEEP", "else": "$$PRUNE" } } }], "default": "$$KEEP" } } }], "cursor": {} }'); + document +--------------------------------------------------------------------- + + { "_id" : { "$numberInt" : "2" }, "title" : "Document 2", "classification" : "public", "content" : "This is public content.", "metadata" : { "author" : "Bob", "revision" : { "$numberInt" : "1" } } } + +(3 rows) + +/*$lookup $let and $redact example*/ +SELECT helio_api.insert_one('db','redactUsers','{ "_id": 1, "name": "Alice"}', NULL); +NOTICE: creating collection + insert_one +--------------------------------------------------------------------- + { "n" : { "$numberInt" : "1" }, "ok" : { "$numberDouble" : "1.0" } } +(1 row) + +SELECT helio_api.insert_one('db','redactUsers','{ "_id": 2, "name": "Bob"}', NULL); + insert_one +--------------------------------------------------------------------- + { "n" : { "$numberInt" : "1" }, "ok" : { "$numberDouble" : "1.0" } } +(1 row) + +SELECT helio_api.insert_one('db','redactUsers','{ "_id": 3, "name": "Charlie"}', NULL); + insert_one +--------------------------------------------------------------------- + { "n" : { "$numberInt" : "1" }, "ok" : { "$numberDouble" : "1.0" } } +(1 row) + +SELECT helio_api.insert_one('db','redactOrders','{ "_id": 1, "user_id": 1, "order_amount":150, "status": "completed"}', NULL); +NOTICE: creating collection + insert_one +--------------------------------------------------------------------- + { "n" : { "$numberInt" : "1" }, "ok" : { "$numberDouble" : "1.0" } } +(1 row) + +SELECT helio_api.insert_one('db','redactOrders','{ "_id": 2, "user_id": 1, "order_amount":200, "status": "pending"}', NULL); + insert_one +--------------------------------------------------------------------- + { "n" : { "$numberInt" : "1" }, "ok" : { "$numberDouble" : "1.0" } } +(1 row) + +SELECT helio_api.insert_one('db','redactOrders','{ "_id": 3, "user_id": 2, "order_amount":500, "status": "completed"}', NULL); + insert_one +--------------------------------------------------------------------- + { "n" : { "$numberInt" : "1" }, "ok" : { "$numberDouble" : "1.0" } } +(1 row) + +SELECT helio_api.insert_one('db','redactOrders','{ "_id": 4, "user_id": 2, "order_amount":50, "status": "completed"}', NULL); + insert_one +--------------------------------------------------------------------- + { "n" : { "$numberInt" : "1" }, "ok" : { "$numberDouble" : "1.0" } } +(1 row) + +SELECT helio_api.insert_one('db','redactOrders','{ "_id": 5, "user_id": 3, "order_amount":300, "status": "pending"}', NULL); + insert_one +--------------------------------------------------------------------- + { "n" : { "$numberInt" : "1" }, "ok" : { "$numberDouble" : "1.0" } } +(1 row) + +/* $redact with $let*/ +SELECT document FROM bson_aggregation_pipeline('db', '{ "aggregate": "redactUsers", "pipeline": [ { "$lookup": { "from": "redactOrders", "localField": "_id", "foreignField": "user_id", "as": "user_orders", "pipeline": [ { "$redact": { "$cond": { "if": { "$let": { "vars": { "totalAmount": { "$sum": "$$ROOT.order_amount" } }, "in": { "$gt": [ "$$totalAmount", 40 ] } } }, "then": "$$KEEP", "else": "$$PRUNE" } } } ] } } ], "cursor": {} }'); + document +--------------------------------------------------------------------- + { "_id" : { "$numberInt" : "1" }, "name" : "Alice", "user_orders" : [ { "_id" : { "$numberInt" : "1" }, "user_id" : { "$numberInt" : "1" }, "order_amount" : { "$numberInt" : "150" }, "status" : "completed" }, { "_id" : { "$numberInt" : "2" }, "user_id" : { "$numberInt" : "1" }, "order_amount" : { "$numberInt" : "200" }, "status" : "pending" } ] } + { "_id" : { "$numberInt" : "2" }, "name" : "Bob", "user_orders" : [ { "_id" : { "$numberInt" : "3" }, "user_id" : { "$numberInt" : "2" }, "order_amount" : { "$numberInt" : "500" }, "status" : "completed" }, { "_id" : { "$numberInt" : "4" }, "user_id" : { "$numberInt" : "2" }, "order_amount" : { "$numberInt" : "50" }, "status" : "completed" } ] } + { "_id" : { "$numberInt" : "3" }, "name" : "Charlie", "user_orders" : [ { "_id" : { "$numberInt" : "5" }, "user_id" : { "$numberInt" : "3" }, "order_amount" : { "$numberInt" : "300" }, "status" : "pending" } ] } +(3 rows) + +/* add $let with the same level with $lookup, different variable with $let in $redact*/ +SELECT document FROM bson_aggregation_pipeline('db', '{ "aggregate": "redactUsers", "pipeline": [ { "$lookup": { "from": "redactOrders", "localField": "_id", "foreignField": "user_id", "as": "user_orders", "let": { "user_id": "$_id" }, "pipeline": [ { "$redact": { "$cond": { "if": { "$let": { "vars": { "totalAmount": { "$sum": "$order_amount" } }, "in": { "$gt": [ "$$totalAmount", 40 ] } } }, "then": "$$KEEP", "else": "$$PRUNE" } } } ] } } ], "cursor": {} }'); + document +--------------------------------------------------------------------- + { "_id" : { "$numberInt" : "1" }, "name" : "Alice", "user_orders" : [ { "_id" : { "$numberInt" : "1" }, "user_id" : { "$numberInt" : "1" }, "order_amount" : { "$numberInt" : "150" }, "status" : "completed" }, { "_id" : { "$numberInt" : "2" }, "user_id" : { "$numberInt" : "1" }, "order_amount" : { "$numberInt" : "200" }, "status" : "pending" } ] } + { "_id" : { "$numberInt" : "2" }, "name" : "Bob", "user_orders" : [ { "_id" : { "$numberInt" : "3" }, "user_id" : { "$numberInt" : "2" }, "order_amount" : { "$numberInt" : "500" }, "status" : "completed" }, { "_id" : { "$numberInt" : "4" }, "user_id" : { "$numberInt" : "2" }, "order_amount" : { "$numberInt" : "50" }, "status" : "completed" } ] } + { "_id" : { "$numberInt" : "3" }, "name" : "Charlie", "user_orders" : [ { "_id" : { "$numberInt" : "5" }, "user_id" : { "$numberInt" : "3" }, "order_amount" : { "$numberInt" : "300" }, "status" : "pending" } ] } +(3 rows) + +/* two level $let has the same variable*/ +SELECT document FROM bson_aggregation_pipeline('db', '{ "aggregate": "redactUsers", "pipeline": [ { "$lookup": { "from": "redactOrders", "localField": "_id", "foreignField": "user_id", "as": "user_orders", "let": { "user_id": "$_id", "totalAmount": { "$sum": "$user_orders.order_amount" } }, "pipeline": [ { "$redact": { "$cond": { "if": { "$let": { "vars": { "totalAmount": { "$sum": "$order_amount" } }, "in": { "$gt": [ "$$totalAmount", 40 ] } } }, "then": "$$KEEP", "else": "$$PRUNE" } } } ] } } ], "cursor": {} }'); + document +--------------------------------------------------------------------- + { "_id" : { "$numberInt" : "1" }, "name" : "Alice", "user_orders" : [ { "_id" : { "$numberInt" : "1" }, "user_id" : { "$numberInt" : "1" }, "order_amount" : { "$numberInt" : "150" }, "status" : "completed" }, { "_id" : { "$numberInt" : "2" }, "user_id" : { "$numberInt" : "1" }, "order_amount" : { "$numberInt" : "200" }, "status" : "pending" } ] } + { "_id" : { "$numberInt" : "2" }, "name" : "Bob", "user_orders" : [ { "_id" : { "$numberInt" : "3" }, "user_id" : { "$numberInt" : "2" }, "order_amount" : { "$numberInt" : "500" }, "status" : "completed" }, { "_id" : { "$numberInt" : "4" }, "user_id" : { "$numberInt" : "2" }, "order_amount" : { "$numberInt" : "50" }, "status" : "completed" } ] } + { "_id" : { "$numberInt" : "3" }, "name" : "Charlie", "user_orders" : [ { "_id" : { "$numberInt" : "5" }, "user_id" : { "$numberInt" : "3" }, "order_amount" : { "$numberInt" : "300" }, "status" : "pending" } ] } +(3 rows) + +/* redact use top level $let*/ +SELECT document FROM bson_aggregation_pipeline('db', '{ "aggregate": "redactUsers", "pipeline": [ { "$lookup": { "from": "redactOrders", "localField": "_id", "foreignField": "user_id", "as": "user_orders", "let": { "user_id": "$_id" }, "pipeline": [ { "$redact": { "$cond": { "if": { "$let": { "vars": { "totalAmount": { "$sum": "$order_amount" } }, "in": { "$and": [ { "$gt": [ "$$totalAmount", 40 ] }, { "$lt": [ "$$user_id", 2 ] } ] } } }, "then": "$$KEEP", "else": "$$PRUNE" } } } ] } } ], "cursor": {} }'); + document +--------------------------------------------------------------------- + { "_id" : { "$numberInt" : "1" }, "name" : "Alice", "user_orders" : [ { "_id" : { "$numberInt" : "1" }, "user_id" : { "$numberInt" : "1" }, "order_amount" : { "$numberInt" : "150" }, "status" : "completed" }, { "_id" : { "$numberInt" : "2" }, "user_id" : { "$numberInt" : "1" }, "order_amount" : { "$numberInt" : "200" }, "status" : "pending" } ] } + { "_id" : { "$numberInt" : "2" }, "name" : "Bob", "user_orders" : [ ] } + { "_id" : { "$numberInt" : "3" }, "name" : "Charlie", "user_orders" : [ ] } +(3 rows) + +/*facet with redact test case user data*/ +SELECT helio_api.insert_one('db', 'facetUsers', '{ "_id": 1, "name": "Alice", "email": "alice@example.com", "age": 25 }', NULL); +NOTICE: creating collection + insert_one +--------------------------------------------------------------------- + { "n" : { "$numberInt" : "1" }, "ok" : { "$numberDouble" : "1.0" } } +(1 row) + +SELECT helio_api.insert_one('db', 'facetUsers', '{ "_id": 2, "name": "Bob", "email": "bob@example.com", "age": 25 }', NULL); + insert_one +--------------------------------------------------------------------- + { "n" : { "$numberInt" : "1" }, "ok" : { "$numberDouble" : "1.0" } } +(1 row) + +SELECT helio_api.insert_one('db', 'facetUsers', '{ "_id": 3, "name": "Charlie", "email": "charlie@example.com", "age": 30 }', NULL); + insert_one +--------------------------------------------------------------------- + { "n" : { "$numberInt" : "1" }, "ok" : { "$numberDouble" : "1.0" } } +(1 row) + +/*facet with redact case, one is empty array and the other is not*/ +SELECT document FROM bson_aggregation_pipeline('db', '{ "aggregate": "facetUsers", "pipeline": [ { "$facet": { "ageGroup": [ { "$group": { "_id": "$age", "users": { "$push": "$name" } } } ], "redactEmail": [ { "$redact": { "$cond": { "if": { "$eq": ["$email", null] }, "then": "$$KEEP", "else": "$$PRUNE" } } } ] } } ], "cursor": {} }'); + document +--------------------------------------------------------------------- + { "ageGroup" : [ { "_id" : { "$numberInt" : "30" }, "users" : [ "Charlie" ] }, { "_id" : { "$numberInt" : "25" }, "users" : [ "Alice", "Bob" ] } ], "redactEmail" : [ ] } +(1 row) + +SELECT document FROM bson_aggregation_pipeline('db', '{ "aggregate": "facetUsers", "pipeline": [ { "$facet": { "ageGroup": [ { "$group": { "_id": "$age", "users": { "$push": "$name" } } } ], "redactEmail": [ { "$redact": { "$cond": { "if": { "$eq": ["$email", "alice@example.com"] }, "then": "$$KEEP", "else": "$$PRUNE" } } } ] } } ], "cursor": {} }'); + document +--------------------------------------------------------------------- + { "ageGroup" : [ { "_id" : { "$numberInt" : "30" }, "users" : [ "Charlie" ] }, { "_id" : { "$numberInt" : "25" }, "users" : [ "Alice", "Bob" ] } ], "redactEmail" : [ { "_id" : { "$numberInt" : "1" }, "name" : "Alice", "email" : "alice@example.com", "age" : { "$numberInt" : "25" } } ] } +(1 row) + +/*graphLookup with redact test case employee data*/ +SELECT helio_api.insert_one('db', 'graphLookupEmployee', '{ "_id": 1, "employee_id": 1, "name": "Alice", "manager_id": null, "email": "alice@example.com" }', NULL); +NOTICE: creating collection + insert_one +--------------------------------------------------------------------- + { "n" : { "$numberInt" : "1" }, "ok" : { "$numberDouble" : "1.0" } } +(1 row) + +SELECT helio_api.insert_one('db', 'graphLookupEmployee', '{ "_id": 2, "employee_id": 2, "name": "Bob", "manager_id": 1, "email": "bob@example.com" }', NULL); + insert_one +--------------------------------------------------------------------- + { "n" : { "$numberInt" : "1" }, "ok" : { "$numberDouble" : "1.0" } } +(1 row) + +SELECT helio_api.insert_one('db', 'graphLookupEmployee', '{ "_id": 3, "employee_id": 3, "name": "Charlie", "manager_id": 1, "email": "charlie@example.com" }', NULL); + insert_one +--------------------------------------------------------------------- + { "n" : { "$numberInt" : "1" }, "ok" : { "$numberDouble" : "1.0" } } +(1 row) + +SELECT helio_api.insert_one('db', 'graphLookupEmployee', '{ "_id": 4, "employee_id": 4, "name": "David", "manager_id": 2, "email": "david@example.com" }', NULL); + insert_one +--------------------------------------------------------------------- + { "n" : { "$numberInt" : "1" }, "ok" : { "$numberDouble" : "1.0" } } +(1 row) + +SELECT helio_api.insert_one('db', 'graphLookupEmployee', '{ "_id": 5, "employee_id": 5, "name": "Eve", "manager_id": 2, "email": "eve@example.com" }', NULL); + insert_one +--------------------------------------------------------------------- + { "n" : { "$numberInt" : "1" }, "ok" : { "$numberDouble" : "1.0" } } +(1 row) + +/*graphLookup with redact test case, prune employee do not have subordinates*/ +SELECT document FROM bson_aggregation_pipeline('db', '{ "aggregate": "graphLookupEmployee", "pipeline": [ { "$graphLookup": { "from": "graphLookupEmployee", "startWith": "$employee_id", "connectFromField": "employee_id", "connectToField": "manager_id", "as": "subordinates" } }, { "$redact": { "$cond": { "if": { "$eq": [{ "$size": "$subordinates" }, 0] }, "then": "$$PRUNE", "else": "$$KEEP" } } } ], "cursor": {} }'); + document +--------------------------------------------------------------------- + { "_id" : { "$numberInt" : "1" }, "employee_id" : { "$numberInt" : "1" }, "name" : "Alice", "manager_id" : null, "email" : "alice@example.com", "subordinates" : [ { "_id" : { "$numberInt" : "2" }, "employee_id" : { "$numberInt" : "2" }, "name" : "Bob", "manager_id" : { "$numberInt" : "1" }, "email" : "bob@example.com" }, { "_id" : { "$numberInt" : "3" }, "employee_id" : { "$numberInt" : "3" }, "name" : "Charlie", "manager_id" : { "$numberInt" : "1" }, "email" : "charlie@example.com" }, { "_id" : { "$numberInt" : "4" }, "employee_id" : { "$numberInt" : "4" }, "name" : "David", "manager_id" : { "$numberInt" : "2" }, "email" : "david@example.com" }, { "_id" : { "$numberInt" : "5" }, "employee_id" : { "$numberInt" : "5" }, "name" : "Eve", "manager_id" : { "$numberInt" : "2" }, "email" : "eve@example.com" } ] } + { "_id" : { "$numberInt" : "2" }, "employee_id" : { "$numberInt" : "2" }, "name" : "Bob", "manager_id" : { "$numberInt" : "1" }, "email" : "bob@example.com", "subordinates" : [ { "_id" : { "$numberInt" : "4" }, "employee_id" : { "$numberInt" : "4" }, "name" : "David", "manager_id" : { "$numberInt" : "2" }, "email" : "david@example.com" }, { "_id" : { "$numberInt" : "5" }, "employee_id" : { "$numberInt" : "5" }, "name" : "Eve", "manager_id" : { "$numberInt" : "2" }, "email" : "eve@example.com" } ] } + + + +(5 rows) + +/*unionWith with redact test case user and employee data*/ +SELECT helio_api.insert_one('db', 'unionWithUsers', '{ "_id": 1, "name": "Alice", "role": "admin", "address": { "city": "New York", "zip": "10001" } }', NULL); +NOTICE: creating collection + insert_one +--------------------------------------------------------------------- + { "n" : { "$numberInt" : "1" }, "ok" : { "$numberDouble" : "1.0" } } +(1 row) + +SELECT helio_api.insert_one('db', 'unionWithUsers', '{ "_id": 2, "name": "Bob", "role": "user", "address": { "city": "Los Angeles", "zip": "90001" } }', NULL); + insert_one +--------------------------------------------------------------------- + { "n" : { "$numberInt" : "1" }, "ok" : { "$numberDouble" : "1.0" } } +(1 row) + +SELECT helio_api.insert_one('db', 'unionWithEmployees', '{ "_id": 101, "name": "Charlie", "role": "admin", "department": "HR", "address": { "city": "San Francisco", "zip": "94101" } }', NULL); +NOTICE: creating collection + insert_one +--------------------------------------------------------------------- + { "n" : { "$numberInt" : "1" }, "ok" : { "$numberDouble" : "1.0" } } +(1 row) + +SELECT helio_api.insert_one('db', 'unionWithEmployees', '{ "_id": 102, "name": "David", "role": "user", "department": "IT", "address": { "city": "Chicago", "zip": "60601" } }', NULL); + insert_one +--------------------------------------------------------------------- + { "n" : { "$numberInt" : "1" }, "ok" : { "$numberDouble" : "1.0" } } +(1 row) + +SELECT document FROM bson_aggregation_pipeline('db', '{ "aggregate": "unionWithUsers", "pipeline": [ { "$unionWith": { "coll": "unionWithEmployees", "pipeline": [ { "$redact": { "$cond": { "if": { "$gt": ["$_id", 101] }, "then": "$$KEEP", "else": "$$PRUNE" } } } ] } } ], "cursor": {} }'); + document +--------------------------------------------------------------------- + { "_id" : { "$numberInt" : "1" }, "name" : "Alice", "role" : "admin", "address" : { "city" : "New York", "zip" : "10001" } } + { "_id" : { "$numberInt" : "2" }, "name" : "Bob", "role" : "user", "address" : { "city" : "Los Angeles", "zip" : "90001" } } + + { "_id" : { "$numberInt" : "102" }, "name" : "David", "role" : "user", "department" : "IT", "address" : { "city" : "Chicago", "zip" : "60601" } } +(4 rows) + +/*negative case*/ +/*redact input as number*/ +SELECT document FROM bson_aggregation_pipeline('db', '{ "aggregate": "redactTest3", "pipeline": [ { "$redact": 1 }], "cursor": {} }'); +ERROR: $redact's parameter must be an expression or string valued as $$KEEP, $$DESCEND, and $$PRUNE, but input as '1'. +/*redact input as string*/ +SELECT document FROM bson_aggregation_pipeline('db', '{ "aggregate": "redactTest3", "pipeline": [ { "$redact": "string" }], "cursor": {} }'); +ERROR: $redact's expression should not return anything aside from the variables $$KEEP, $$DESCEND, and $$PRUNE, but returned '"string"'. +/*redact input as boolean*/ +SELECT document FROM bson_aggregation_pipeline('db', '{ "aggregate": "redactTest3", "pipeline": [ { "$redact": true }], "cursor": {} }'); +ERROR: $redact's parameter must be an expression or string valued as $$KEEP, $$DESCEND, and $$PRUNE, but input as 'true'. +/*redact input system variable not KEEP or PRUNE or DESCEND*/ +SELECT document FROM bson_aggregation_pipeline('db', '{ "aggregate": "redactTest3", "pipeline": [ { "$redact": "$$NOTVALID"}], "cursor": {} }'); +ERROR: Use of undefined variable: NOTVALID +/*redact input as array*/ +SELECT document FROM bson_aggregation_pipeline('db', '{ "aggregate": "redactTest3", "pipeline": [ { "$redact": ["$$KEEP", "$$PRUNE"]} ], "cursor": {} }'); +ERROR: $redact's parameter must be an expression or string valued as $$KEEP, $$DESCEND, and $$PRUNE, but input as '[ "$$KEEP", "$$PRUNE" ]'. +/*redact input cond return not KEEP or PRUNE or DESCEND*/ +SELECT document FROM bson_aggregation_pipeline('db', '{ "aggregate": "redactTest3", "pipeline": [ { "$redact": { "$cond": {"if": {"$eq": ["$level", 1]}, "then": "$$KEEP", "else": "$$NOTVALID"} } } ], "cursor": {} }'); +ERROR: Use of undefined variable: NOTVALID +/*throw exception when $$KEEP $$PRUEN $$DESCEND are used in other stages*/ +SELECT document FROM bson_aggregation_pipeline('db', '{ "aggregate": "redactTest3", "pipeline": [ { "$project": {"filteredField" : "$$PRUNE"} } ], "cursor": {} }'); +ERROR: Use of undefined variable: PRUNE +SELECT document FROM bson_aggregation_pipeline('db', '{ "aggregate": "redactTest3", "pipeline": [ { "$project": {"newField" : "$$DESCEND"} } ], "cursor": {} }'); +ERROR: Use of undefined variable: DESCEND +SELECT document FROM bson_aggregation_pipeline('db', '{ "aggregate": "redactTest3", "pipeline": [ { "$project": {"newField" :{ "$add":["$$KEEP",1]} } } ], "cursor": {} }'); +ERROR: Use of undefined variable: KEEP +SELECT document FROM bson_aggregation_pipeline('db', '{ "aggregate": "redactTest3", "pipeline": [ { "$addFields": {"newField" : "$$DESCEND"} } ], "cursor": {} }'); +ERROR: Use of undefined variable: DESCEND +/*EXPLAIN*/ +EXPLAIN (VERBOSE ON, COSTS OFF) SELECT document FROM helio_api_catalog.bson_aggregation_pipeline('db', '{ "aggregate": "redactTest3", "pipeline": [ { "$redact": "$$KEEP" } ] }'); + QUERY PLAN +--------------------------------------------------------------------- + Custom Scan (Citus Adaptive) + Output: remote_scan.document + Task Count: 1 + Tasks Shown: All + -> Task + Query: SELECT helio_api_internal.bson_dollar_redact(document, '{ }'::helio_core.bson, '$$KEEP'::text, '{ }'::helio_core.bson) AS document FROM helio_data.documents_51502_5150036 collection WHERE (shard_key_value OPERATOR(pg_catalog.=) '51502'::bigint) + Node: host=localhost port=58070 dbname=regression + -> Bitmap Heap Scan on helio_data.documents_51502_5150036 collection + Output: helio_api_internal.bson_dollar_redact(document, '{ }'::helio_core.bson, '$$KEEP'::text, '{ }'::helio_core.bson) + Recheck Cond: (collection.shard_key_value = '51502'::bigint) + -> Bitmap Index Scan on _id_ + Index Cond: (collection.shard_key_value = '51502'::bigint) +(12 rows) + +EXPLAIN (VERBOSE ON, COSTS OFF) SELECT document FROM helio_api_catalog.bson_aggregation_pipeline('db', '{ "aggregate": "redactTest3", "pipeline": [ { "$redact": { "$cond": {"if": {"$eq": ["$level", 1]}, "then": "$$KEEP", "else": "$$PRUNE"} } } ] }'); + QUERY PLAN +--------------------------------------------------------------------- + Custom Scan (Citus Adaptive) + Output: remote_scan.document + Task Count: 1 + Tasks Shown: All + -> Task + Query: SELECT helio_api_internal.bson_dollar_redact(document, '{ "$cond" : { "if" : { "$eq" : [ "$level", { "$numberInt" : "1" } ] }, "then" : "$$KEEP", "else" : "$$PRUNE" } }'::helio_core.bson, ''::text, '{ }'::helio_core.bson) AS document FROM helio_data.documents_51502_5150036 collection WHERE (shard_key_value OPERATOR(pg_catalog.=) '51502'::bigint) + Node: host=localhost port=58070 dbname=regression + -> Bitmap Heap Scan on helio_data.documents_51502_5150036 collection + Output: helio_api_internal.bson_dollar_redact(document, '{ "$cond" : { "if" : { "$eq" : [ "$level", { "$numberInt" : "1" } ] }, "then" : "$$KEEP", "else" : "$$PRUNE" } }'::helio_core.bson, ''::text, '{ }'::helio_core.bson) + Recheck Cond: (collection.shard_key_value = '51502'::bigint) + -> Bitmap Index Scan on _id_ + Index Cond: (collection.shard_key_value = '51502'::bigint) +(12 rows) + +/*sharded collection*/ +SELECT shard_collection('db', 'redactTest3', '{ "amount": "hashed" }', false); + shard_collection +--------------------------------------------------------------------- + +(1 row) + +/*positive cases:*/ +SELECT document FROM bson_aggregation_pipeline('db', '{ "aggregate": "redactTest3", "pipeline": [ { "$redact": { "$cond": [{"$lte": ["$level", 1]}, "$$KEEP", "$$PRUNE"] } } ], "cursor": {} }'); + document +--------------------------------------------------------------------- + { "_id" : { "$numberInt" : "1" }, "level" : { "$numberInt" : "1" }, "a" : { "level" : { "$numberInt" : "1" }, "b" : { "$numberInt" : "1" } }, "c" : { "level" : { "$numberInt" : "1" }, "d" : { "$numberInt" : "1" } } } + + +(3 rows) + +SELECT document FROM bson_aggregation_pipeline('db', '{ "aggregate": "redactTest3", "pipeline": [ { "$redact": { "$cond": [{"$lte": ["$level", 2]}, "$$KEEP", "$$PRUNE"] } } ], "cursor": {} }'); + document +--------------------------------------------------------------------- + { "_id" : { "$numberInt" : "1" }, "level" : { "$numberInt" : "1" }, "a" : { "level" : { "$numberInt" : "1" }, "b" : { "$numberInt" : "1" } }, "c" : { "level" : { "$numberInt" : "1" }, "d" : { "$numberInt" : "1" } } } + { "_id" : { "$numberInt" : "2" }, "level" : { "$numberInt" : "2" }, "a" : { "level" : { "$numberInt" : "2" }, "b" : { "$numberInt" : "2" } }, "c" : { "level" : { "$numberInt" : "2" }, "d" : { "$numberInt" : "2" } } } + +(3 rows) + +SELECT document FROM bson_aggregation_pipeline('db', '{ "aggregate": "redactTest3", "pipeline": [ { "$redact": { "$cond": [{"$lte": ["$level", 3]}, "$$KEEP", "$$PRUNE"] } } ], "cursor": {} }'); + document +--------------------------------------------------------------------- + { "_id" : { "$numberInt" : "1" }, "level" : { "$numberInt" : "1" }, "a" : { "level" : { "$numberInt" : "1" }, "b" : { "$numberInt" : "1" } }, "c" : { "level" : { "$numberInt" : "1" }, "d" : { "$numberInt" : "1" } } } + { "_id" : { "$numberInt" : "2" }, "level" : { "$numberInt" : "2" }, "a" : { "level" : { "$numberInt" : "2" }, "b" : { "$numberInt" : "2" } }, "c" : { "level" : { "$numberInt" : "2" }, "d" : { "$numberInt" : "2" } } } + { "_id" : { "$numberInt" : "3" }, "level" : { "$numberInt" : "3" }, "a" : { "level" : { "$numberInt" : "3" }, "b" : { "$numberInt" : "3" } }, "c" : { "level" : { "$numberInt" : "3" }, "d" : { "$numberInt" : "3" } } } +(3 rows) + +/*test directly systemvariable*/ +SELECT document FROM bson_aggregation_pipeline('db', '{ "aggregate": "redactTest3", "pipeline": [ { "$redact": "$$KEEP" }], "cursor": {} }'); + document +--------------------------------------------------------------------- + { "_id" : { "$numberInt" : "1" }, "level" : { "$numberInt" : "1" }, "a" : { "level" : { "$numberInt" : "1" }, "b" : { "$numberInt" : "1" } }, "c" : { "level" : { "$numberInt" : "1" }, "d" : { "$numberInt" : "1" } } } + { "_id" : { "$numberInt" : "2" }, "level" : { "$numberInt" : "2" }, "a" : { "level" : { "$numberInt" : "2" }, "b" : { "$numberInt" : "2" } }, "c" : { "level" : { "$numberInt" : "2" }, "d" : { "$numberInt" : "2" } } } + { "_id" : { "$numberInt" : "3" }, "level" : { "$numberInt" : "3" }, "a" : { "level" : { "$numberInt" : "3" }, "b" : { "$numberInt" : "3" } }, "c" : { "level" : { "$numberInt" : "3" }, "d" : { "$numberInt" : "3" } } } +(3 rows) + +SELECT document FROM bson_aggregation_pipeline('db', '{ "aggregate": "redactTest3", "pipeline": [ { "$redact": "$$PRUNE"}], "cursor": {} }'); + document +--------------------------------------------------------------------- + + + +(3 rows) + +SELECT document FROM bson_aggregation_pipeline('db', '{ "aggregate": "redactTest3", "pipeline": [ { "$redact": "$$DESCEND"}], "cursor": {} }'); + document +--------------------------------------------------------------------- + { "_id" : { "$numberInt" : "1" }, "level" : { "$numberInt" : "1" }, "a" : { "level" : { "$numberInt" : "1" }, "b" : { "$numberInt" : "1" } }, "c" : { "level" : { "$numberInt" : "1" }, "d" : { "$numberInt" : "1" } } } + { "_id" : { "$numberInt" : "2" }, "level" : { "$numberInt" : "2" }, "a" : { "level" : { "$numberInt" : "2" }, "b" : { "$numberInt" : "2" } }, "c" : { "level" : { "$numberInt" : "2" }, "d" : { "$numberInt" : "2" } } } + { "_id" : { "$numberInt" : "3" }, "level" : { "$numberInt" : "3" }, "a" : { "level" : { "$numberInt" : "3" }, "b" : { "$numberInt" : "3" } }, "c" : { "level" : { "$numberInt" : "3" }, "d" : { "$numberInt" : "3" } } } +(3 rows) + +/*EXPLAIN*/ +EXPLAIN (VERBOSE ON, COSTS OFF) SELECT document FROM helio_api_catalog.bson_aggregation_pipeline('db', '{ "aggregate": "redactTest3", "pipeline": [ { "$redact": "$$KEEP" } ] }'); + QUERY PLAN +--------------------------------------------------------------------- + Custom Scan (Citus Adaptive) + Output: remote_scan.document + Task Count: 8 + Tasks Shown: One of 8 + -> Task + Query: SELECT helio_api_internal.bson_dollar_redact(document, '{ }'::helio_core.bson, '$$KEEP'::text, '{ }'::helio_core.bson) AS document FROM helio_data.documents_51502_5150160 collection WHERE true + Node: host=localhost port=58070 dbname=regression + -> Seq Scan on helio_data.documents_51502_5150160 collection + Output: helio_api_internal.bson_dollar_redact(document, '{ }'::helio_core.bson, '$$KEEP'::text, '{ }'::helio_core.bson) +(9 rows) + +EXPLAIN (VERBOSE ON, COSTS OFF) SELECT document FROM helio_api_catalog.bson_aggregation_pipeline('db', '{ "aggregate": "redactTest3", "pipeline": [ { "$redact": { "$cond": {"if": {"$eq": ["$level", 1]}, "then": "$$KEEP", "else": "$$PRUNE"} } } ] }'); + QUERY PLAN +--------------------------------------------------------------------- + Custom Scan (Citus Adaptive) + Output: remote_scan.document + Task Count: 8 + Tasks Shown: One of 8 + -> Task + Query: SELECT helio_api_internal.bson_dollar_redact(document, '{ "$cond" : { "if" : { "$eq" : [ "$level", { "$numberInt" : "1" } ] }, "then" : "$$KEEP", "else" : "$$PRUNE" } }'::helio_core.bson, ''::text, '{ }'::helio_core.bson) AS document FROM helio_data.documents_51502_5150160 collection WHERE true + Node: host=localhost port=58070 dbname=regression + -> Seq Scan on helio_data.documents_51502_5150160 collection + Output: helio_api_internal.bson_dollar_redact(document, '{ "$cond" : { "if" : { "$eq" : [ "$level", { "$numberInt" : "1" } ] }, "then" : "$$KEEP", "else" : "$$PRUNE" } }'::helio_core.bson, ''::text, '{ }'::helio_core.bson) +(9 rows) + diff --git a/internal/pg_helio_distributed/src/test/regress/sql/bson_aggregation_pipeline_tests_redact.sql b/internal/pg_helio_distributed/src/test/regress/sql/bson_aggregation_pipeline_tests_redact.sql new file mode 100644 index 00000000..21188531 --- /dev/null +++ b/internal/pg_helio_distributed/src/test/regress/sql/bson_aggregation_pipeline_tests_redact.sql @@ -0,0 +1,137 @@ +SET search_path TO helio_core,helio_api,helio_api_catalog,helio_api_internal; + +SET citus.next_shard_id TO 5150000; +SET helio_api.next_collection_id TO 51500; +SET helio_api.next_collection_index_id TO 51500; + +/* Insert data, normal case*/ +SELECT helio_api.insert_one('db','redactTest1','{ "_id": 1, "level": "public", "content": "content 1", "details": { "level": "public", "value": "content 1.1", "moreDetails": { "level": "restricted", "info": "content 1.1.1" } } }', NULL); +SELECT helio_api.insert_one('db','redactTest1','{ "_id": 2, "level": "restricted", "content": "content 2", "details": { "level": "public", "value": "content 2.1", "moreDetails": { "level": "restricted", "info": "content 2.1.1" } } }', NULL); +SELECT helio_api.insert_one('db','redactTest1','{ "_id": 3, "level": "public", "content": "content 3", "details": { "level": "restricted", "value": "content 3.1", "moreDetails": { "level": "public", "info": "content 3.1.1" } } }', NULL); +SELECT helio_api.insert_one('db','redactTest1','{ "_id": 4, "content": "content 4", "details": { "level": "public", "value": "content 4.1" } }', NULL); +SELECT helio_api.insert_one('db','redactTest1','{ "_id": 5, "level": "public", "content": "content 5", "details": { "level": "public", "value": "content 5.1", "moreDetails": [{ "level": "restricted", "info": "content 5.1.1" }, { "level": "public", "info": "content 5.1.2" }] } }', NULL); + + +SELECT document FROM bson_aggregation_pipeline('db', + '{ "aggregate": "redactTest1", "pipeline": [ { "$redact": { "$cond": { "if": { "$eq": ["$level", "public"] }, "then": "$$KEEP", "else": "$$PRUNE" } } } ], "cursor": {} }'); + +SELECT document FROM bson_aggregation_pipeline('db', + '{ "aggregate": "redactTest1", "pipeline": [ { "$redact": { "$cond": { "if": { "$eq": ["$level", "public"] }, "then": "$$DESCEND", "else": "$$PRUNE" } } } ], "cursor": {} }'); + +/* Insert data, add validation for array-nested subdocument, array of documents, array of arrays, empty document being returned, test DESCEND and PRUNE*/ +SELECT helio_api.insert_one('db','redactTest2','{ "_id": 1, "level": 1, "a": { "level": 2, "b": { "level": 4, "c": { "level": 1, "d": 8 } } }, "e": 20 }', NULL); +SELECT helio_api.insert_one('db','redactTest2','{ "_id": 2, "level": 4, "a": { "level": 3, "b": [{ "level": 1, "e": 4 }] } }', NULL); +SELECT helio_api.insert_one('db','redactTest2','{ "_id": 3, "level": 2, "a": { "b": { "level": 3, "n": 12 } } }', NULL); +SELECT helio_api.insert_one('db','redactTest2','{ "_id": 4, "level": 3, "a": [{ "level": 5, "b": 20 }] }', NULL); +SELECT helio_api.insert_one('db','redactTest2','{ "_id": 5, "level": 3, "b": { "level": 3, "d": [ { "level": 1, "e": 4 }, { "level": 5, "g": 9 }, [{ "level": 1, "r": 11 }, 52, 42, 75, { "level": 5, "s": 3 }]] } }', NULL); + +SELECT document FROM bson_aggregation_pipeline('db', '{ "aggregate": "redactTest2", "pipeline": [ { "$redact": { "$cond": [{"$lte": ["$level", 1]}, "$$DESCEND", "$$PRUNE"] } } ], "cursor": {} }'); +SELECT document FROM bson_aggregation_pipeline('db', '{ "aggregate": "redactTest2", "pipeline": [ { "$redact": { "$cond": [{"$lte": ["$level", 2]}, "$$DESCEND", "$$PRUNE"] } } ], "cursor": {} }'); +SELECT document FROM bson_aggregation_pipeline('db', '{ "aggregate": "redactTest2", "pipeline": [ { "$redact": { "$cond": [{"$lte": ["$level", 3]}, "$$DESCEND", "$$PRUNE"] } } ], "cursor": {} }'); +SELECT document FROM bson_aggregation_pipeline('db', '{ "aggregate": "redactTest2", "pipeline": [ { "$redact": { "$cond": [{"$lte": ["$level", 4]}, "$$DESCEND", "$$PRUNE"] } } ], "cursor": {} }'); +SELECT document FROM bson_aggregation_pipeline('db', '{ "aggregate": "redactTest2", "pipeline": [ { "$redact": { "$cond": [{"$lte": ["$level", 5]}, "$$DESCEND", "$$PRUNE"] } } ], "cursor": {} }'); +SELECT document FROM bson_aggregation_pipeline('db', '{ "aggregate": "redactTest2", "pipeline": [ { "$redact": { "$cond": [{"$lte": ["$level", 5]}, { "$literal" :"$$DESCEND"}, "$$PRUNE"] } } ], "cursor": {} }'); + +/* Insert data, test KEEP*/ +SELECT helio_api.insert_one('db','redactTest3','{ "_id": 1, "level": 1, "a": { "level": 1, "b": 1 }, "c": { "level": 1, "d": 1 }}', NULL); +SELECT helio_api.insert_one('db','redactTest3','{ "_id": 2, "level": 2, "a": { "level": 2, "b": 2 }, "c": { "level": 2, "d": 2 }}', NULL); +SELECT helio_api.insert_one('db','redactTest3','{ "_id": 3, "level": 3, "a": { "level": 3, "b": 3 }, "c": { "level": 3, "d": 3 }}', NULL); + +SELECT document FROM bson_aggregation_pipeline('db', '{ "aggregate": "redactTest3", "pipeline": [ { "$redact": { "$cond": [{"$lte": ["$level", 1]}, "$$KEEP", "$$PRUNE"] } } ], "cursor": {} }'); +SELECT document FROM bson_aggregation_pipeline('db', '{ "aggregate": "redactTest3", "pipeline": [ { "$redact": { "$cond": [{"$lte": ["$level", 2]}, "$$KEEP", "$$PRUNE"] } } ], "cursor": {} }'); +SELECT document FROM bson_aggregation_pipeline('db', '{ "aggregate": "redactTest3", "pipeline": [ { "$redact": { "$cond": [{"$lte": ["$level", 3]}, "$$KEEP", "$$PRUNE"] } } ], "cursor": {} }'); + +/*test directly systemvariable*/ +SELECT document FROM bson_aggregation_pipeline('db', '{ "aggregate": "redactTest3", "pipeline": [ { "$redact": "$$KEEP" }], "cursor": {} }'); +SELECT document FROM bson_aggregation_pipeline('db', '{ "aggregate": "redactTest3", "pipeline": [ { "$redact": "$$PRUNE"}], "cursor": {} }'); +SELECT document FROM bson_aggregation_pipeline('db', '{ "aggregate": "redactTest3", "pipeline": [ { "$redact": "$$DESCEND"}], "cursor": {} }'); + +/*switch case*/ +SELECT helio_api.insert_one('db','redactTestSwitch','{ "_id": 1, "title": "Document 1", "classification": "confidential", "content": "This is confidential content.", "metadata": { "author": "Alice", "revision": 3 } }', NULL); +SELECT helio_api.insert_one('db','redactTestSwitch','{ "_id": 2, "title": "Document 2", "classification": "public", "content": "This is public content.", "metadata": { "author": "Bob", "revision": 1 } }', NULL); +SELECT helio_api.insert_one('db','redactTestSwitch','{ "_id": 3, "title": "Document 3", "classification": "restricted", "content": "This content is restricted.", "metadata": { "author": "Charlie", "revision": 2 } }', NULL); + +SELECT document FROM bson_aggregation_pipeline('db', '{ "aggregate": "redactTestSwitch", "pipeline": [ { "$redact": { "$switch": { "branches": [ { "case": { "$eq": ["$classification", "confidential"] }, "then": "$$PRUNE" }, { "case": { "$eq": ["$classification", "restricted"] }, "then": { "$cond": { "if": { "$eq": ["$content", null] }, "then": "$$KEEP", "else": "$$PRUNE" } } }], "default": "$$KEEP" } } }], "cursor": {} }'); + +/*$lookup $let and $redact example*/ +SELECT helio_api.insert_one('db','redactUsers','{ "_id": 1, "name": "Alice"}', NULL); +SELECT helio_api.insert_one('db','redactUsers','{ "_id": 2, "name": "Bob"}', NULL); +SELECT helio_api.insert_one('db','redactUsers','{ "_id": 3, "name": "Charlie"}', NULL); + +SELECT helio_api.insert_one('db','redactOrders','{ "_id": 1, "user_id": 1, "order_amount":150, "status": "completed"}', NULL); +SELECT helio_api.insert_one('db','redactOrders','{ "_id": 2, "user_id": 1, "order_amount":200, "status": "pending"}', NULL); +SELECT helio_api.insert_one('db','redactOrders','{ "_id": 3, "user_id": 2, "order_amount":500, "status": "completed"}', NULL); +SELECT helio_api.insert_one('db','redactOrders','{ "_id": 4, "user_id": 2, "order_amount":50, "status": "completed"}', NULL); +SELECT helio_api.insert_one('db','redactOrders','{ "_id": 5, "user_id": 3, "order_amount":300, "status": "pending"}', NULL); + +/* $redact with $let*/ +SELECT document FROM bson_aggregation_pipeline('db', '{ "aggregate": "redactUsers", "pipeline": [ { "$lookup": { "from": "redactOrders", "localField": "_id", "foreignField": "user_id", "as": "user_orders", "pipeline": [ { "$redact": { "$cond": { "if": { "$let": { "vars": { "totalAmount": { "$sum": "$$ROOT.order_amount" } }, "in": { "$gt": [ "$$totalAmount", 40 ] } } }, "then": "$$KEEP", "else": "$$PRUNE" } } } ] } } ], "cursor": {} }'); +/* add $let with the same level with $lookup, different variable with $let in $redact*/ +SELECT document FROM bson_aggregation_pipeline('db', '{ "aggregate": "redactUsers", "pipeline": [ { "$lookup": { "from": "redactOrders", "localField": "_id", "foreignField": "user_id", "as": "user_orders", "let": { "user_id": "$_id" }, "pipeline": [ { "$redact": { "$cond": { "if": { "$let": { "vars": { "totalAmount": { "$sum": "$order_amount" } }, "in": { "$gt": [ "$$totalAmount", 40 ] } } }, "then": "$$KEEP", "else": "$$PRUNE" } } } ] } } ], "cursor": {} }'); +/* two level $let has the same variable*/ +SELECT document FROM bson_aggregation_pipeline('db', '{ "aggregate": "redactUsers", "pipeline": [ { "$lookup": { "from": "redactOrders", "localField": "_id", "foreignField": "user_id", "as": "user_orders", "let": { "user_id": "$_id", "totalAmount": { "$sum": "$user_orders.order_amount" } }, "pipeline": [ { "$redact": { "$cond": { "if": { "$let": { "vars": { "totalAmount": { "$sum": "$order_amount" } }, "in": { "$gt": [ "$$totalAmount", 40 ] } } }, "then": "$$KEEP", "else": "$$PRUNE" } } } ] } } ], "cursor": {} }'); +/* redact use top level $let*/ +SELECT document FROM bson_aggregation_pipeline('db', '{ "aggregate": "redactUsers", "pipeline": [ { "$lookup": { "from": "redactOrders", "localField": "_id", "foreignField": "user_id", "as": "user_orders", "let": { "user_id": "$_id" }, "pipeline": [ { "$redact": { "$cond": { "if": { "$let": { "vars": { "totalAmount": { "$sum": "$order_amount" } }, "in": { "$and": [ { "$gt": [ "$$totalAmount", 40 ] }, { "$lt": [ "$$user_id", 2 ] } ] } } }, "then": "$$KEEP", "else": "$$PRUNE" } } } ] } } ], "cursor": {} }'); + +/*facet with redact test case user data*/ +SELECT helio_api.insert_one('db', 'facetUsers', '{ "_id": 1, "name": "Alice", "email": "alice@example.com", "age": 25 }', NULL); +SELECT helio_api.insert_one('db', 'facetUsers', '{ "_id": 2, "name": "Bob", "email": "bob@example.com", "age": 25 }', NULL); +SELECT helio_api.insert_one('db', 'facetUsers', '{ "_id": 3, "name": "Charlie", "email": "charlie@example.com", "age": 30 }', NULL); +/*facet with redact case, one is empty array and the other is not*/ +SELECT document FROM bson_aggregation_pipeline('db', '{ "aggregate": "facetUsers", "pipeline": [ { "$facet": { "ageGroup": [ { "$group": { "_id": "$age", "users": { "$push": "$name" } } } ], "redactEmail": [ { "$redact": { "$cond": { "if": { "$eq": ["$email", null] }, "then": "$$KEEP", "else": "$$PRUNE" } } } ] } } ], "cursor": {} }'); +SELECT document FROM bson_aggregation_pipeline('db', '{ "aggregate": "facetUsers", "pipeline": [ { "$facet": { "ageGroup": [ { "$group": { "_id": "$age", "users": { "$push": "$name" } } } ], "redactEmail": [ { "$redact": { "$cond": { "if": { "$eq": ["$email", "alice@example.com"] }, "then": "$$KEEP", "else": "$$PRUNE" } } } ] } } ], "cursor": {} }'); + +/*graphLookup with redact test case employee data*/ +SELECT helio_api.insert_one('db', 'graphLookupEmployee', '{ "_id": 1, "employee_id": 1, "name": "Alice", "manager_id": null, "email": "alice@example.com" }', NULL); +SELECT helio_api.insert_one('db', 'graphLookupEmployee', '{ "_id": 2, "employee_id": 2, "name": "Bob", "manager_id": 1, "email": "bob@example.com" }', NULL); +SELECT helio_api.insert_one('db', 'graphLookupEmployee', '{ "_id": 3, "employee_id": 3, "name": "Charlie", "manager_id": 1, "email": "charlie@example.com" }', NULL); +SELECT helio_api.insert_one('db', 'graphLookupEmployee', '{ "_id": 4, "employee_id": 4, "name": "David", "manager_id": 2, "email": "david@example.com" }', NULL); +SELECT helio_api.insert_one('db', 'graphLookupEmployee', '{ "_id": 5, "employee_id": 5, "name": "Eve", "manager_id": 2, "email": "eve@example.com" }', NULL); +/*graphLookup with redact test case, prune employee do not have subordinates*/ +SELECT document FROM bson_aggregation_pipeline('db', '{ "aggregate": "graphLookupEmployee", "pipeline": [ { "$graphLookup": { "from": "graphLookupEmployee", "startWith": "$employee_id", "connectFromField": "employee_id", "connectToField": "manager_id", "as": "subordinates" } }, { "$redact": { "$cond": { "if": { "$eq": [{ "$size": "$subordinates" }, 0] }, "then": "$$PRUNE", "else": "$$KEEP" } } } ], "cursor": {} }'); + +/*unionWith with redact test case user and employee data*/ +SELECT helio_api.insert_one('db', 'unionWithUsers', '{ "_id": 1, "name": "Alice", "role": "admin", "address": { "city": "New York", "zip": "10001" } }', NULL); +SELECT helio_api.insert_one('db', 'unionWithUsers', '{ "_id": 2, "name": "Bob", "role": "user", "address": { "city": "Los Angeles", "zip": "90001" } }', NULL); +SELECT helio_api.insert_one('db', 'unionWithEmployees', '{ "_id": 101, "name": "Charlie", "role": "admin", "department": "HR", "address": { "city": "San Francisco", "zip": "94101" } }', NULL); +SELECT helio_api.insert_one('db', 'unionWithEmployees', '{ "_id": 102, "name": "David", "role": "user", "department": "IT", "address": { "city": "Chicago", "zip": "60601" } }', NULL); +SELECT document FROM bson_aggregation_pipeline('db', '{ "aggregate": "unionWithUsers", "pipeline": [ { "$unionWith": { "coll": "unionWithEmployees", "pipeline": [ { "$redact": { "$cond": { "if": { "$gt": ["$_id", 101] }, "then": "$$KEEP", "else": "$$PRUNE" } } } ] } } ], "cursor": {} }'); + +/*negative case*/ +/*redact input as number*/ +SELECT document FROM bson_aggregation_pipeline('db', '{ "aggregate": "redactTest3", "pipeline": [ { "$redact": 1 }], "cursor": {} }'); +/*redact input as string*/ +SELECT document FROM bson_aggregation_pipeline('db', '{ "aggregate": "redactTest3", "pipeline": [ { "$redact": "string" }], "cursor": {} }'); +/*redact input as boolean*/ +SELECT document FROM bson_aggregation_pipeline('db', '{ "aggregate": "redactTest3", "pipeline": [ { "$redact": true }], "cursor": {} }'); +/*redact input system variable not KEEP or PRUNE or DESCEND*/ +SELECT document FROM bson_aggregation_pipeline('db', '{ "aggregate": "redactTest3", "pipeline": [ { "$redact": "$$NOTVALID"}], "cursor": {} }'); +/*redact input as array*/ +SELECT document FROM bson_aggregation_pipeline('db', '{ "aggregate": "redactTest3", "pipeline": [ { "$redact": ["$$KEEP", "$$PRUNE"]} ], "cursor": {} }'); +/*redact input cond return not KEEP or PRUNE or DESCEND*/ +SELECT document FROM bson_aggregation_pipeline('db', '{ "aggregate": "redactTest3", "pipeline": [ { "$redact": { "$cond": {"if": {"$eq": ["$level", 1]}, "then": "$$KEEP", "else": "$$NOTVALID"} } } ], "cursor": {} }'); +/*throw exception when $$KEEP $$PRUEN $$DESCEND are used in other stages*/ +SELECT document FROM bson_aggregation_pipeline('db', '{ "aggregate": "redactTest3", "pipeline": [ { "$project": {"filteredField" : "$$PRUNE"} } ], "cursor": {} }'); +SELECT document FROM bson_aggregation_pipeline('db', '{ "aggregate": "redactTest3", "pipeline": [ { "$project": {"newField" : "$$DESCEND"} } ], "cursor": {} }'); +SELECT document FROM bson_aggregation_pipeline('db', '{ "aggregate": "redactTest3", "pipeline": [ { "$project": {"newField" :{ "$add":["$$KEEP",1]} } } ], "cursor": {} }'); +SELECT document FROM bson_aggregation_pipeline('db', '{ "aggregate": "redactTest3", "pipeline": [ { "$addFields": {"newField" : "$$DESCEND"} } ], "cursor": {} }'); + +/*EXPLAIN*/ +EXPLAIN (VERBOSE ON, COSTS OFF) SELECT document FROM helio_api_catalog.bson_aggregation_pipeline('db', '{ "aggregate": "redactTest3", "pipeline": [ { "$redact": "$$KEEP" } ] }'); +EXPLAIN (VERBOSE ON, COSTS OFF) SELECT document FROM helio_api_catalog.bson_aggregation_pipeline('db', '{ "aggregate": "redactTest3", "pipeline": [ { "$redact": { "$cond": {"if": {"$eq": ["$level", 1]}, "then": "$$KEEP", "else": "$$PRUNE"} } } ] }'); + +/*sharded collection*/ +SELECT shard_collection('db', 'redactTest3', '{ "amount": "hashed" }', false); +/*positive cases:*/ +SELECT document FROM bson_aggregation_pipeline('db', '{ "aggregate": "redactTest3", "pipeline": [ { "$redact": { "$cond": [{"$lte": ["$level", 1]}, "$$KEEP", "$$PRUNE"] } } ], "cursor": {} }'); +SELECT document FROM bson_aggregation_pipeline('db', '{ "aggregate": "redactTest3", "pipeline": [ { "$redact": { "$cond": [{"$lte": ["$level", 2]}, "$$KEEP", "$$PRUNE"] } } ], "cursor": {} }'); +SELECT document FROM bson_aggregation_pipeline('db', '{ "aggregate": "redactTest3", "pipeline": [ { "$redact": { "$cond": [{"$lte": ["$level", 3]}, "$$KEEP", "$$PRUNE"] } } ], "cursor": {} }'); + +/*test directly systemvariable*/ +SELECT document FROM bson_aggregation_pipeline('db', '{ "aggregate": "redactTest3", "pipeline": [ { "$redact": "$$KEEP" }], "cursor": {} }'); +SELECT document FROM bson_aggregation_pipeline('db', '{ "aggregate": "redactTest3", "pipeline": [ { "$redact": "$$PRUNE"}], "cursor": {} }'); +SELECT document FROM bson_aggregation_pipeline('db', '{ "aggregate": "redactTest3", "pipeline": [ { "$redact": "$$DESCEND"}], "cursor": {} }'); + +/*EXPLAIN*/ +EXPLAIN (VERBOSE ON, COSTS OFF) SELECT document FROM helio_api_catalog.bson_aggregation_pipeline('db', '{ "aggregate": "redactTest3", "pipeline": [ { "$redact": "$$KEEP" } ] }'); +EXPLAIN (VERBOSE ON, COSTS OFF) SELECT document FROM helio_api_catalog.bson_aggregation_pipeline('db', '{ "aggregate": "redactTest3", "pipeline": [ { "$redact": { "$cond": {"if": {"$eq": ["$level", 1]}, "then": "$$KEEP", "else": "$$PRUNE"} } } ] }'); diff --git a/mongoerrors.csv b/mongoerrors.csv index 5de339b5..e47d24ae 100644 --- a/mongoerrors.csv +++ b/mongoerrors.csv @@ -113,6 +113,7 @@ MongoError,ErrorName 17047,Location17047 17048,Location17048 17049,Location17049 +17053,Location17053 17080,DollarCondMissingIfParameter 17081,DollarCondMissingThenParameter 17082,DollarCondMissingElseParameter diff --git a/pg_documentdb/include/aggregation/bson_aggregation_pipeline_private.h b/pg_documentdb/include/aggregation/bson_aggregation_pipeline_private.h index 5e58e996..56adf502 100644 --- a/pg_documentdb/include/aggregation/bson_aggregation_pipeline_private.h +++ b/pg_documentdb/include/aggregation/bson_aggregation_pipeline_private.h @@ -19,6 +19,17 @@ #ifndef BSON_AGGREGATION_PIPELINE_PRIVATE_H #define BSON_AGGREGATION_PIPELINE_PRIVATE_H +/* + * for nested stage, use this to record its parent stage name + */ +typedef enum ParentStageName +{ + ParentStageName_NOPARENT = 0, + ParentStageName_LOOKUP, + ParentStageName_FACET, + ParentStageName_UNIONWITH, + ParentStageName_INVERSEMATCH, +} ParentStageName; /* * Shared context during aggregation pipeline build phase. @@ -102,6 +113,9 @@ typedef struct /* Whether or not it's a point read query */ bool isPointReadQuery; + + /*Parent Stage Name*/ + ParentStageName parentStageName; } AggregationPipelineBuildContext; diff --git a/pg_documentdb/include/metadata/metadata_cache.h b/pg_documentdb/include/metadata/metadata_cache.h index 765835da..6774d194 100644 --- a/pg_documentdb/include/metadata/metadata_cache.h +++ b/pg_documentdb/include/metadata/metadata_cache.h @@ -280,6 +280,7 @@ Oid BsonDollarProjectGeonearFunctionOid(void); Oid BsonDollarInverseMatchFunctionId(void); Oid BsonDollarProjectFunctionOid(void); Oid BsonDollarProjectWithLetFunctionOid(void); +Oid BsonDollarRedactWithLetFunctionOid(void); Oid BsonDollarMergeHandleWhenMatchedFunctionOid(void); Oid BsonDollarMergeAddObjectIdFunctionOid(void); Oid BsonDollarMergeGenerateObjectId(void); diff --git a/pg_documentdb/include/operators/bson_expression.h b/pg_documentdb/include/operators/bson_expression.h index 471cdb9f..c375b5e2 100644 --- a/pg_documentdb/include/operators/bson_expression.h +++ b/pg_documentdb/include/operators/bson_expression.h @@ -205,6 +205,9 @@ typedef struct ParseAggregationExpressionContext { /* Function that is called after every aggregation expression is parsed. */ ValidateParsedAggregationExpression validateParsedExpressionFunc; + + /* Only $redact is allowed to use the $$KEEP,$$PRUNE, and $$DESCEND system variables. Use this boolean to prevent other operators from using these three variables.*/ + bool allowRedactVariables; } ParseAggregationExpressionContext; diff --git a/pg_documentdb/include/utils/feature_counter.h b/pg_documentdb/include/utils/feature_counter.h index 87eca367..89cb7dd7 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 255 +#define MAX_FEATURE_COUNT 256 /* Internal features that are not exposed */ #define INTERNAL_FEATURE_TYPE MAX_FEATURE_COUNT @@ -266,6 +266,7 @@ typedef enum FEATURE_STAGE_OUT, FEATURE_STAGE_PROJECT, FEATURE_STAGE_PROJECT_FIND, + FEATURE_STAGE_REDACT, FEATURE_STAGE_REPLACE_ROOT, FEATURE_STAGE_REPLACE_WITH, FEATURE_STAGE_SAMPLE, diff --git a/pg_documentdb/src/aggregation/bson_aggregation_nested_pipeline.c b/pg_documentdb/src/aggregation/bson_aggregation_nested_pipeline.c index add2e7bb..f6436942 100644 --- a/pg_documentdb/src/aggregation/bson_aggregation_nested_pipeline.c +++ b/pg_documentdb/src/aggregation/bson_aggregation_nested_pipeline.c @@ -687,6 +687,7 @@ CreateInverseMatchFromCollectionQuery(InverseMatchArgs *inverseMatchArgs, subPipelineContext.nestedPipelineLevel = context->nestedPipelineLevel + 1; subPipelineContext.databaseNameDatum = context->databaseNameDatum; subPipelineContext.variableSpec = context->variableSpec; + subPipelineContext.parentStageName = ParentStageName_INVERSEMATCH; strncpy((char *) subPipelineContext.collationString, context->collationString, MAX_ICU_COLLATION_LENGTH); @@ -964,6 +965,7 @@ HandleUnionWith(const bson_value_t *existingValue, Query *query, subPipelineContext.nestedPipelineLevel = context->nestedPipelineLevel + 1; subPipelineContext.databaseNameDatum = context->databaseNameDatum; subPipelineContext.variableSpec = context->variableSpec; + subPipelineContext.parentStageName = ParentStageName_UNIONWITH; strncpy((char *) subPipelineContext.collationString, context->collationString, MAX_ICU_COLLATION_LENGTH); @@ -980,6 +982,7 @@ HandleUnionWith(const bson_value_t *existingValue, Query *query, subPipelineContext.nestedPipelineLevel = context->nestedPipelineLevel + 1; subPipelineContext.databaseNameDatum = context->databaseNameDatum; subPipelineContext.variableSpec = context->variableSpec; + subPipelineContext.parentStageName = ParentStageName_UNIONWITH; strncpy((char *) subPipelineContext.collationString, context->collationString, MAX_ICU_COLLATION_LENGTH); @@ -1154,6 +1157,7 @@ BuildFacetUnionAllQuery(int numStages, const bson_value_t *facetValue, nestedContext.databaseNameDatum = parentContext->databaseNameDatum; nestedContext.sortSpec = *sortSpec; nestedContext.variableSpec = parentContext->variableSpec; + nestedContext.parentStageName = ParentStageName_FACET; strncpy((char *) nestedContext.collationString, parentContext->collationString, MAX_ICU_COLLATION_LENGTH); @@ -1211,6 +1215,7 @@ BuildFacetUnionAllQuery(int numStages, const bson_value_t *facetValue, nestedContext.databaseNameDatum = parentContext->databaseNameDatum; nestedContext.sortSpec = *sortSpec; nestedContext.variableSpec = parentContext->variableSpec; + nestedContext.parentStageName = ParentStageName_FACET; strncpy((char *) nestedContext.collationString, parentContext->collationString, MAX_ICU_COLLATION_LENGTH); nestedContext.mongoCollection = parentContext->mongoCollection; @@ -1841,6 +1846,7 @@ OptimizeLookup(LookupArgs *lookupArgs, optimizationArgs->rightQueryContext.variableSpec = leftQueryContext->variableSpec; strncpy((char *) optimizationArgs->rightQueryContext.collationString, leftQueryContext->collationString, MAX_ICU_COLLATION_LENGTH); + optimizationArgs->rightQueryContext.parentStageName = ParentStageName_LOOKUP; optimizationArgs->isLookupAgnostic = lookupArgs->from.length == 0; optimizationArgs->isLookupUncorrelated = !lookupArgs->hasLookupMatch; @@ -2506,6 +2512,7 @@ ProcessLookupCoreWithLet(Query *query, AggregationPipelineBuildContext *context, projectorQueryContext.mongoCollection = optimizationArgs.rightQueryContext.mongoCollection; projectorQueryContext.variableSpec = letExpr; + projectorQueryContext.parentStageName = ParentStageName_LOOKUP; strncpy((char *) projectorQueryContext.collationString, context->collationString, MAX_ICU_COLLATION_LENGTH); diff --git a/pg_documentdb/src/aggregation/bson_aggregation_pipeline.c b/pg_documentdb/src/aggregation/bson_aggregation_pipeline.c index ca689b0a..35b30714 100644 --- a/pg_documentdb/src/aggregation/bson_aggregation_pipeline.c +++ b/pg_documentdb/src/aggregation/bson_aggregation_pipeline.c @@ -245,6 +245,8 @@ static Query * HandleProject(const bson_value_t *existingValue, Query *query, static Query * HandleProjectFind(const bson_value_t *existingValue, const bson_value_t *queryValue, Query *query, AggregationPipelineBuildContext *context); +static Query * HandleRedact(const bson_value_t *existingValue, Query *query, + AggregationPipelineBuildContext *context); static Query * HandleReplaceRoot(const bson_value_t *existingValue, Query *query, AggregationPipelineBuildContext *context); static Query * HandleReplaceWith(const bson_value_t *existingValue, Query *query, @@ -703,12 +705,12 @@ static const AggregationStageDefinition StageDefinitions[] = }, { .stage = "$redact", - .mutateFunc = NULL, + .mutateFunc = &HandleRedact, .requiresPersistentCursor = &RequiresPersistentCursorTrue, .canInlineLookupStageFunc = NULL, .preservesStableSortOrder = true, .canHandleAgnosticQueries = false, - .isProjectTransform = false, + .isProjectTransform = true, .isOutputStage = false, .pipelineCheckFunc = NULL, .allowBaseShardTablePushdown = true, @@ -2895,6 +2897,94 @@ HandleProject(const bson_value_t *existingValue, Query *query, } +/* + * Mutates the query for the $redact stage + */ +static Query * +HandleRedact(const bson_value_t *existingValue, Query *query, + AggregationPipelineBuildContext *context) +{ + ReportFeatureUsage(FEATURE_STAGE_REDACT); + + /* Check if redact feature is available according to version. */ + if (!IsClusterVersionAtleast(DocDB_V0, 24, 0)) + { + ereport(ERROR, (errcode(ERRCODE_DOCUMENTDB_COMMANDNOTSUPPORTED), + errmsg( + "Stage $redact is not supported yet in native pipeline"), + errdetail_log( + "Stage $redact is not supported yet in native pipeline"))); + } + + Const *redactSpec; + Const *redactSpecText; + + if (existingValue->value_type == BSON_TYPE_DOCUMENT) + { + redactSpec = MakeBsonConst(PgbsonInitFromDocumentBsonValue(existingValue)); + redactSpecText = MakeTextConst("", 0); + } + else if (existingValue->value_type == BSON_TYPE_UTF8) + { + redactSpec = MakeBsonConst(PgbsonInitEmpty()); + redactSpecText = MakeTextConst( + existingValue->value.v_utf8.str, existingValue->value.v_utf8.len); + } + else + { + ereport(ERROR, (errcode(ERRCODE_DOCUMENTDB_LOCATION17053), + errmsg( + "$redact's parameter must be an expression or string valued as $$KEEP, $$DESCEND, and $$PRUNE, but input as '%s'.", + BsonValueToJsonForLogging(existingValue)), + errdetail_log( + "$redact's parameter must be an expression or string valued as $$KEEP, $$DESCEND, and $$PRUNE."))); + } + + /* The first projector is the document */ + TargetEntry *firstEntry = linitial(query->targetList); + Expr *currentProjection = firstEntry->expr; + + /* + * There is two kind of $redact parameters: + * a. like "$redact: { $cond: { if: { $eq: ["$level", "public"] }, then: "$$KEEP", else: "$$PRUNE" }" + * existingValue->value_type is BSON_TYPE_DOCUMENT. + * BsonDollarRedactWithLetFunctionOid() takes four parameters, currentProjection, redactSpec, redactSpecText, variableSpec. + * redactSpec is the document and redactSpecText is empty + * b. like "$redact: "$$PRUNE" + * existingValue->value.value_type is BSON_TYPE_UTF8. + * In this case, BsonDollarRedactWithLetFunctionOid() takes four parameters, currentProjection, redactSpec, redactSpecText, variableSpec. + * redactSpec is set to empty document and redactSpecText is the string. + */ + List *args = list_make4(currentProjection, redactSpec, redactSpecText, + context->variableSpec == NULL ? (Expr *) MakeBsonConst( + PgbsonInitEmpty()) : context->variableSpec); + + FuncExpr *resultExpr = makeFuncExpr( + BsonDollarRedactWithLetFunctionOid(), BsonTypeId(), args, InvalidOid, + InvalidOid, COERCE_EXPLICIT_CALL); + + firstEntry->expr = (Expr *) resultExpr; + + /* The following code addresses nested redact handling. + * The behavior of $lookup and $facet with nested redact differs from $unionWith: + * $lookup and $facet result in unexpected null values, use COALESCE to return an empty value instead. + * For $unionWith, it will still return null as redact does. + */ + if (context->nestedPipelineLevel > 0 && context->parentStageName != + ParentStageName_UNIONWITH) + { + CoalesceExpr *coalesceExpr = makeNode(CoalesceExpr); + coalesceExpr->args = list_make2(resultExpr, MakeBsonConst(PgbsonInitEmpty())); + coalesceExpr->coalescetype = BsonTypeId(); + coalesceExpr->coalescecollid = InvalidOid; + + firstEntry->expr = (Expr *) coalesceExpr; + } + + return query; +} + + static Query * HandleProjectFind(const bson_value_t *existingValue, const bson_value_t *queryValue, Query *query, diff --git a/pg_documentdb/src/aggregation/bson_project.c b/pg_documentdb/src/aggregation/bson_project.c index 024336ac..5664b3d1 100644 --- a/pg_documentdb/src/aggregation/bson_project.c +++ b/pg_documentdb/src/aggregation/bson_project.c @@ -83,17 +83,16 @@ typedef struct BsonProjectionQueryState /* - * Cached state for ReplaceRoot. + * Cached state for ReplaceRoot and Redact. */ -typedef struct BsonReplaceRootState +typedef struct BsonReplaceRootRedactState { /* The aggregation expression data */ AggregationExpressionData *expressionData; /* The variable context for let if any */ ExpressionVariableContext *variableContext; -} BsonReplaceRootState; - +} BsonReplaceRootRedactState; /* --------------------------------------------------------- */ /* Forward declaration */ @@ -142,8 +141,10 @@ static pgbson * BsonLookUpGetFilterExpression(pgbson *sourceDocument, static pgbson * BsonLookUpProject(pgbson *sourceDocument, int numMatchedDocuments, Datum *mathedArray, char *matchedDocsFieldName); static void PopulateReplaceRootExpressionDataFromSpec( - BsonReplaceRootState *expressionData, pgbson *pathSpec, pgbson *variableSpec); + BsonReplaceRootRedactState *expressionData, pgbson *pathSpec, pgbson *variableSpec); +static void BuildRedactState(BsonReplaceRootRedactState *redactState, const + bson_value_t *redactValue, pgbson *variableSpec); static void BuildBsonPathTreeForDollarProject(BsonProjectionQueryState *state, BsonProjectionContext *context); static void BuildBsonPathTreeForDollarAddFields(BsonProjectionQueryState *state, @@ -166,6 +167,12 @@ static void PostProcessParseProjectNode(void *state, const StringView *path, bool *hasFieldsForIntermediate); static pgbson * ProjectGeonearDocument(const GeonearDistanceState *state, pgbson *document); +static pgbson * EvaluateRedactDocument(pgbson *document, const + BsonReplaceRootRedactState *state, + bool *shouldPrune); +static void EvaluateRedactArray(const bson_value_t *array, const + BsonReplaceRootRedactState *state, + pgbson_array_writer *array_Writer); static void SetVariableSpec(ExpressionVariableContext **state, pgbson *variableSpec); static inline bool IsBsonDollarProjectFunctionOid(Oid functionOid); static inline bool IsBsonDollarAddFieldsFunctionOid(Oid functionOid); @@ -180,6 +187,7 @@ PG_FUNCTION_INFO_V1(bson_dollar_set); PG_FUNCTION_INFO_V1(bson_dollar_unset); PG_FUNCTION_INFO_V1(bson_dollar_replace_root); PG_FUNCTION_INFO_V1(bson_dollar_merge_documents_at_path); +PG_FUNCTION_INFO_V1(bson_dollar_redact); PG_FUNCTION_INFO_V1(bson_dollar_merge_documents); PG_FUNCTION_INFO_V1(bson_dollar_lookup_expression_eval_merge); PG_FUNCTION_INFO_V1(bson_dollar_lookup_extract_filter_expression); @@ -724,12 +732,12 @@ bson_dollar_replace_root(PG_FUNCTION_ARGS) numArgs = 2; } - BsonReplaceRootState localState = { 0 }; - const BsonReplaceRootState *replaceRootExpression; + BsonReplaceRootRedactState localState = { 0 }; + const BsonReplaceRootRedactState *replaceRootExpression; SetCachedFunctionStateMultiArgs( replaceRootExpression, - BsonReplaceRootState, + BsonReplaceRootRedactState, argPositions, numArgs, PopulateReplaceRootExpressionDataFromSpec, @@ -1069,6 +1077,269 @@ GetProjectionStateForBsonUnset(const bson_value_t *unsetValue, bool forceProject } +/* + * bson_dollar_redact performs a projection with fields visibility controlled by defined conditions. + */ +Datum +bson_dollar_redact(PG_FUNCTION_ARGS) +{ + pgbson *document = PG_GETARG_PGBSON(0); + pgbson *redactSpec = PG_GETARG_PGBSON(1); + char *redactSpecText = text_to_cstring(PG_GETARG_TEXT_PP(2)); + pgbson *variableSpec = PG_GETARG_MAYBE_NULL_PGBSON(3); + + bson_value_t redactValue = { 0 }; + + if (IsPgbsonEmptyDocument(redactSpec) && (strcmp(redactSpecText, "") != 0)) + { + redactValue.value_type = BSON_TYPE_UTF8; + redactValue.value.v_utf8.str = redactSpecText; + redactValue.value.v_utf8.len = strlen(redactSpecText); + } + else + { + redactValue = ConvertPgbsonToBsonValue(redactSpec); + } + + int argPositions[3] = { 1, 2, 3 }; + int numArgs = 3; + + if (variableSpec == NULL) + { + variableSpec = PgbsonInitEmpty(); + } + + const BsonReplaceRootRedactState *redactState; + SetCachedFunctionStateMultiArgs( + redactState, + BsonReplaceRootRedactState, + argPositions, + numArgs, + BuildRedactState, + &redactValue, + variableSpec); + + pgbson *result; + bool shouldPrune = false; + if (redactState == NULL) + { + BsonReplaceRootRedactState newState = { 0 }; + BuildRedactState(&newState, &redactValue, variableSpec); + result = EvaluateRedactDocument(document, &newState, &shouldPrune); + } + else + { + result = EvaluateRedactDocument(document, redactState, &shouldPrune); + } + + if (shouldPrune) + { + PG_RETURN_NULL(); + } + PG_RETURN_POINTER(result); +} + + +/* Parse $redact stage argument and build state. + * { $redact: } + * The argument can be any expression, only need to check evaluation result of expression. + */ +static void +BuildRedactState(BsonReplaceRootRedactState *redactState, const bson_value_t *redactValue, + pgbson *variableSpec) +{ + ParseAggregationExpressionContext context = { allowRedactVariables: true }; + redactState->expressionData = palloc0(sizeof(AggregationExpressionData)); + ParseAggregationExpressionData(redactState->expressionData, redactValue, &context); + + SetVariableSpec(&redactState->variableContext, variableSpec); +} + + +/* + * Given a document and a redact state, evaluate the document with the redact expression in state. + * Recursively evaluate any nested documents or documents in arrays when the result returned is $$DESCEND. + * Set boolean shouldPrune to true if the result returned is $$PRUNE, so that we can go back and prune the document along with its key at upper level. + * see redact.md for more details. + */ +static pgbson * +EvaluateRedactDocument(pgbson *document, const BsonReplaceRootRedactState *state, + bool *shouldPrune) +{ + StringView path = { .string = "", .length = 0 }; + pgbson_writer evaluatedResultWriter; + PgbsonWriterInit(&evaluatedResultWriter); + bool isNullOnEmpty = false; + + if (state->expressionData->kind == AggregationExpressionKind_SystemVariable) + { + switch (state->expressionData->systemVariable.kind) + { + case AggregationExpressionSystemVariableKind_Keep: + case AggregationExpressionSystemVariableKind_Descend: + { + /* include current document to result, and stop process any nest fields. */ + return document; + } + + case AggregationExpressionSystemVariableKind_Prune: + { + /* current document and its key(if available) should be excluded in the result. */ + *shouldPrune = true; + return PgbsonInitEmpty(); + } + + default: + { + ereport(ERROR, (errcode(ERRCODE_DOCUMENTDB_LOCATION17053), + errmsg( + "$redact's expression should not return anything aside from the variables $$KEEP, $$DESCEND, and $$PRUNE, but returned '%s'.", + BsonValueToJsonForLogging( + &(state->expressionData->value))))); + break; + } + } + } + + EvaluateAggregationExpressionDataToWriter(state->expressionData, document, path, + &evaluatedResultWriter, + state->variableContext, + isNullOnEmpty); + + pgbson *evaluatedResult = PgbsonWriterGetPgbson(&evaluatedResultWriter); + pgbsonelement evaluatedResultElement = { 0 }; + PgbsonToSinglePgbsonElement(evaluatedResult, &evaluatedResultElement); + + AggregationExpressionData *parsedValue = palloc0(sizeof(AggregationExpressionData)); + ParseAggregationExpressionContext context = { allowRedactVariables: true }; + ParseAggregationExpressionData(parsedValue, &evaluatedResultElement.bsonValue, + &context); + if (parsedValue->kind == AggregationExpressionKind_SystemVariable) + { + switch (parsedValue->systemVariable.kind) + { + case AggregationExpressionSystemVariableKind_Keep: + { + /* include current document to result, and stop process any nest fields. */ + return document; + } + + case AggregationExpressionSystemVariableKind_Prune: + { + /* current document and its key(if available) should be excluded in the result. */ + *shouldPrune = true; + } + + case AggregationExpressionSystemVariableKind_Descend: + { + /* iterate all fields and find any nested document or arrays to continue evaluation. */ + pgbson_writer writer; + PgbsonWriterInit(&writer); + bson_iter_t docIter; + PgbsonInitIterator(document, &docIter); + while (bson_iter_next(&docIter)) + { + if (BSON_ITER_HOLDS_DOCUMENT(&docIter)) + { + /* recursively evaluate nested document */ + bool shouldPrune = false; + pgbson *subDocument = EvaluateRedactDocument( + PgbsonInitFromDocumentBsonValue(bson_iter_value(&docIter)), + state, &shouldPrune); + if (shouldPrune) + { + /* skip this field, do not write the key and its value. */ + continue; + } + else + { + PgbsonWriterAppendDocument(&writer, bson_iter_key(&docIter), + strlen(bson_iter_key(&docIter)), + subDocument); + } + } + else if (BSON_ITER_HOLDS_ARRAY(&docIter)) + { + /* recursively evaluate nested arrays */ + pgbson_array_writer array_Writer; + PgbsonWriterStartArray(&writer, bson_iter_key(&docIter), + strlen(bson_iter_key(&docIter)), + &array_Writer); + EvaluateRedactArray(bson_iter_value(&docIter), state, + &array_Writer); + PgbsonWriterEndArray(&writer, &array_Writer); + } + else + { + /* write current field to result */ + PgbsonWriterAppendValue(&writer, bson_iter_key(&docIter), strlen( + bson_iter_key(&docIter)), + bson_iter_value(&docIter)); + } + } + pgbson *result = PgbsonWriterGetPgbson(&writer); + return result; + } + + default: + { + break; + } + } + } + + pfree(parsedValue); + ereport(ERROR, (errcode(ERRCODE_DOCUMENTDB_LOCATION17053), + errmsg( + "$redact's expression should not return anything aside from the variables $$KEEP, $$DESCEND, and $$PRUNE, but returned '%s'.", + BsonValueToJsonForLogging(&evaluatedResultElement.bsonValue)))); +} + + +/* + * Handles the projection of an array field for the $redact stage. + * There is a recursive call to EvaluateRedactDocument for nested documents and recursive calls to EvaluateRedactArray for nested arrays. + */ +static void +EvaluateRedactArray(const bson_value_t *array, const BsonReplaceRootRedactState *state, + pgbson_array_writer *array_Writer) +{ + /* recursively evaluate nested documents in array */ + bson_iter_t arrayIter; + BsonValueInitIterator(array, &arrayIter); + + while (bson_iter_next(&arrayIter)) + { + const bson_value_t *arrayElement = bson_iter_value( + &arrayIter); + if (BSON_ITER_HOLDS_DOCUMENT(&arrayIter)) + { + bool shouldPrune = false; + pgbson *nestedDocument = EvaluateRedactDocument( + PgbsonInitFromDocumentBsonValue(arrayElement), state, &shouldPrune); + if (!shouldPrune) + { + PgbsonArrayWriterWriteDocument(array_Writer, + nestedDocument); + } + } + else if (BSON_ITER_HOLDS_ARRAY(&arrayIter)) + { + pgbson_array_writer child_array_writer; + PgbsonArrayWriterStartArray(array_Writer, + &child_array_writer); + EvaluateRedactArray(arrayElement, state, &child_array_writer); + PgbsonArrayWriterEndArray(array_Writer, &child_array_writer); + } + else + { + PgbsonArrayWriterWriteValue(array_Writer, + arrayElement); + } + } +} + + /* * Given a bson document specified by sourceDocument, * applies the transform specified by the BsonProjectionQueryState @@ -2252,7 +2523,7 @@ FilterNodeToWrite(void *state, int currentIndex) /* Populates the aggregation expression data for a replace root stage based on the pathSpec specified to $replaceRoot. */ static void -PopulateReplaceRootExpressionDataFromSpec(BsonReplaceRootState *expressionData, +PopulateReplaceRootExpressionDataFromSpec(BsonReplaceRootRedactState *expressionData, pgbson *pathSpec, pgbson *variableSpec) { bson_iter_t pathSpecIter; diff --git a/pg_documentdb/src/infrastructure/feature_counter.c b/pg_documentdb/src/infrastructure/feature_counter.c index 8347b58c..e69f5e3e 100644 --- a/pg_documentdb/src/infrastructure/feature_counter.c +++ b/pg_documentdb/src/infrastructure/feature_counter.c @@ -280,6 +280,7 @@ static char FeatureMapping[MAX_FEATURE_COUNT][MAX_FEATURE_NAME_LENGTH] = { [FEATURE_STAGE_OUT] = "out", [FEATURE_STAGE_PROJECT] = "project", [FEATURE_STAGE_PROJECT_FIND] = "project_find", + [FEATURE_STAGE_REDACT] = "redact", [FEATURE_STAGE_REPLACE_ROOT] = "replace_root", [FEATURE_STAGE_REPLACE_WITH] = "replace_with", [FEATURE_STAGE_SAMPLE] = "sample", diff --git a/pg_documentdb/src/metadata/metadata_cache.c b/pg_documentdb/src/metadata/metadata_cache.c index 12457ed1..0b53d65a 100644 --- a/pg_documentdb/src/metadata/metadata_cache.c +++ b/pg_documentdb/src/metadata/metadata_cache.c @@ -649,6 +649,9 @@ typedef struct HelioApiOidCacheData /* OID of the bson_dollar_project function */ Oid ApiCatalogBsonDollarProjectFunctionOid; + /* OID of the bson_dollar_redact(bson, bson, text, bson) function */ + Oid ApiInternalBsonDollarRedactWithLetFunctionOid; + /* OID of the bson_dollar_project function with let */ Oid ApiCatalogBsonDollarProjectWithLetFunctionOid; @@ -3114,6 +3117,18 @@ BsonDollarProjectWithLetFunctionOid(void) } +Oid +BsonDollarRedactWithLetFunctionOid(void) +{ + return GetOperatorFunctionIdFourArgs( + &Cache.ApiInternalBsonDollarRedactWithLetFunctionOid, + DocumentDBApiInternalSchemaName, + "bson_dollar_redact", + BsonTypeId(), BsonTypeId(), + TEXTOID, BsonTypeId()); +} + + Oid BsonDollarLookupExpressionEvalMergeOid(void) { diff --git a/pg_documentdb/src/operators/bson_expression.c b/pg_documentdb/src/operators/bson_expression.c index 217a1712..b97e4f51 100644 --- a/pg_documentdb/src/operators/bson_expression.c +++ b/pg_documentdb/src/operators/bson_expression.c @@ -1779,24 +1779,48 @@ ParseAggregationExpressionData(AggregationExpressionData *expressionData, } else if (StringViewEqualsCString(&expressionView, "$$DESCEND")) { - expressionData->kind = AggregationExpressionKind_SystemVariable; - expressionData->systemVariable.kind = - AggregationExpressionSystemVariableKind_Descend; - expressionData->systemVariable.pathSuffix = dottedSuffix; + if (context->allowRedactVariables) + { + expressionData->kind = AggregationExpressionKind_SystemVariable; + expressionData->systemVariable.kind = + AggregationExpressionSystemVariableKind_Descend; + expressionData->systemVariable.pathSuffix = dottedSuffix; + } + else + { + ereport(ERROR, (errcode(ERRCODE_DOCUMENTDB_LOCATION17276), + errmsg("Use of undefined variable: DESCEND"))); + } } else if (StringViewEqualsCString(&expressionView, "$$PRUNE")) { - expressionData->kind = AggregationExpressionKind_SystemVariable; - expressionData->systemVariable.kind = - AggregationExpressionSystemVariableKind_Prune; - expressionData->systemVariable.pathSuffix = dottedSuffix; + if (context->allowRedactVariables) + { + expressionData->kind = AggregationExpressionKind_SystemVariable; + expressionData->systemVariable.kind = + AggregationExpressionSystemVariableKind_Prune; + expressionData->systemVariable.pathSuffix = dottedSuffix; + } + else + { + ereport(ERROR, (errcode(ERRCODE_DOCUMENTDB_LOCATION17276), + errmsg("Use of undefined variable: PRUNE"))); + } } else if (StringViewEqualsCString(&expressionView, "$$KEEP")) { - expressionData->kind = AggregationExpressionKind_SystemVariable; - expressionData->systemVariable.kind = - AggregationExpressionSystemVariableKind_Keep; - expressionData->systemVariable.pathSuffix = dottedSuffix; + if (context->allowRedactVariables) + { + expressionData->kind = AggregationExpressionKind_SystemVariable; + expressionData->systemVariable.kind = + AggregationExpressionSystemVariableKind_Keep; + expressionData->systemVariable.pathSuffix = dottedSuffix; + } + else + { + ereport(ERROR, (errcode(ERRCODE_DOCUMENTDB_LOCATION17276), + errmsg("Use of undefined variable: KEEP"))); + } } else if (StringViewEqualsCString(&expressionView, "$$SEARCH_META")) { @@ -2261,22 +2285,30 @@ EvaluateAggregationExpressionSystemVariable(const AggregationExpressionData *dat return; } + /* $$KEEP $$DESCEND $$PRUNE can only be used by stage $redact and gated by boolean allowRedactVariables. + * Return the variable string as we handle the logics at stage level.*/ case AggregationExpressionSystemVariableKind_Descend: { - ereport(ERROR, (errcode(ERRCODE_DOCUMENTDB_COMMANDNOTSUPPORTED), - errmsg("Variable $$DESCEND not supported yet"))); + variableValue.value_type = BSON_TYPE_UTF8; + variableValue.value.v_utf8.str = "$$DESCEND"; + variableValue.value.v_utf8.len = 9; + break; } case AggregationExpressionSystemVariableKind_Prune: { - ereport(ERROR, (errcode(ERRCODE_DOCUMENTDB_COMMANDNOTSUPPORTED), - errmsg("Variable $$PRUNE not supported yet"))); + variableValue.value_type = BSON_TYPE_UTF8; + variableValue.value.v_utf8.str = "$$PRUNE"; + variableValue.value.v_utf8.len = 7; + break; } case AggregationExpressionSystemVariableKind_Keep: { - ereport(ERROR, (errcode(ERRCODE_DOCUMENTDB_COMMANDNOTSUPPORTED), - errmsg("Variable $$KEEP not supported yet"))); + variableValue.value_type = BSON_TYPE_UTF8; + variableValue.value.v_utf8.str = "$$KEEP"; + variableValue.value.v_utf8.len = 6; + break; } case AggregationExpressionSystemVariableKind_SearchMeta: diff --git a/pg_documentdb_core/include/utils/documentdb_codes.txt b/pg_documentdb_core/include/utils/documentdb_codes.txt index efd65e76..8ff2ca22 100644 --- a/pg_documentdb_core/include/utils/documentdb_codes.txt +++ b/pg_documentdb_core/include/utils/documentdb_codes.txt @@ -497,3 +497,4 @@ Location40229,M00DQ,495 UserCountLimitExceeded,M00DR,496 Location55,M00DS,497 Location40236,M00DT,498 +Location17053,M00DU,499 \ No newline at end of file diff --git a/pg_documentdb_core/include/utils/documentdb_errors.h b/pg_documentdb_core/include/utils/documentdb_errors.h index 9d91dfbd..393f1a2a 100644 --- a/pg_documentdb_core/include/utils/documentdb_errors.h +++ b/pg_documentdb_core/include/utils/documentdb_errors.h @@ -1090,4 +1090,6 @@ typedef int DocumentdbErrorEreportCode; #define ERRCODE_DOCUMENTDB_LOCATION40236 MAKE_SQLSTATE('M', '0', '0', 'D', 'T') +#define ERRCODE_DOCUMENTDB_LOCATION17053 MAKE_SQLSTATE('M', '0', '0', 'D', 'U') + #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 2eacd2d4..4d472dd5 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 @@ -18,5 +18,5 @@ 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; diff --git a/pg_helio_api/sql/udfs/aggregation/bson_aggregation_redact--1.24-0.sql b/pg_helio_api/sql/udfs/aggregation/bson_aggregation_redact--1.24-0.sql new file mode 100644 index 00000000..2e1199b9 --- /dev/null +++ b/pg_helio_api/sql/udfs/aggregation/bson_aggregation_redact--1.24-0.sql @@ -0,0 +1,5 @@ +CREATE OR REPLACE FUNCTION helio_api_internal.bson_dollar_redact(__CORE_SCHEMA__.bson, __CORE_SCHEMA__.bson, text, __CORE_SCHEMA__.bson) + RETURNS __CORE_SCHEMA__.bson + LANGUAGE c + IMMUTABLE PARALLEL SAFE STRICT +AS 'MODULE_PATHNAME', $function$bson_dollar_redact$function$; diff --git a/pg_helio_api/sql/udfs/aggregation/bson_aggregation_redact--latest.sql b/pg_helio_api/sql/udfs/aggregation/bson_aggregation_redact--latest.sql new file mode 100644 index 00000000..2e1199b9 --- /dev/null +++ b/pg_helio_api/sql/udfs/aggregation/bson_aggregation_redact--latest.sql @@ -0,0 +1,5 @@ +CREATE OR REPLACE FUNCTION helio_api_internal.bson_dollar_redact(__CORE_SCHEMA__.bson, __CORE_SCHEMA__.bson, text, __CORE_SCHEMA__.bson) + RETURNS __CORE_SCHEMA__.bson + LANGUAGE c + IMMUTABLE PARALLEL SAFE STRICT +AS 'MODULE_PATHNAME', $function$bson_dollar_redact$function$;