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 ca95e3aa..5e89f915 100644 --- a/internal/pg_helio_distributed/src/test/regress/basic_schedule_core +++ b/internal/pg_helio_distributed/src/test/regress/basic_schedule_core @@ -33,4 +33,5 @@ test: bson_dollar_operators_negation_tests_explain_runtime test: bson_dollar_ops_text_search_tests bson_dollar_ops_expr_tests test: bson_dollar_ops_json_schema_build_tree_tests bson_dollar_ops_json_schema_query_tests -test: bson_dollar_ops_collation_runtime_tests \ No newline at end of file +test: bson_dollar_ops_collation_runtime_tests +test: bson_aggregation_stage_out_tests_2 \ No newline at end of file diff --git a/internal/pg_helio_distributed/src/test/regress/expected/bson_aggregation_stage_out_tests_2.out b/internal/pg_helio_distributed/src/test/regress/expected/bson_aggregation_stage_out_tests_2.out new file mode 100644 index 00000000..69d2cf6f --- /dev/null +++ b/internal/pg_helio_distributed/src/test/regress/expected/bson_aggregation_stage_out_tests_2.out @@ -0,0 +1,725 @@ +SET search_path TO helio_api_catalog, helio_api, helio_core, mongo_catalog; +SET citus.next_shard_id TO 9830000; +SET helio_api.next_collection_id TO 9830; +SET helio_api.next_collection_index_id TO 9830; +-- simplest test case working with db database +SELECT helio_api.insert('db', '{"insert":"source", "documents":[ + { "_id" : 1, "employee": "Ant", "salary": 100000, "fiscal_year": 2017 }, + { "_id" : 2, "employee": "Bee", "salary": 120000, "fiscal_year": 2017 }, + { "_id" : 3, "employee": "Ant", "salary": 115000, "fiscal_year": 2018 }, + { "_id" : 4, "employee": "Bee", "salary": 145000, "fiscal_year": 2018 }, + { "_id" : 5, "employee": "Cat", "salary": 135000, "fiscal_year": 2018 }, + { "_id" : 6, "employee": "Cat", "salary": 150000, "fiscal_year": 2019 } +]}'); +NOTICE: creating collection + insert +--------------------------------------------------------------------- + ("{ ""n"" : { ""$numberInt"" : ""6"" }, ""ok"" : { ""$numberDouble"" : ""1.0"" } }",t) +(1 row) + +-- simple test without GUC enable +SELECT * FROM aggregate_cursor_first_page('db', '{ "aggregate": "source", "pipeline": [ {"$out" : "target"} ], "cursor": { "batchSize": 1 } }', 4294967294); +ERROR: $out aggregation stage is not supported yet. +-- Let's enable GUC +SET helio_api.enableOutStage TO ON; +SELECT * FROM aggregate_cursor_first_page('db', '{ "aggregate": "source", "pipeline": [ {"$out" : "target"} ], "cursor": { "batchSize": 1 } }', 4294967294); +NOTICE: creating collection + cursorpage | continuation | persistconnection | cursorid +--------------------------------------------------------------------- + { "cursor" : { "id" : { "$numberLong" : "0"}, "ns" : "db.source", "firstBatch" : [ ] }, "ok" : { "$numberDouble" : "1.0" } } | | f | 4294967294 +(1 row) + +SELECT document FROM helio_api.collection('db', 'target'); + document +--------------------------------------------------------------------- + { "_id" : { "$numberInt" : "1" }, "employee" : "Ant", "salary" : { "$numberInt" : "100000" }, "fiscal_year" : { "$numberInt" : "2017" } } + { "_id" : { "$numberInt" : "2" }, "employee" : "Bee", "salary" : { "$numberInt" : "120000" }, "fiscal_year" : { "$numberInt" : "2017" } } + { "_id" : { "$numberInt" : "3" }, "employee" : "Ant", "salary" : { "$numberInt" : "115000" }, "fiscal_year" : { "$numberInt" : "2018" } } + { "_id" : { "$numberInt" : "4" }, "employee" : "Bee", "salary" : { "$numberInt" : "145000" }, "fiscal_year" : { "$numberInt" : "2018" } } + { "_id" : { "$numberInt" : "5" }, "employee" : "Cat", "salary" : { "$numberInt" : "135000" }, "fiscal_year" : { "$numberInt" : "2018" } } + { "_id" : { "$numberInt" : "6" }, "employee" : "Cat", "salary" : { "$numberInt" : "150000" }, "fiscal_year" : { "$numberInt" : "2019" } } +(6 rows) + +SELECT * FROM aggregate_cursor_first_page('db', '{ "aggregate": "source", "pipeline": [ {"$out" : { "db" : "db", "coll" : "target2" } } ], "cursor": { "batchSize": 1 } }', 4294967294); +NOTICE: creating collection + cursorpage | continuation | persistconnection | cursorid +--------------------------------------------------------------------- + { "cursor" : { "id" : { "$numberLong" : "0"}, "ns" : "db.source", "firstBatch" : [ ] }, "ok" : { "$numberDouble" : "1.0" } } | | f | 4294967294 +(1 row) + +SELECT document FROM helio_api.collection('db', 'target2'); + document +--------------------------------------------------------------------- + { "_id" : { "$numberInt" : "1" }, "employee" : "Ant", "salary" : { "$numberInt" : "100000" }, "fiscal_year" : { "$numberInt" : "2017" } } + { "_id" : { "$numberInt" : "2" }, "employee" : "Bee", "salary" : { "$numberInt" : "120000" }, "fiscal_year" : { "$numberInt" : "2017" } } + { "_id" : { "$numberInt" : "3" }, "employee" : "Ant", "salary" : { "$numberInt" : "115000" }, "fiscal_year" : { "$numberInt" : "2018" } } + { "_id" : { "$numberInt" : "4" }, "employee" : "Bee", "salary" : { "$numberInt" : "145000" }, "fiscal_year" : { "$numberInt" : "2018" } } + { "_id" : { "$numberInt" : "5" }, "employee" : "Cat", "salary" : { "$numberInt" : "135000" }, "fiscal_year" : { "$numberInt" : "2018" } } + { "_id" : { "$numberInt" : "6" }, "employee" : "Cat", "salary" : { "$numberInt" : "150000" }, "fiscal_year" : { "$numberInt" : "2019" } } +(6 rows) + +SELECT helio_api.drop_collection('db','source'); + drop_collection +--------------------------------------------------------------------- + t +(1 row) + +SELECT helio_api.drop_collection('db','target'); + drop_collection +--------------------------------------------------------------------- + t +(1 row) + +SELECT helio_api.drop_collection('db','target2'); + drop_collection +--------------------------------------------------------------------- + t +(1 row) + +-- simplest test case working +SELECT helio_api.insert('newdb', '{"insert":"source", "documents":[ + { "_id" : 1, "employee": "Ant", "salary": 100000, "fiscal_year": 2017 }, + { "_id" : 2, "employee": "Bee", "salary": 120000, "fiscal_year": 2017 }, + { "_id" : 3, "employee": "Ant", "salary": 115000, "fiscal_year": 2018 }, + { "_id" : 4, "employee": "Bee", "salary": 145000, "fiscal_year": 2018 }, + { "_id" : 5, "employee": "Cat", "salary": 135000, "fiscal_year": 2018 }, + { "_id" : 6, "employee": "Cat", "salary": 150000, "fiscal_year": 2019 } +]}'); +NOTICE: creating collection + insert +--------------------------------------------------------------------- + ("{ ""n"" : { ""$numberInt"" : ""6"" }, ""ok"" : { ""$numberDouble"" : ""1.0"" } }",t) +(1 row) + +SELECT * FROM aggregate_cursor_first_page('newdb', '{ "aggregate": "source", "pipeline": [ {"$out" : "target"} ], "cursor": { "batchSize": 1 } }', 4294967294); +NOTICE: creating collection + cursorpage | continuation | persistconnection | cursorid +--------------------------------------------------------------------- + { "cursor" : { "id" : { "$numberLong" : "0"}, "ns" : "newdb.source", "firstBatch" : [ ] }, "ok" : { "$numberDouble" : "1.0" } } | | f | 4294967294 +(1 row) + +SELECT document FROM helio_api.collection('newdb', 'target'); + document +--------------------------------------------------------------------- + { "_id" : { "$numberInt" : "1" }, "employee" : "Ant", "salary" : { "$numberInt" : "100000" }, "fiscal_year" : { "$numberInt" : "2017" } } + { "_id" : { "$numberInt" : "2" }, "employee" : "Bee", "salary" : { "$numberInt" : "120000" }, "fiscal_year" : { "$numberInt" : "2017" } } + { "_id" : { "$numberInt" : "3" }, "employee" : "Ant", "salary" : { "$numberInt" : "115000" }, "fiscal_year" : { "$numberInt" : "2018" } } + { "_id" : { "$numberInt" : "4" }, "employee" : "Bee", "salary" : { "$numberInt" : "145000" }, "fiscal_year" : { "$numberInt" : "2018" } } + { "_id" : { "$numberInt" : "5" }, "employee" : "Cat", "salary" : { "$numberInt" : "135000" }, "fiscal_year" : { "$numberInt" : "2018" } } + { "_id" : { "$numberInt" : "6" }, "employee" : "Cat", "salary" : { "$numberInt" : "150000" }, "fiscal_year" : { "$numberInt" : "2019" } } +(6 rows) + +SELECT * FROM aggregate_cursor_first_page('newdb', '{ "aggregate": "source", "pipeline": [ {"$out" : { "db" : "newdb", "coll" : "target2" } } ], "cursor": { "batchSize": 1 } }', 4294967294); +NOTICE: creating collection + cursorpage | continuation | persistconnection | cursorid +--------------------------------------------------------------------- + { "cursor" : { "id" : { "$numberLong" : "0"}, "ns" : "newdb.source", "firstBatch" : [ ] }, "ok" : { "$numberDouble" : "1.0" } } | | f | 4294967294 +(1 row) + +SELECT document FROM helio_api.collection('newdb', 'target2'); + document +--------------------------------------------------------------------- + { "_id" : { "$numberInt" : "1" }, "employee" : "Ant", "salary" : { "$numberInt" : "100000" }, "fiscal_year" : { "$numberInt" : "2017" } } + { "_id" : { "$numberInt" : "2" }, "employee" : "Bee", "salary" : { "$numberInt" : "120000" }, "fiscal_year" : { "$numberInt" : "2017" } } + { "_id" : { "$numberInt" : "3" }, "employee" : "Ant", "salary" : { "$numberInt" : "115000" }, "fiscal_year" : { "$numberInt" : "2018" } } + { "_id" : { "$numberInt" : "4" }, "employee" : "Bee", "salary" : { "$numberInt" : "145000" }, "fiscal_year" : { "$numberInt" : "2018" } } + { "_id" : { "$numberInt" : "5" }, "employee" : "Cat", "salary" : { "$numberInt" : "135000" }, "fiscal_year" : { "$numberInt" : "2018" } } + { "_id" : { "$numberInt" : "6" }, "employee" : "Cat", "salary" : { "$numberInt" : "150000" }, "fiscal_year" : { "$numberInt" : "2019" } } +(6 rows) + +SELECT helio_api.drop_collection('newdb','source'); + drop_collection +--------------------------------------------------------------------- + t +(1 row) + +SELECT helio_api.drop_collection('newdb','target'); + drop_collection +--------------------------------------------------------------------- + t +(1 row) + +SELECT helio_api.drop_collection('newdb','target2'); + drop_collection +--------------------------------------------------------------------- + t +(1 row) + +-- when source and target collection are same +SELECT helio_api.insert('newdb', '{"insert":"source", "documents":[{ "_id" : 1, "data": "This is source collection"}]}'); +NOTICE: creating collection + insert +--------------------------------------------------------------------- + ("{ ""n"" : { ""$numberInt"" : ""1"" }, ""ok"" : { ""$numberDouble"" : ""1.0"" } }",t) +(1 row) + +SELECT * FROM aggregate_cursor_first_page('newdb', '{ "aggregate": "source", "pipeline": [ {"$project" : {"data" : "updating same"} } ,{"$out" : { "db" : "newdb", "coll" : "source" } } ], "cursor": { "batchSize": 1 } }', 4294967294); +ERROR: The target collection cannot be the same as the source collection in $out stage. +SELECT document FROM helio_api.collection('newdb', 'source'); + document +--------------------------------------------------------------------- + { "_id" : { "$numberInt" : "1" }, "data" : "This is source collection" } +(1 row) + +SELECT helio_api.drop_collection('newdb','source'); + drop_collection +--------------------------------------------------------------------- + t +(1 row) + +-- case where target collection already exist: +SELECT helio_api.insert('newdb', '{"insert":"source", "documents":[{ "_id" : 1, "data": "This is source collection"}]}'); +NOTICE: creating collection + insert +--------------------------------------------------------------------- + ("{ ""n"" : { ""$numberInt"" : ""1"" }, ""ok"" : { ""$numberDouble"" : ""1.0"" } }",t) +(1 row) + +SELECT helio_api.insert('newdb', '{"insert":"target", "documents":[{ "_id" : 1, "data": "This is target collection"}]}'); +NOTICE: creating collection + insert +--------------------------------------------------------------------- + ("{ ""n"" : { ""$numberInt"" : ""1"" }, ""ok"" : { ""$numberDouble"" : ""1.0"" } }",t) +(1 row) + +SELECT * FROM aggregate_cursor_first_page('newdb', '{ "aggregate": "source", "pipeline": [ {"$out" : { "db" : "newdb", "coll" : "target" } } ], "cursor": { "batchSize": 1 } }', 4294967294); + cursorpage | continuation | persistconnection | cursorid +--------------------------------------------------------------------- + { "cursor" : { "id" : { "$numberLong" : "0"}, "ns" : "newdb.source", "firstBatch" : [ ] }, "ok" : { "$numberDouble" : "1.0" } } | | f | 4294967294 +(1 row) + +SELECT document FROM helio_api.collection('newdb', 'target'); + document +--------------------------------------------------------------------- + { "_id" : { "$numberInt" : "1" }, "data" : "This is source collection" } +(1 row) + +SELECT helio_api.drop_collection('newdb','source'); + drop_collection +--------------------------------------------------------------------- + t +(1 row) + +SELECT helio_api.drop_collection('newdb','target'); + drop_collection +--------------------------------------------------------------------- + t +(1 row) + +-- when target db is different: +SELECT helio_api.insert('newdb', '{"insert":"source", "documents":[{ "_id" : 1, "data": "This is source collection"}]}'); +NOTICE: creating collection + insert +--------------------------------------------------------------------- + ("{ ""n"" : { ""$numberInt"" : ""1"" }, ""ok"" : { ""$numberDouble"" : ""1.0"" } }",t) +(1 row) + +SELECT * FROM aggregate_cursor_first_page('newdb', '{ "aggregate": "source", "pipeline": [ {"$out" : { "db" : "db2", "coll" : "target" } } ], "cursor": { "batchSize": 1 } }', 4294967294); +NOTICE: creating collection + cursorpage | continuation | persistconnection | cursorid +--------------------------------------------------------------------- + { "cursor" : { "id" : { "$numberLong" : "0"}, "ns" : "newdb.source", "firstBatch" : [ ] }, "ok" : { "$numberDouble" : "1.0" } } | | f | 4294967294 +(1 row) + +SELECT document FROM helio_api.collection('db2', 'target'); + document +--------------------------------------------------------------------- + { "_id" : { "$numberInt" : "1" }, "data" : "This is source collection" } +(1 row) + +SELECT helio_api.drop_collection('newdb','source'); + drop_collection +--------------------------------------------------------------------- + t +(1 row) + +SELECT helio_api.drop_collection('db2','target'); + drop_collection +--------------------------------------------------------------------- + t +(1 row) + +-- index validation: +-- 1. If source and target are same collection, only data will get updated index should remain +SELECT helio_api.insert('newdb', '{"insert":"src", "documents":[{ "_id" : 1, "data": "This is source collection"}]}'); +NOTICE: creating collection + insert +--------------------------------------------------------------------- + ("{ ""n"" : { ""$numberInt"" : ""1"" }, ""ok"" : { ""$numberDouble"" : ""1.0"" } }",t) +(1 row) + +SELECT helio_api_internal.create_indexes_non_concurrently('newdb', '{ "createIndexes": "src", "indexes": [{ "key": {"a": 1, "b" : 1, "c" :1}, "name": "index_1" }] }'::helio_core.bson, true); + create_indexes_non_concurrently +--------------------------------------------------------------------- + { "raw" : { "defaultShard" : { "numIndexesBefore" : { "$numberInt" : "1" }, "numIndexesAfter" : { "$numberInt" : "2" }, "createdCollectionAutomatically" : false, "ok" : { "$numberInt" : "1" } } }, "ok" : { "$numberInt" : "1" } } +(1 row) + +SELECT helio_api_internal.create_indexes_non_concurrently('newdb', '{ "createIndexes": "src", "indexes": [{ "key": {"his is some index" :1}, "name": "index_2" }] }'::helio_core.bson, true); + create_indexes_non_concurrently +--------------------------------------------------------------------- + { "raw" : { "defaultShard" : { "numIndexesBefore" : { "$numberInt" : "2" }, "numIndexesAfter" : { "$numberInt" : "3" }, "createdCollectionAutomatically" : false, "ok" : { "$numberInt" : "1" } } }, "ok" : { "$numberInt" : "1" } } +(1 row) + +SELECT bson_dollar_unwind(cursorpage, '$cursor.firstBatch') FROM helio_api.list_indexes_cursor_first_page('newdb', '{ "listIndexes": "src" }') ORDER BY 1; + bson_dollar_unwind +--------------------------------------------------------------------- + { "cursor" : { "id" : { "$numberLong" : "0"}, "ns" : "newdb.src", "firstBatch" : { "v" : { "$numberInt" : "2" }, "key" : { "_id" : { "$numberInt" : "1" } }, "name" : "_id_" } }, "ok" : { "$numberDouble" : "1.0" } } + { "cursor" : { "id" : { "$numberLong" : "0"}, "ns" : "newdb.src", "firstBatch" : { "v" : { "$numberInt" : "2" }, "key" : { "a" : { "$numberInt" : "1" }, "b" : { "$numberInt" : "1" }, "c" : { "$numberInt" : "1" } }, "name" : "index_1" } }, "ok" : { "$numberDouble" : "1.0" } } + { "cursor" : { "id" : { "$numberLong" : "0"}, "ns" : "newdb.src", "firstBatch" : { "v" : { "$numberInt" : "2" }, "key" : { "his is some index" : { "$numberInt" : "1" } }, "name" : "index_2" } }, "ok" : { "$numberDouble" : "1.0" } } +(3 rows) + +SELECT * FROM aggregate_cursor_first_page('newdb', '{ "aggregate": "src", "pipeline": [ {"$project" : {"data" : "updating data"} }, {"$out" : { "db" : "newdb", "coll" : "src" } } ], "cursor": { "batchSize": 1 } }', 4294967294); +ERROR: The target collection cannot be the same as the source collection in $out stage. +SELECT bson_dollar_unwind(cursorpage, '$cursor.firstBatch') FROM helio_api.list_indexes_cursor_first_page('newdb', '{ "listIndexes": "src" }') ORDER BY 1; + bson_dollar_unwind +--------------------------------------------------------------------- + { "cursor" : { "id" : { "$numberLong" : "0"}, "ns" : "newdb.src", "firstBatch" : { "v" : { "$numberInt" : "2" }, "key" : { "_id" : { "$numberInt" : "1" } }, "name" : "_id_" } }, "ok" : { "$numberDouble" : "1.0" } } + { "cursor" : { "id" : { "$numberLong" : "0"}, "ns" : "newdb.src", "firstBatch" : { "v" : { "$numberInt" : "2" }, "key" : { "a" : { "$numberInt" : "1" }, "b" : { "$numberInt" : "1" }, "c" : { "$numberInt" : "1" } }, "name" : "index_1" } }, "ok" : { "$numberDouble" : "1.0" } } + { "cursor" : { "id" : { "$numberLong" : "0"}, "ns" : "newdb.src", "firstBatch" : { "v" : { "$numberInt" : "2" }, "key" : { "his is some index" : { "$numberInt" : "1" } }, "name" : "index_2" } }, "ok" : { "$numberDouble" : "1.0" } } +(3 rows) + +SELECT document FROM helio_api.collection('newdb', 'src'); + document +--------------------------------------------------------------------- + { "_id" : { "$numberInt" : "1" }, "data" : "This is source collection" } +(1 row) + +SELECT helio_api.drop_collection('newdb','src'); + drop_collection +--------------------------------------------------------------------- + t +(1 row) + +-- 2. if target already exist only data will get updated index should remain +SELECT helio_api.insert('newdb', '{"insert":"src", "documents":[{ "_id" : 1, "data": "This is source collection"}]}'); +NOTICE: creating collection + insert +--------------------------------------------------------------------- + ("{ ""n"" : { ""$numberInt"" : ""1"" }, ""ok"" : { ""$numberDouble"" : ""1.0"" } }",t) +(1 row) + +SELECT helio_api.insert('newdb', '{"insert":"tar", "documents":[{ "_id" : 1, "data": "This is target collection"}]}'); +NOTICE: creating collection + insert +--------------------------------------------------------------------- + ("{ ""n"" : { ""$numberInt"" : ""1"" }, ""ok"" : { ""$numberDouble"" : ""1.0"" } }",t) +(1 row) + +SELECT helio_api_internal.create_indexes_non_concurrently('newdb', '{ "createIndexes": "tar", "indexes": [{ "key": {"a": 1, "b" : 1, "c" :1}, "name": "index_1" }] }'::helio_core.bson, true); + create_indexes_non_concurrently +--------------------------------------------------------------------- + { "raw" : { "defaultShard" : { "numIndexesBefore" : { "$numberInt" : "1" }, "numIndexesAfter" : { "$numberInt" : "2" }, "createdCollectionAutomatically" : false, "ok" : { "$numberInt" : "1" } } }, "ok" : { "$numberInt" : "1" } } +(1 row) + +SELECT helio_api_internal.create_indexes_non_concurrently('newdb', '{ "createIndexes": "tar", "indexes": [{ "key": {"his is some index" :1}, "name": "index_2" }] }'::helio_core.bson, true); + create_indexes_non_concurrently +--------------------------------------------------------------------- + { "raw" : { "defaultShard" : { "numIndexesBefore" : { "$numberInt" : "2" }, "numIndexesAfter" : { "$numberInt" : "3" }, "createdCollectionAutomatically" : false, "ok" : { "$numberInt" : "1" } } }, "ok" : { "$numberInt" : "1" } } +(1 row) + +SELECT bson_dollar_unwind(cursorpage, '$cursor.firstBatch') FROM helio_api.list_indexes_cursor_first_page('newdb', '{ "listIndexes": "tar" }') ORDER BY 1; + bson_dollar_unwind +--------------------------------------------------------------------- + { "cursor" : { "id" : { "$numberLong" : "0"}, "ns" : "newdb.tar", "firstBatch" : { "v" : { "$numberInt" : "2" }, "key" : { "_id" : { "$numberInt" : "1" } }, "name" : "_id_" } }, "ok" : { "$numberDouble" : "1.0" } } + { "cursor" : { "id" : { "$numberLong" : "0"}, "ns" : "newdb.tar", "firstBatch" : { "v" : { "$numberInt" : "2" }, "key" : { "a" : { "$numberInt" : "1" }, "b" : { "$numberInt" : "1" }, "c" : { "$numberInt" : "1" } }, "name" : "index_1" } }, "ok" : { "$numberDouble" : "1.0" } } + { "cursor" : { "id" : { "$numberLong" : "0"}, "ns" : "newdb.tar", "firstBatch" : { "v" : { "$numberInt" : "2" }, "key" : { "his is some index" : { "$numberInt" : "1" } }, "name" : "index_2" } }, "ok" : { "$numberDouble" : "1.0" } } +(3 rows) + +SELECT * FROM aggregate_cursor_first_page('newdb', '{ "aggregate": "src", "pipeline": [ {"$project" : {"data" : "updating data"} }, {"$out" : { "db" : "newdb", "coll" : "tar" } } ], "cursor": { "batchSize": 1 } }', 4294967294); + cursorpage | continuation | persistconnection | cursorid +--------------------------------------------------------------------- + { "cursor" : { "id" : { "$numberLong" : "0"}, "ns" : "newdb.src", "firstBatch" : [ ] }, "ok" : { "$numberDouble" : "1.0" } } | | f | 4294967294 +(1 row) + +SELECT bson_dollar_unwind(cursorpage, '$cursor.firstBatch') FROM helio_api.list_indexes_cursor_first_page('newdb', '{ "listIndexes": "tar" }') ORDER BY 1; + bson_dollar_unwind +--------------------------------------------------------------------- + { "cursor" : { "id" : { "$numberLong" : "0"}, "ns" : "newdb.tar", "firstBatch" : { "v" : { "$numberInt" : "2" }, "key" : { "_id" : { "$numberInt" : "1" } }, "name" : "_id_" } }, "ok" : { "$numberDouble" : "1.0" } } + { "cursor" : { "id" : { "$numberLong" : "0"}, "ns" : "newdb.tar", "firstBatch" : { "v" : { "$numberInt" : "2" }, "key" : { "a" : { "$numberInt" : "1" }, "b" : { "$numberInt" : "1" }, "c" : { "$numberInt" : "1" } }, "name" : "index_1" } }, "ok" : { "$numberDouble" : "1.0" } } + { "cursor" : { "id" : { "$numberLong" : "0"}, "ns" : "newdb.tar", "firstBatch" : { "v" : { "$numberInt" : "2" }, "key" : { "his is some index" : { "$numberInt" : "1" } }, "name" : "index_2" } }, "ok" : { "$numberDouble" : "1.0" } } +(3 rows) + +SELECT document FROM helio_api.collection('newdb', 'tar'); + document +--------------------------------------------------------------------- + { "_id" : { "$numberInt" : "1" }, "data" : "updating data" } +(1 row) + +SELECT helio_api.drop_collection('newdb','src'); + drop_collection +--------------------------------------------------------------------- + t +(1 row) + +SELECT helio_api.drop_collection('newdb','tar'); + drop_collection +--------------------------------------------------------------------- + t +(1 row) + +-- complex query with last stage $out: +SELECT helio_api.insert_one('newdb','source',' {"_id": 1, "name": "American Steak House", "food": ["filet", "sirloin"], "quantity": 100 , "beverages": ["beer", "wine"]}', NULL); +NOTICE: creating collection + insert_one +--------------------------------------------------------------------- + { "n" : { "$numberInt" : "1" }, "ok" : { "$numberDouble" : "1.0" } } +(1 row) + +SELECT helio_api.insert_one('newdb','source','{ "_id": 2, "name": "Honest John Pizza", "food": ["cheese pizza", "pepperoni pizza"], "quantity": 120, "beverages": ["soda"]}', NULL); + insert_one +--------------------------------------------------------------------- + { "n" : { "$numberInt" : "1" }, "ok" : { "$numberDouble" : "1.0" } } +(1 row) + +SELECT helio_api.insert_one('newdb','target','{ "_id": 1, "item": "filet", "restaurant_name": "American Steak House"}', NULL); +NOTICE: creating collection + insert_one +--------------------------------------------------------------------- + { "n" : { "$numberInt" : "1" }, "ok" : { "$numberDouble" : "1.0" } } +(1 row) + +SELECT helio_api.insert_one('newdb','target','{ "_id": 2, "item": "cheese pizza", "restaurant_name": "Honest John Pizza", "drink": "lemonade"}', NULL); + insert_one +--------------------------------------------------------------------- + { "n" : { "$numberInt" : "1" }, "ok" : { "$numberDouble" : "1.0" } } +(1 row) + +SELECT helio_api.insert_one('newdb','target','{ "_id": 3, "item": "cheese pizza", "restaurant_name": "Honest John Pizza", "drink": "soda"}', NULL); + insert_one +--------------------------------------------------------------------- + { "n" : { "$numberInt" : "1" }, "ok" : { "$numberDouble" : "1.0" } } +(1 row) + +SELECT * FROM aggregate_cursor_first_page('newdb', '{ "aggregate": "target", + "pipeline": + [ + { + "$lookup": + { + "from": "source", + "pipeline": [ { "$match": { "quantity": { "$gt": 110 } }}], + "as": "matched_docs", + "localField": "restaurant_name", + "foreignField": "name" + } + }, + {"$sort" : {"_id" : -1}} , + {"$group" :{"_id" : "$restaurant_name"}}, + {"$project" : {"matched_docs" : 0}} + ], "cursor": { "batchSize": 1 } }', 4294967294); + cursorpage | continuation | persistconnection | cursorid +--------------------------------------------------------------------- + { "cursor" : { "id" : { "$numberLong" : "4294967294"}, "ns" : "newdb.target", "firstBatch" : [ { "_id" : "American Steak House" } ] }, "ok" : { "$numberDouble" : "1.0" } } | { "qk" : { "$numberInt" : "2" }, "qn" : "cursor_4294967294", "qi" : { "$numberLong" : "4294967294"}, "numIters" : { "$numberInt" : "0" } } | t | 4294967294 +(1 row) + +SELECT document FROM helio_api.collection('newdb','target'); + document +--------------------------------------------------------------------- + { "_id" : { "$numberInt" : "1" }, "item" : "filet", "restaurant_name" : "American Steak House" } + { "_id" : { "$numberInt" : "2" }, "item" : "cheese pizza", "restaurant_name" : "Honest John Pizza", "drink" : "lemonade" } + { "_id" : { "$numberInt" : "3" }, "item" : "cheese pizza", "restaurant_name" : "Honest John Pizza", "drink" : "soda" } +(3 rows) + +SELECT helio_api.drop_collection('newdb','source'); + drop_collection +--------------------------------------------------------------------- + t +(1 row) + +SELECT helio_api.drop_collection('newdb','target'); + drop_collection +--------------------------------------------------------------------- + t +(1 row) + +-- case when _id is missing from last stage: +SELECT helio_api.insert_one('newdb','source',' {"_id": 1, "name": "Test Case"}', NULL); +NOTICE: creating collection + insert_one +--------------------------------------------------------------------- + { "n" : { "$numberInt" : "1" }, "ok" : { "$numberDouble" : "1.0" } } +(1 row) + +SELECT * FROM aggregate_cursor_first_page('newdb', '{ "aggregate": "source", "pipeline": [ {"$project" : {"_id" : 0} } ,{"$out" : "target" } ], "cursor": { "batchSize": 1 } }', 4294967294); +NOTICE: creating collection + cursorpage | continuation | persistconnection | cursorid +--------------------------------------------------------------------- + { "cursor" : { "id" : { "$numberLong" : "0"}, "ns" : "newdb.source", "firstBatch" : [ ] }, "ok" : { "$numberDouble" : "1.0" } } | | f | 4294967294 +(1 row) + +SELECT bson_dollar_project(document,'{"_id" : {"$gt" : ["$_id", null]} }') FROM helio_api.collection('newdb','target'); + bson_dollar_project +--------------------------------------------------------------------- + { "_id" : true } +(1 row) + +SELECT helio_api.drop_collection('newdb','source'); + drop_collection +--------------------------------------------------------------------- + t +(1 row) + +SELECT helio_api.drop_collection('newdb','target'); + drop_collection +--------------------------------------------------------------------- + t +(1 row) + +-- test when source collection is view +SELECT helio_api.insert('newdb', '{"insert":"source", "documents":[{ "_id" : 1, "a" : 1, "b" : 1 }]}'); +NOTICE: creating collection + insert +--------------------------------------------------------------------- + ("{ ""n"" : { ""$numberInt"" : ""1"" }, ""ok"" : { ""$numberDouble"" : ""1.0"" } }",t) +(1 row) + +SELECT helio_api.create_collection_view('newdb', '{ "create": "sourceView", "viewOn": "source", "pipeline": [ { "$project": { "_id": 1, "c" : {"$add" : ["$a","$b"]} } } ] }'); + create_collection_view +--------------------------------------------------------------------- + { "ok" : { "$numberDouble" : "1.0" } } +(1 row) + +SELECT * FROM aggregate_cursor_first_page('newdb', '{ "aggregate": "sourceView", "pipeline": [ {"$out" : "target" } ], "cursor": { "batchSize": 1 } }', 4294967294); +NOTICE: creating collection + cursorpage | continuation | persistconnection | cursorid +--------------------------------------------------------------------- + { "cursor" : { "id" : { "$numberLong" : "0"}, "ns" : "newdb.sourceView", "firstBatch" : [ ] }, "ok" : { "$numberDouble" : "1.0" } } | | f | 4294967294 +(1 row) + +SELECT document FROM helio_api.collection('newdb', 'target'); + document +--------------------------------------------------------------------- + { "_id" : { "$numberInt" : "1" }, "c" : { "$numberInt" : "2" } } +(1 row) + +SELECT helio_api.drop_collection('newdb','source'); + drop_collection +--------------------------------------------------------------------- + t +(1 row) + +SELECT helio_api.drop_collection('newdb','target'); + drop_collection +--------------------------------------------------------------------- + t +(1 row) + +-- test when source is sharded: +SELECT helio_api.insert_one('newdb','source',' {"_id": 1, "name": "Test Case"}', NULL); +NOTICE: creating collection + insert_one +--------------------------------------------------------------------- + { "n" : { "$numberInt" : "1" }, "ok" : { "$numberDouble" : "1.0" } } +(1 row) + +SELECT helio_api.shard_collection('newdb', 'source', '{ "a": "hashed" }', false); + shard_collection +--------------------------------------------------------------------- + +(1 row) + +SELECT * FROM aggregate_cursor_first_page('newdb', '{ "aggregate": "source", "pipeline": [ {"$out" : "target" } ], "cursor": { "batchSize": 1 } }', 4294967294); +NOTICE: creating collection + cursorpage | continuation | persistconnection | cursorid +--------------------------------------------------------------------- + { "cursor" : { "id" : { "$numberLong" : "0"}, "ns" : "newdb.source", "firstBatch" : [ ] }, "ok" : { "$numberDouble" : "1.0" } } | | f | 4294967294 +(1 row) + +SELECT document from helio_api.collection('newdb','target'); + document +--------------------------------------------------------------------- + { "_id" : { "$numberInt" : "1" }, "name" : "Test Case" } +(1 row) + +SELECT helio_api.drop_collection('newdb','source'); + drop_collection +--------------------------------------------------------------------- + t +(1 row) + +SELECT helio_api.drop_collection('newdb','target'); + drop_collection +--------------------------------------------------------------------- + t +(1 row) + +-- Negative test cases +SELECT helio_api.insert_one('newdb','source',' {"_id": 1, "name": "Test Case"}', NULL); +NOTICE: creating collection + insert_one +--------------------------------------------------------------------- + { "n" : { "$numberInt" : "1" }, "ok" : { "$numberDouble" : "1.0" } } +(1 row) + +SELECT * FROM aggregate_cursor_first_page('newdb', '{ "aggregate": "source", "pipeline": [ {"$out" : 1 } ], "cursor": { "batchSize": 1 } }', 4294967294); +ERROR: $out only supports a string or object argument, but found int +SELECT * FROM aggregate_cursor_first_page('newdb', '{ "aggregate": "source", "pipeline": [ {"$out" : {} } ], "cursor": { "batchSize": 1 } }', 4294967294); +ERROR: If an object is passed to $out it must have exactly 2 fields: 'db' and 'coll' +SELECT * FROM aggregate_cursor_first_page('newdb', '{ "aggregate": "source", "pipeline": [ {"$out" : {"db" : "a"} } ], "cursor": { "batchSize": 1 } }', 4294967294); +ERROR: If an object is passed to $out it must have exactly 2 fields: 'db' and 'coll' +SELECT * FROM aggregate_cursor_first_page('newdb', '{ "aggregate": "source", "pipeline": [ {"$out" : {"coll" : "a"} } ], "cursor": { "batchSize": 1 } }', 4294967294); +ERROR: If an object is passed to $out it must have exactly 2 fields: 'db' and 'coll' +SELECT * FROM aggregate_cursor_first_page('newdb', '{ "aggregate": "source", "pipeline": [ {"$out" : {"db" : "a", "coll" : "a", "other" : "a"} } ], "cursor": { "batchSize": 1 } }', 4294967294); +ERROR: If an object is passed to $out it must have exactly 2 fields: 'db' and 'coll' +SELECT * FROM aggregate_cursor_first_page('newdb', '{ "aggregate": "source", "pipeline": [ {"$out" : {"db" : "a", "coll" : 1} } ], "cursor": { "batchSize": 1 } }', 4294967294); +ERROR: wrong type for field (coll) int != string +SELECT * FROM aggregate_cursor_first_page('newdb', '{ "aggregate": "source", "pipeline": [ {"$out" : {"db" : 1, "coll" : "a"} } ], "cursor": { "batchSize": 1 } }', 4294967294); +ERROR: wrong type for field (db) int != string +-- test when target is view: +SELECT helio_api.insert('newdb', '{"insert":"source", "documents":[{ "_id" : 1, "a" : 1, "b" : 1 }]}'); + insert +--------------------------------------------------------------------- + ("{ ""n"" : { ""$numberInt"" : ""0"" }, ""ok"" : { ""$numberDouble"" : ""1.0"" }, ""writeErrors"" : [ { ""index"" : { ""$numberInt"" : ""0"" }, ""code"" : { ""$numberInt"" : ""687876856"" }, ""errmsg"" : ""Duplicate key violation on the requested collection: Index '_id_'"" } ] }",f) +(1 row) + +SELECT helio_api.create_collection_view('newdb', '{ "create": "targetView", "viewOn": "source", "pipeline": [ { "$project": { "_id": 1, "c" : {"$add" : ["$a","$b"]} } } ] }'); + create_collection_view +--------------------------------------------------------------------- + { "ok" : { "$numberDouble" : "1.0" } } +(1 row) + +SELECT * FROM aggregate_cursor_first_page('newdb', '{ "aggregate": "source", "pipeline": [ {"$out" : "targetView" } ], "cursor": { "batchSize": 1 } }', 4294967294); +ERROR: Namespace newdb.targetView is a view, not a collection +HINT: Namespace newdb.targetView is a view, not a collection +SELECT helio_api.drop_collection('newdb','source'); + drop_collection +--------------------------------------------------------------------- + t +(1 row) + +-- test when target is sharded: +SELECT helio_api.insert_one('newdb','source',' {"_id": 1, "name": "Test Case"}', NULL); +NOTICE: creating collection + insert_one +--------------------------------------------------------------------- + { "n" : { "$numberInt" : "1" }, "ok" : { "$numberDouble" : "1.0" } } +(1 row) + +SELECT helio_api.insert_one('newdb','target',' {"_id": 1, "name": "Test Case"}', NULL); +NOTICE: creating collection + insert_one +--------------------------------------------------------------------- + { "n" : { "$numberInt" : "1" }, "ok" : { "$numberDouble" : "1.0" } } +(1 row) + +SELECT helio_api.shard_collection('newdb', 'target', '{ "a": "hashed" }', false); + shard_collection +--------------------------------------------------------------------- + +(1 row) + +SELECT * FROM aggregate_cursor_first_page('newdb', '{ "aggregate": "source", "pipeline": [ {"$out" : "target" } ], "cursor": { "batchSize": 1 } }', 4294967294); +ERROR: newdb.target cannot be sharded +SELECT helio_api.drop_collection('newdb','source'); + drop_collection +--------------------------------------------------------------------- + t +(1 row) + +SELECT helio_api.drop_collection('newdb','target'); + drop_collection +--------------------------------------------------------------------- + t +(1 row) + +-- let's verify we insert or update proper data in database. +--try to insert 16 MB Document +SELECT helio_api.insert_one('newdb','sourceDataValidation','{ "_id": 1, "item": "a" }' , NULL); +NOTICE: creating collection + insert_one +--------------------------------------------------------------------- + { "n" : { "$numberInt" : "1" }, "ok" : { "$numberDouble" : "1.0" } } +(1 row) + +SELECT * FROM aggregate_cursor_first_page('newdb', FORMAT('{ "aggregate": "sourceDataValidation", "pipeline": [ {"$addFields" : { "newLargeField": "%s"} }, {"$out" : "targetDataValidation"} ], "cursor": { "batchSize": 1 } }',repeat('a', 16*1024*1024) )::bson, 4294967294); +NOTICE: creating collection +ERROR: Size 16777262 is larger than MaxDocumentSize 16777216 +--try to insert bad _id field +SELECT * FROM aggregate_cursor_first_page('newdb', '{ "aggregate": "sourceDataValidation", "pipeline": [ {"$project" : {"_id" : [1,2,3]}}, {"$out" : "targetDataValidation"} ], "cursor": { "batchSize": 1 } }'); +NOTICE: creating collection +ERROR: The '_id' value cannot be of type array +-- Let's take a look at explain plan +--1) colocated tables , single shard distributed +SELECT helio_api.insert_one('newdb','explainsrc',' {"_id": 1, "name": "Test Case"}', NULL); +NOTICE: creating collection + insert_one +--------------------------------------------------------------------- + { "n" : { "$numberInt" : "1" }, "ok" : { "$numberDouble" : "1.0" } } +(1 row) + +EXPLAIN (COSTS OFF) SELECT document FROM bson_aggregation_pipeline('newdb', '{ "aggregate": "explainsrc", "pipeline": [{"$out" : "target"} ] }'); +NOTICE: creating collection + QUERY PLAN +--------------------------------------------------------------------- + Custom Scan (Citus Adaptive) + Task Count: 1 + Tasks Shown: All + -> Task + Node: host=localhost port=58070 dbname=regression + -> Merge on documents_9863_9830120 documents_9863 + -> Nested Loop Left Join + -> Bitmap Heap Scan on documents_9862_9830118 collection + Recheck Cond: (shard_key_value = '9862'::bigint) + -> Bitmap Index Scan on _id_ + Index Cond: (shard_key_value = '9862'::bigint) + -> Materialize + -> Bitmap Heap Scan on documents_9863_9830120 documents_9863 + Recheck Cond: (shard_key_value = '9863'::bigint) + -> Bitmap Index Scan on _id_ + Index Cond: (shard_key_value = '9863'::bigint) +(16 rows) + +--2) non colocated tables, hash shard distributed +SELECT helio_api.insert_one('db','explainsrc',' {"_id": 1, "name": "Test Case"}', NULL); +NOTICE: creating collection + insert_one +--------------------------------------------------------------------- + { "n" : { "$numberInt" : "1" }, "ok" : { "$numberDouble" : "1.0" } } +(1 row) + +EXPLAIN (VERBOSE ON, COSTS OFF) SELECT document FROM bson_aggregation_pipeline('db', '{ "aggregate": "explainsrc", "pipeline": [{"$out" : "target"} ] }'); +NOTICE: creating collection + QUERY PLAN +--------------------------------------------------------------------- + Custom Scan (Citus MERGE INTO ...) + MERGE INTO documents_9865 method: pull to coordinator + -> Custom Scan (Citus Adaptive) + Output: remote_scan.document, remote_scan.target_shard_key_value, remote_scan.generated_object_id + Task Count: 1 + Tasks Shown: All + -> Task + Query: SELECT document, target_shard_key_value, generated_object_id FROM (SELECT collection.document, '9865'::bigint AS target_shard_key_value, helio_api_internal.bson_dollar_merge_generate_object_id(collection.document) AS generated_object_id FROM helio_data.documents_9864_9830124 collection WHERE (collection.shard_key_value OPERATOR(pg_catalog.=) '9864'::bigint)) citus_insert_select_subquery + Node: host=localhost port=58070 dbname=regression + -> Bitmap Heap Scan on helio_data.documents_9864_9830124 collection + Output: collection.document, '9865'::bigint, helio_api_internal.bson_dollar_merge_generate_object_id(collection.document) + Recheck Cond: (collection.shard_key_value = '9864'::bigint) + -> Bitmap Index Scan on _id_ + Index Cond: (collection.shard_key_value = '9864'::bigint) +(14 rows) + +--3) sharded source +SELECT helio_api.shard_collection('newdb', 'explainsrc', '{ "a": "hashed" }', false); + shard_collection +--------------------------------------------------------------------- + +(1 row) + +EXPLAIN (VERBOSE ON, COSTS OFF) SELECT document FROM bson_aggregation_pipeline('db', '{ "aggregate": "explainsrc", "pipeline": [{"$out" : "target"} ] }'); + QUERY PLAN +--------------------------------------------------------------------- + Custom Scan (Citus MERGE INTO ...) + MERGE INTO documents_9865 method: pull to coordinator + -> Custom Scan (Citus Adaptive) + Output: remote_scan.document, remote_scan.target_shard_key_value, remote_scan.generated_object_id + Task Count: 1 + Tasks Shown: All + -> Task + Query: SELECT document, target_shard_key_value, generated_object_id FROM (SELECT collection.document, '9865'::bigint AS target_shard_key_value, helio_api_internal.bson_dollar_merge_generate_object_id(collection.document) AS generated_object_id FROM helio_data.documents_9864_9830124 collection WHERE (collection.shard_key_value OPERATOR(pg_catalog.=) '9864'::bigint)) citus_insert_select_subquery + Node: host=localhost port=58070 dbname=regression + -> Bitmap Heap Scan on helio_data.documents_9864_9830124 collection + Output: collection.document, '9865'::bigint, helio_api_internal.bson_dollar_merge_generate_object_id(collection.document) + Recheck Cond: (collection.shard_key_value = '9864'::bigint) + -> Bitmap Index Scan on _id_ + Index Cond: (collection.shard_key_value = '9864'::bigint) +(14 rows) + diff --git a/internal/pg_helio_distributed/src/test/regress/sql/bson_aggregation_stage_out_tests_2.sql b/internal/pg_helio_distributed/src/test/regress/sql/bson_aggregation_stage_out_tests_2.sql new file mode 100644 index 00000000..d309a230 --- /dev/null +++ b/internal/pg_helio_distributed/src/test/regress/sql/bson_aggregation_stage_out_tests_2.sql @@ -0,0 +1,198 @@ +SET search_path TO helio_api_catalog, helio_api, helio_core, mongo_catalog; + +SET citus.next_shard_id TO 9830000; +SET helio_api.next_collection_id TO 9830; +SET helio_api.next_collection_index_id TO 9830; + + +-- simplest test case working with db database +SELECT helio_api.insert('db', '{"insert":"source", "documents":[ + { "_id" : 1, "employee": "Ant", "salary": 100000, "fiscal_year": 2017 }, + { "_id" : 2, "employee": "Bee", "salary": 120000, "fiscal_year": 2017 }, + { "_id" : 3, "employee": "Ant", "salary": 115000, "fiscal_year": 2018 }, + { "_id" : 4, "employee": "Bee", "salary": 145000, "fiscal_year": 2018 }, + { "_id" : 5, "employee": "Cat", "salary": 135000, "fiscal_year": 2018 }, + { "_id" : 6, "employee": "Cat", "salary": 150000, "fiscal_year": 2019 } +]}'); + +-- simple test without GUC enable +SELECT * FROM aggregate_cursor_first_page('db', '{ "aggregate": "source", "pipeline": [ {"$out" : "target"} ], "cursor": { "batchSize": 1 } }', 4294967294); + +-- Let's enable GUC +SET helio_api.enableOutStage TO ON; + +SELECT * FROM aggregate_cursor_first_page('db', '{ "aggregate": "source", "pipeline": [ {"$out" : "target"} ], "cursor": { "batchSize": 1 } }', 4294967294); +SELECT document FROM helio_api.collection('db', 'target'); + +SELECT * FROM aggregate_cursor_first_page('db', '{ "aggregate": "source", "pipeline": [ {"$out" : { "db" : "db", "coll" : "target2" } } ], "cursor": { "batchSize": 1 } }', 4294967294); +SELECT document FROM helio_api.collection('db', 'target2'); +SELECT helio_api.drop_collection('db','source'); +SELECT helio_api.drop_collection('db','target'); +SELECT helio_api.drop_collection('db','target2'); + +-- simplest test case working +SELECT helio_api.insert('newdb', '{"insert":"source", "documents":[ + { "_id" : 1, "employee": "Ant", "salary": 100000, "fiscal_year": 2017 }, + { "_id" : 2, "employee": "Bee", "salary": 120000, "fiscal_year": 2017 }, + { "_id" : 3, "employee": "Ant", "salary": 115000, "fiscal_year": 2018 }, + { "_id" : 4, "employee": "Bee", "salary": 145000, "fiscal_year": 2018 }, + { "_id" : 5, "employee": "Cat", "salary": 135000, "fiscal_year": 2018 }, + { "_id" : 6, "employee": "Cat", "salary": 150000, "fiscal_year": 2019 } +]}'); + +SELECT * FROM aggregate_cursor_first_page('newdb', '{ "aggregate": "source", "pipeline": [ {"$out" : "target"} ], "cursor": { "batchSize": 1 } }', 4294967294); +SELECT document FROM helio_api.collection('newdb', 'target'); + +SELECT * FROM aggregate_cursor_first_page('newdb', '{ "aggregate": "source", "pipeline": [ {"$out" : { "db" : "newdb", "coll" : "target2" } } ], "cursor": { "batchSize": 1 } }', 4294967294); +SELECT document FROM helio_api.collection('newdb', 'target2'); + +SELECT helio_api.drop_collection('newdb','source'); +SELECT helio_api.drop_collection('newdb','target'); +SELECT helio_api.drop_collection('newdb','target2'); + +-- when source and target collection are same +SELECT helio_api.insert('newdb', '{"insert":"source", "documents":[{ "_id" : 1, "data": "This is source collection"}]}'); +SELECT * FROM aggregate_cursor_first_page('newdb', '{ "aggregate": "source", "pipeline": [ {"$project" : {"data" : "updating same"} } ,{"$out" : { "db" : "newdb", "coll" : "source" } } ], "cursor": { "batchSize": 1 } }', 4294967294); +SELECT document FROM helio_api.collection('newdb', 'source'); +SELECT helio_api.drop_collection('newdb','source'); + +-- case where target collection already exist: +SELECT helio_api.insert('newdb', '{"insert":"source", "documents":[{ "_id" : 1, "data": "This is source collection"}]}'); +SELECT helio_api.insert('newdb', '{"insert":"target", "documents":[{ "_id" : 1, "data": "This is target collection"}]}'); +SELECT * FROM aggregate_cursor_first_page('newdb', '{ "aggregate": "source", "pipeline": [ {"$out" : { "db" : "newdb", "coll" : "target" } } ], "cursor": { "batchSize": 1 } }', 4294967294); +SELECT document FROM helio_api.collection('newdb', 'target'); +SELECT helio_api.drop_collection('newdb','source'); +SELECT helio_api.drop_collection('newdb','target'); + +-- when target db is different: +SELECT helio_api.insert('newdb', '{"insert":"source", "documents":[{ "_id" : 1, "data": "This is source collection"}]}'); +SELECT * FROM aggregate_cursor_first_page('newdb', '{ "aggregate": "source", "pipeline": [ {"$out" : { "db" : "db2", "coll" : "target" } } ], "cursor": { "batchSize": 1 } }', 4294967294); +SELECT document FROM helio_api.collection('db2', 'target'); +SELECT helio_api.drop_collection('newdb','source'); +SELECT helio_api.drop_collection('db2','target'); + + +-- index validation: +-- 1. If source and target are same collection, only data will get updated index should remain +SELECT helio_api.insert('newdb', '{"insert":"src", "documents":[{ "_id" : 1, "data": "This is source collection"}]}'); +SELECT helio_api_internal.create_indexes_non_concurrently('newdb', '{ "createIndexes": "src", "indexes": [{ "key": {"a": 1, "b" : 1, "c" :1}, "name": "index_1" }] }'::helio_core.bson, true); +SELECT helio_api_internal.create_indexes_non_concurrently('newdb', '{ "createIndexes": "src", "indexes": [{ "key": {"his is some index" :1}, "name": "index_2" }] }'::helio_core.bson, true); + + +SELECT bson_dollar_unwind(cursorpage, '$cursor.firstBatch') FROM helio_api.list_indexes_cursor_first_page('newdb', '{ "listIndexes": "src" }') ORDER BY 1; +SELECT * FROM aggregate_cursor_first_page('newdb', '{ "aggregate": "src", "pipeline": [ {"$project" : {"data" : "updating data"} }, {"$out" : { "db" : "newdb", "coll" : "src" } } ], "cursor": { "batchSize": 1 } }', 4294967294); +SELECT bson_dollar_unwind(cursorpage, '$cursor.firstBatch') FROM helio_api.list_indexes_cursor_first_page('newdb', '{ "listIndexes": "src" }') ORDER BY 1; +SELECT document FROM helio_api.collection('newdb', 'src'); +SELECT helio_api.drop_collection('newdb','src'); + + +-- 2. if target already exist only data will get updated index should remain +SELECT helio_api.insert('newdb', '{"insert":"src", "documents":[{ "_id" : 1, "data": "This is source collection"}]}'); +SELECT helio_api.insert('newdb', '{"insert":"tar", "documents":[{ "_id" : 1, "data": "This is target collection"}]}'); +SELECT helio_api_internal.create_indexes_non_concurrently('newdb', '{ "createIndexes": "tar", "indexes": [{ "key": {"a": 1, "b" : 1, "c" :1}, "name": "index_1" }] }'::helio_core.bson, true); +SELECT helio_api_internal.create_indexes_non_concurrently('newdb', '{ "createIndexes": "tar", "indexes": [{ "key": {"his is some index" :1}, "name": "index_2" }] }'::helio_core.bson, true); +SELECT bson_dollar_unwind(cursorpage, '$cursor.firstBatch') FROM helio_api.list_indexes_cursor_first_page('newdb', '{ "listIndexes": "tar" }') ORDER BY 1; +SELECT * FROM aggregate_cursor_first_page('newdb', '{ "aggregate": "src", "pipeline": [ {"$project" : {"data" : "updating data"} }, {"$out" : { "db" : "newdb", "coll" : "tar" } } ], "cursor": { "batchSize": 1 } }', 4294967294); +SELECT bson_dollar_unwind(cursorpage, '$cursor.firstBatch') FROM helio_api.list_indexes_cursor_first_page('newdb', '{ "listIndexes": "tar" }') ORDER BY 1; +SELECT document FROM helio_api.collection('newdb', 'tar'); +SELECT helio_api.drop_collection('newdb','src'); +SELECT helio_api.drop_collection('newdb','tar'); + +-- complex query with last stage $out: +SELECT helio_api.insert_one('newdb','source',' {"_id": 1, "name": "American Steak House", "food": ["filet", "sirloin"], "quantity": 100 , "beverages": ["beer", "wine"]}', NULL); +SELECT helio_api.insert_one('newdb','source','{ "_id": 2, "name": "Honest John Pizza", "food": ["cheese pizza", "pepperoni pizza"], "quantity": 120, "beverages": ["soda"]}', NULL); + +SELECT helio_api.insert_one('newdb','target','{ "_id": 1, "item": "filet", "restaurant_name": "American Steak House"}', NULL); +SELECT helio_api.insert_one('newdb','target','{ "_id": 2, "item": "cheese pizza", "restaurant_name": "Honest John Pizza", "drink": "lemonade"}', NULL); +SELECT helio_api.insert_one('newdb','target','{ "_id": 3, "item": "cheese pizza", "restaurant_name": "Honest John Pizza", "drink": "soda"}', NULL); + +SELECT * FROM aggregate_cursor_first_page('newdb', '{ "aggregate": "target", + "pipeline": + [ + { + "$lookup": + { + "from": "source", + "pipeline": [ { "$match": { "quantity": { "$gt": 110 } }}], + "as": "matched_docs", + "localField": "restaurant_name", + "foreignField": "name" + } + }, + {"$sort" : {"_id" : -1}} , + {"$group" :{"_id" : "$restaurant_name"}}, + {"$project" : {"matched_docs" : 0}} + ], "cursor": { "batchSize": 1 } }', 4294967294); + +SELECT document FROM helio_api.collection('newdb','target'); +SELECT helio_api.drop_collection('newdb','source'); +SELECT helio_api.drop_collection('newdb','target'); + +-- case when _id is missing from last stage: +SELECT helio_api.insert_one('newdb','source',' {"_id": 1, "name": "Test Case"}', NULL); +SELECT * FROM aggregate_cursor_first_page('newdb', '{ "aggregate": "source", "pipeline": [ {"$project" : {"_id" : 0} } ,{"$out" : "target" } ], "cursor": { "batchSize": 1 } }', 4294967294); +SELECT bson_dollar_project(document,'{"_id" : {"$gt" : ["$_id", null]} }') FROM helio_api.collection('newdb','target'); +SELECT helio_api.drop_collection('newdb','source'); +SELECT helio_api.drop_collection('newdb','target'); + +-- test when source collection is view +SELECT helio_api.insert('newdb', '{"insert":"source", "documents":[{ "_id" : 1, "a" : 1, "b" : 1 }]}'); +SELECT helio_api.create_collection_view('newdb', '{ "create": "sourceView", "viewOn": "source", "pipeline": [ { "$project": { "_id": 1, "c" : {"$add" : ["$a","$b"]} } } ] }'); +SELECT * FROM aggregate_cursor_first_page('newdb', '{ "aggregate": "sourceView", "pipeline": [ {"$out" : "target" } ], "cursor": { "batchSize": 1 } }', 4294967294); +SELECT document FROM helio_api.collection('newdb', 'target'); +SELECT helio_api.drop_collection('newdb','source'); +SELECT helio_api.drop_collection('newdb','target'); + +-- test when source is sharded: +SELECT helio_api.insert_one('newdb','source',' {"_id": 1, "name": "Test Case"}', NULL); +SELECT helio_api.shard_collection('newdb', 'source', '{ "a": "hashed" }', false); +SELECT * FROM aggregate_cursor_first_page('newdb', '{ "aggregate": "source", "pipeline": [ {"$out" : "target" } ], "cursor": { "batchSize": 1 } }', 4294967294); +SELECT document from helio_api.collection('newdb','target'); +SELECT helio_api.drop_collection('newdb','source'); +SELECT helio_api.drop_collection('newdb','target'); + +-- Negative test cases +SELECT helio_api.insert_one('newdb','source',' {"_id": 1, "name": "Test Case"}', NULL); +SELECT * FROM aggregate_cursor_first_page('newdb', '{ "aggregate": "source", "pipeline": [ {"$out" : 1 } ], "cursor": { "batchSize": 1 } }', 4294967294); +SELECT * FROM aggregate_cursor_first_page('newdb', '{ "aggregate": "source", "pipeline": [ {"$out" : {} } ], "cursor": { "batchSize": 1 } }', 4294967294); +SELECT * FROM aggregate_cursor_first_page('newdb', '{ "aggregate": "source", "pipeline": [ {"$out" : {"db" : "a"} } ], "cursor": { "batchSize": 1 } }', 4294967294); +SELECT * FROM aggregate_cursor_first_page('newdb', '{ "aggregate": "source", "pipeline": [ {"$out" : {"coll" : "a"} } ], "cursor": { "batchSize": 1 } }', 4294967294); +SELECT * FROM aggregate_cursor_first_page('newdb', '{ "aggregate": "source", "pipeline": [ {"$out" : {"db" : "a", "coll" : "a", "other" : "a"} } ], "cursor": { "batchSize": 1 } }', 4294967294); +SELECT * FROM aggregate_cursor_first_page('newdb', '{ "aggregate": "source", "pipeline": [ {"$out" : {"db" : "a", "coll" : 1} } ], "cursor": { "batchSize": 1 } }', 4294967294); +SELECT * FROM aggregate_cursor_first_page('newdb', '{ "aggregate": "source", "pipeline": [ {"$out" : {"db" : 1, "coll" : "a"} } ], "cursor": { "batchSize": 1 } }', 4294967294); + +-- test when target is view: +SELECT helio_api.insert('newdb', '{"insert":"source", "documents":[{ "_id" : 1, "a" : 1, "b" : 1 }]}'); +SELECT helio_api.create_collection_view('newdb', '{ "create": "targetView", "viewOn": "source", "pipeline": [ { "$project": { "_id": 1, "c" : {"$add" : ["$a","$b"]} } } ] }'); +SELECT * FROM aggregate_cursor_first_page('newdb', '{ "aggregate": "source", "pipeline": [ {"$out" : "targetView" } ], "cursor": { "batchSize": 1 } }', 4294967294); +SELECT helio_api.drop_collection('newdb','source'); + +-- test when target is sharded: +SELECT helio_api.insert_one('newdb','source',' {"_id": 1, "name": "Test Case"}', NULL); +SELECT helio_api.insert_one('newdb','target',' {"_id": 1, "name": "Test Case"}', NULL); +SELECT helio_api.shard_collection('newdb', 'target', '{ "a": "hashed" }', false); +SELECT * FROM aggregate_cursor_first_page('newdb', '{ "aggregate": "source", "pipeline": [ {"$out" : "target" } ], "cursor": { "batchSize": 1 } }', 4294967294); +SELECT helio_api.drop_collection('newdb','source'); +SELECT helio_api.drop_collection('newdb','target'); + +-- let's verify we insert or update proper data in database. +--try to insert 16 MB Document +SELECT helio_api.insert_one('newdb','sourceDataValidation','{ "_id": 1, "item": "a" }' , NULL); +SELECT * FROM aggregate_cursor_first_page('newdb', FORMAT('{ "aggregate": "sourceDataValidation", "pipeline": [ {"$addFields" : { "newLargeField": "%s"} }, {"$out" : "targetDataValidation"} ], "cursor": { "batchSize": 1 } }',repeat('a', 16*1024*1024) )::bson, 4294967294); + +--try to insert bad _id field +SELECT * FROM aggregate_cursor_first_page('newdb', '{ "aggregate": "sourceDataValidation", "pipeline": [ {"$project" : {"_id" : [1,2,3]}}, {"$out" : "targetDataValidation"} ], "cursor": { "batchSize": 1 } }'); + +-- Let's take a look at explain plan + +--1) colocated tables , single shard distributed +SELECT helio_api.insert_one('newdb','explainsrc',' {"_id": 1, "name": "Test Case"}', NULL); +EXPLAIN (COSTS OFF) SELECT document FROM bson_aggregation_pipeline('newdb', '{ "aggregate": "explainsrc", "pipeline": [{"$out" : "target"} ] }'); + +--2) non colocated tables, hash shard distributed +SELECT helio_api.insert_one('db','explainsrc',' {"_id": 1, "name": "Test Case"}', NULL); +EXPLAIN (VERBOSE ON, COSTS OFF) SELECT document FROM bson_aggregation_pipeline('db', '{ "aggregate": "explainsrc", "pipeline": [{"$out" : "target"} ] }'); + +--3) sharded source +SELECT helio_api.shard_collection('newdb', 'explainsrc', '{ "a": "hashed" }', false); +EXPLAIN (VERBOSE ON, COSTS OFF) SELECT document FROM bson_aggregation_pipeline('db', '{ "aggregate": "explainsrc", "pipeline": [{"$out" : "target"} ] }'); diff --git a/mongoerrors.csv b/mongoerrors.csv index fa4acd90..ceede73f 100644 --- a/mongoerrors.csv +++ b/mongoerrors.csv @@ -53,6 +53,7 @@ BackgroundOperationInProgressForNamespace,12587,50 Location13026,13026,51 Location13027,13027,52 Location13068,13068,53 +Location13111,13111,461 MergeStageNoMatchingDocument,13113,54 DbAlreadyExists,13297,55 Location13548,13548,56 @@ -96,7 +97,8 @@ Location16879,16879,94 Location16880,16880,95 Location16882,16882,96 Location16883,16883,97 -DollarOutTempCollectionCantBeCreated,16994,98 +Location16990,16990,460 +Location16994,16994,98 Location17040,17040,99 Location17041,17041,100 Location17042,17042,101 diff --git a/pg_helio_api/include/aggregation/bson_aggregation_pipeline_private.h b/pg_helio_api/include/aggregation/bson_aggregation_pipeline_private.h index cbedd137..68e1ff74 100644 --- a/pg_helio_api/include/aggregation/bson_aggregation_pipeline_private.h +++ b/pg_helio_api/include/aggregation/bson_aggregation_pipeline_private.h @@ -176,6 +176,8 @@ Query * HandleSearch(const bson_value_t *existingValue, Query *query, /* output to collection related aggregation pipeline */ Query * HandleMerge(const bson_value_t *existingValue, Query *query, AggregationPipelineBuildContext *context); +Query * HandleOut(const bson_value_t *existingValue, Query *query, + AggregationPipelineBuildContext *context); /* atlas vector search related aggregation stages */ Query * HandleMongoNativeVectorSearch(const bson_value_t *existingValue, Query *query, diff --git a/pg_helio_api/include/utils/feature_counter.h b/pg_helio_api/include/utils/feature_counter.h index 1f99b390..697a36e9 100644 --- a/pg_helio_api/include/utils/feature_counter.h +++ b/pg_helio_api/include/utils/feature_counter.h @@ -15,7 +15,7 @@ #include #define MAX_FEATURE_NAME_LENGTH 255 -#define MAX_FEATURE_COUNT 235 +#define MAX_FEATURE_COUNT 236 /* Internal features that are not exposed */ #define INTERNAL_FEATURE_TYPE MAX_FEATURE_COUNT @@ -252,6 +252,7 @@ typedef enum FEATURE_STAGE_LOOKUP, FEATURE_STAGE_MATCH, FEATURE_STAGE_MERGE, + FEATURE_STAGE_OUT, FEATURE_STAGE_PROJECT, FEATURE_STAGE_PROJECT_FIND, FEATURE_STAGE_REPLACE_ROOT, diff --git a/pg_helio_api/include/utils/mongo_errors.h b/pg_helio_api/include/utils/mongo_errors.h index 13ff11eb..88cf8533 100644 --- a/pg_helio_api/include/utils/mongo_errors.h +++ b/pg_helio_api/include/utils/mongo_errors.h @@ -122,6 +122,7 @@ _DEFINE_MONGO_ERROR(BackgroundOperationInProgressForNamespace, 12587); _DEFINE_MONGO_ERROR(Location13026, 13026); _DEFINE_MONGO_ERROR(Location13027, 13027); _DEFINE_MONGO_ERROR(Location13068, 13068); +_DEFINE_MONGO_ERROR(Location13111, 13111); _DEFINE_MONGO_ERROR(MergeStageNoMatchingDocument, 13113); _DEFINE_MONGO_ERROR(DbAlreadyExists, 13297); _DEFINE_MONGO_ERROR(Location13548, 13548); @@ -166,7 +167,8 @@ _DEFINE_MONGO_ERROR(Location16879, 16879); _DEFINE_MONGO_ERROR(Location16880, 16880); _DEFINE_MONGO_ERROR(Location16882, 16882); _DEFINE_MONGO_ERROR(Location16883, 16883); -_DEFINE_MONGO_ERROR(DollarOutTempCollectionCantBeCreated, 16994); +_DEFINE_MONGO_ERROR(Location16990, 16990); +_DEFINE_MONGO_ERROR(Location16994, 16994); _DEFINE_MONGO_ERROR(Location17040, 17040); _DEFINE_MONGO_ERROR(Location17041, 17041); _DEFINE_MONGO_ERROR(Location17042, 17042); diff --git a/pg_helio_api/src/aggregation/bson_aggregates.c b/pg_helio_api/src/aggregation/bson_aggregates.c index b0499f72..4e85a754 100644 --- a/pg_helio_api/src/aggregation/bson_aggregates.c +++ b/pg_helio_api/src/aggregation/bson_aggregates.c @@ -302,7 +302,7 @@ bson_out_transition(PG_FUNCTION_ARGS) if (stagingCollection == NULL) { /* failed to create the staging collection. We use the word 'temporary' to match Mongo error message */ - ereport(ERROR, (errcode(MongoDollarOutTempCollectionCantBeCreated), + ereport(ERROR, (errcode(MongoLocation16994), errmsg( "failed to create temporary $out collection"))); } diff --git a/pg_helio_api/src/aggregation/bson_aggregation_output_pipeline.c b/pg_helio_api/src/aggregation/bson_aggregation_output_pipeline.c index 1a9b4e9c..c4a77976 100644 --- a/pg_helio_api/src/aggregation/bson_aggregation_output_pipeline.c +++ b/pg_helio_api/src/aggregation/bson_aggregation_output_pipeline.c @@ -34,6 +34,7 @@ #include #include #include +#include #include "io/helio_bson_core.h" #include "metadata/metadata_cache.h" @@ -51,6 +52,7 @@ #include "aggregation/bson_tree.h" #include "aggregation/bson_tree_write.h" #include "optimizer/optimizer.h" +#include "utils/query_utils.h" #include "aggregation/bson_aggregation_pipeline_private.h" @@ -99,6 +101,19 @@ typedef struct MergeArgs WhenNotMatchedAction whenNotMatched; } MergeArgs; + +/* + * Struct having parsed view of the arguments to $out stage. + */ +typedef struct OutArgs +{ + /* name of input target Databse */ + StringView targetDB; + + /* name of input target collection */ + StringView targetCollection; +} OutArgs; + /* GUC to enable $merge aggregation stage */ extern bool EnableMergeStage; @@ -108,8 +123,15 @@ extern bool EnableMergeTargetCreation; /* GUC to enable $merge across databases */ extern bool EnableMergeAcrossDB; +/* GUC to enable $out aggregation stage */ +extern bool EnableOutStage; + +extern bool EnableCollation; + static void ParseMergeStage(const bson_value_t *existingValue, const char *currentNameSpace, MergeArgs *args); +static void ParseOutStage(const bson_value_t *existingValue, const char *currentNameSpace, + OutArgs *args); static void VaildateMergeOnFieldValues(const bson_value_t *onArray, uint64 collectionId); static void RearrangeTargetListForMerge(Query *query, MongoCollection *targetCollection, @@ -145,7 +167,7 @@ static inline void AddTargetCollectionRTEDollarMerge(Query *query, MongoCollection *targetCollection); static HTAB * InitHashTableFromStringArray(const bson_value_t *onValues, int onValuesArraySize); -static inline bool ValidatePreviousStagesOfDollarMerge(Query *query); +static inline bool ValidatePreOutputStages(Query *query); static bool MergeQueryCTEWalker(Node *node, void *context); static inline void ValidateFinalPgbsonBeforeWriting(const pgbson *sourceDocument); static inline Expr * CreateSingleJoinExpr(const char *joinField, @@ -162,6 +184,7 @@ static void WriteJoinConditionToQueryDollarMergeLegacy(Query *query, Var *source Var *sourceShardKeyValueVar, Var *targetShardKeyValueVar, MergeArgs mergeArgs); +static void TruncateDataTable(int collectionId); PG_FUNCTION_INFO_V1(bson_dollar_merge_handle_when_matched); PG_FUNCTION_INFO_V1(bson_dollar_merge_add_object_id); @@ -439,7 +462,7 @@ HandleMerge(const bson_value_t *existingValue, Query *query, return query; } - ValidatePreviousStagesOfDollarMerge(query); + ValidatePreOutputStages(query); MergeArgs mergeArgs; memset(&mergeArgs, 0, sizeof(mergeArgs)); @@ -1064,9 +1087,9 @@ RearrangeTargetListForMerge(Query *query, MongoCollection *targetCollection, newTargetList = lappend(newTargetList, generatedObjectIdTE); - if (IsClusterVersionAtleastThis(1, 20, 0)) + /* 4. append bson_dollar_extract_merge_filter function so all on fields so that we can use extracted source in join condition */ + if (onValues && IsClusterVersionAtleastThis(1, 20, 0)) { - /* 4. append bson_dollar_extract_merge_filter function so all on fields so that we can use extracted source in join condition */ if (onValues->value_type == BSON_TYPE_UTF8) { newTargetList = lappend(newTargetList, @@ -1096,7 +1119,7 @@ RearrangeTargetListForMerge(Query *query, MongoCollection *targetCollection, } } - /* 4. Move all Remaining entries from the existing target list to the new target list. */ + /* 5. Move all Remaining entries from the existing target list to the new target list. */ int targetEntryIndex = 0; ListCell *cell; @@ -1170,6 +1193,7 @@ AddTargetCollectionRTEDollarMerge(Query *query, MongoCollection *targetCollectio RangeTblEntry *existingrte = list_nth(query->rtable, 0); query->rtable = list_make2(rte, existingrte); query->resultRelation = 1; + query->jointree->fromlist = list_make1(rte); } @@ -1524,10 +1548,10 @@ InitHashTableFromStringArray(const bson_value_t *inputKeyArray, int arraySize) /* - * ValidatePreviousStagesOfDollarMerge traverse query tree to fail early if $merge is used with $graphLookup + * ValidatePreOutputStages traverse query tree to fail early if $merge/$out is used with $graphLookup or contains any mutable function. */ static inline bool -ValidatePreviousStagesOfDollarMerge(Query *query) +ValidatePreOutputStages(Query *query) { /* An example of this could be when the target collection for the $lookup operation is missing, and the empty_data_table function is invoked. */ if (contain_mutable_functions((Node *) query)) @@ -1736,3 +1760,242 @@ WriteJoinConditionToQueryDollarMergeLegacy(Query *query, Var *sourceDocVar, query->jointree->quals = (Node *) make_ands_explicit(joinFilterList); } + + +/* + * Mutates the query for the $out stage + * + * Example mongo command : { $out: { "db": "targetDb", "coll" : "targetColl" } } + * sql query : + * + * MERGE INTO ONLY mongo_data.documents_3 documents_3 + * USING ( SELECT collection.document, + * '3'::bigint AS target_shard_key_value, + * helio_api_internal.bson_dollar_merge_generate_object_id(collection.document) AS generated_object_id + * FROM mongo_data.documents_2 collection + * WHERE collection.shard_key_value = '2'::bigint) agg_stage_0 + * ON documents_3.shard_key_value OPERATOR(pg_catalog.=) agg_stage_0.target_shard_key_value AND FALSE + * WHEN NOT MATCHED + * THEN INSERT (shard_key_value, object_id, document, creation_time) + * VALUES (agg_stage_0.target_shard_key_value, COALESCE(bson_get_value(agg_stage_0.document, '_id'::text), agg_stage_0.generated_object_id), helio_api_internal.bson_dollar_merge_add_object_id(agg_stage_0.document, agg_stage_0.generated_object_id), '2024-08-21 11:06:38.323204+00'::timestamp with time zone) + */ +Query * +HandleOut(const bson_value_t *existingValue, Query *query, + AggregationPipelineBuildContext *context) +{ + ReportFeatureUsage(FEATURE_STAGE_OUT); + + if (!EnableOutStage) + { + ereport(ERROR, (errcode(MongoCommandNotSupported), + errmsg("$out aggregation stage is not supported yet."))); + } + + OutArgs outArgs = { 0 }; + + memset(&outArgs, 0, sizeof(outArgs)); + ParseOutStage(existingValue, context->namespaceName, &outArgs); + ValidatePreOutputStages(query); + + MongoCollection *targetCollection = + GetMongoCollectionOrViewByNameDatum(StringViewGetTextDatum(&outArgs.targetDB), + StringViewGetTextDatum( + &outArgs.targetCollection), + RowExclusiveLock); + + + if (targetCollection) + { + bool isSourceSameAsTarget = targetCollection->collectionId == + context->mongoCollection->collectionId; + + if (targetCollection->viewDefinition != NULL) + { + ereport(ERROR, (errcode(MongoCommandNotSupportedOnView), + errmsg("Namespace %s.%s is a view, not a collection", + targetCollection->name.databaseName, + targetCollection->name.collectionName), + errhint("Namespace %s.%s is a view, not a collection", + targetCollection->name.databaseName, + targetCollection->name.collectionName))); + } + else if (targetCollection && targetCollection->shardKey != NULL) + { + ereport(ERROR, (errcode(MongoLocation28769), + errmsg("%s.%s cannot be sharded", outArgs.targetDB.string, + outArgs.targetCollection.string))); + } + else if (isSourceSameAsTarget) + { + ereport(ERROR, (errcode(MongoCommandNotSupported), + errmsg( + "The target collection cannot be the same as the source collection in $out stage."))); + } + + /* Truncate the target data table to delete all entries. This allows us to write new data into it */ + TruncateDataTable(targetCollection->collectionId); + } + else + { + /* Create the target collection if it does not exist */ + targetCollection = + CreateCollectionForInsert(StringViewGetTextDatum(&outArgs.targetDB), + StringViewGetTextDatum(&outArgs.targetCollection)); + } + + RearrangeTargetListForMerge(query, targetCollection, false, NULL); + context->expandTargetList = true; + query = MigrateQueryToSubQuery(query, context); + query->commandType = CMD_MERGE; + AddTargetCollectionRTEDollarMerge(query, targetCollection); + + /* constant for source collection */ + const int sourceCollectionVarNo = 2; /* In merge query source table is 2nd table */ + const int sourceDocAttrNo = 1; /* In source table first projector is document */ + const int sourceShardKeyValueAttrNo = 2; /* we will append shard_key_value in source query at 2nd position after document column */ + const int generatedObjectIdAttrNo = 3; /* we will append generated object_id in source query at 3rd position after shard_key_value column */ + const int targetCollectionVarNo = 1; /* In merge query target table is 1st table */ + const int targetShardKeyValueAttrNo = 1; /* From Target table we are just selecting 3 columns first one is shard_key_value */ + + Var *sourceDocVar = makeVar(sourceCollectionVarNo, sourceDocAttrNo, + BsonTypeId(), -1, + InvalidOid, 0); + Var *sourceShardKeyValueVar = makeVar(sourceCollectionVarNo, + sourceShardKeyValueAttrNo, INT8OID, -1, 0, 0); + Var *generatedObjectIdVar = makeVar(sourceCollectionVarNo, + generatedObjectIdAttrNo, BsonTypeId(), -1, 0, 0); + + Var *targetShardKeyValueVar = makeVar(targetCollectionVarNo, + targetShardKeyValueAttrNo, INT8OID, -1, 0, 0); + + query->mergeActionList = list_make1(MakeActionWhenNotMatched(WhenNotMatched_INSERT, + sourceDocVar, + generatedObjectIdVar, + sourceShardKeyValueVar, + targetCollection)); + + /* Write the join condition for $out, which will be in the form of + * `ON target.shard_key_value = source.target_shard_key_value` + * This is necessary because Citus requires the target's distributed column in the join condition. + * In any case, for $out, we always write to an empty table, so it's always whenNotMatched. */ + RangeTblRef *rtr = makeNode(RangeTblRef); + rtr->rtindex = 2; + query->jointree = makeFromExpr(list_make1(rtr), NULL); + query->jointree->quals = (Node *) make_opclause(PostgresInt4EqualOperatorOid(), + BOOLOID, false, + (Expr *) targetShardKeyValueVar, + (Expr *) sourceShardKeyValueVar, + InvalidOid, + InvalidOid); + return query; +} + + +/* + * Truncate data table corresponding to the input collection id. + */ +static void +TruncateDataTable(int collectionId) +{ + StringInfo cmdStr = makeStringInfo(); + + appendStringInfo(cmdStr, + "TRUNCATE TABLE %s.documents_%d", + ApiDataSchemaName, collectionId); + + bool isNull = false; + bool readOnly = false; + ExtensionExecuteQueryViaSPI(cmdStr->data, readOnly, SPI_OK_UTILITY, &isNull); +} + + +/* + * Parses & validates the input $out spec. + * first way : { $out : "collection-name" } + * second way : { $out : {"db" : "database-name", "coll" : "collection-name"} } + * + * Parsed outputs are placed in the OutArgs struct. + */ +static void +ParseOutStage(const bson_value_t *existingValue, const char *currentNameSpace, + OutArgs *args) +{ + if (existingValue->value_type != BSON_TYPE_DOCUMENT && existingValue->value_type != + BSON_TYPE_UTF8) + { + ereport(ERROR, (errcode(MongoLocation16990), + errmsg( + "$out only supports a string or object argument, but found %s", + BsonTypeName(existingValue->value_type)))); + } + + if (existingValue->value_type == BSON_TYPE_UTF8) + { + char *dbName = NULL; + char *dotPosition = strchr(currentNameSpace, '.'); + if (dotPosition != NULL) + { + size_t dbNameLength = dotPosition - currentNameSpace; + dbName = pnstrdup(currentNameSpace, dbNameLength); + } + + args->targetCollection = (StringView) { + .length = existingValue->value.v_utf8.len, + .string = existingValue->value.v_utf8.str + }; + + args->targetDB = CreateStringViewFromString(dbName); + return; + } + + /* parse when input is a document */ + bson_iter_t mergeIter; + BsonValueInitIterator(existingValue, &mergeIter); + + while (bson_iter_next(&mergeIter)) + { + const char *key = bson_iter_key(&mergeIter); + const bson_value_t *bsonValue = bson_iter_value(&mergeIter); + if (strcmp(key, "db") == 0) + { + if (bsonValue->value_type != BSON_TYPE_UTF8) + { + ereport(ERROR, (errcode(MongoLocation13111), + errmsg("wrong type for field (db) %s != string", + BsonTypeName(bsonValue->value_type)))); + } + + args->targetDB = (StringView) { + .length = bsonValue->value.v_utf8.len, + .string = bsonValue->value.v_utf8.str + }; + } + else if (strcmp(key, "coll") == 0) + { + if (bsonValue->value_type != BSON_TYPE_UTF8) + { + ereport(ERROR, (errcode(MongoLocation13111), + errmsg("wrong type for field (coll) %s != string", + BsonTypeName(bsonValue->value_type)))); + } + + args->targetCollection = (StringView) { + .length = bsonValue->value.v_utf8.len, + .string = bsonValue->value.v_utf8.str + }; + } + else + { + ereport(ERROR, (errcode(MongoLocation16990), + errmsg( + "If an object is passed to $out it must have exactly 2 fields: 'db' and 'coll'"))); + } + } + + if (args->targetDB.length == 0 || args->targetCollection.length == 0) + { + ereport(ERROR, (errcode(MongoLocation16994), + errmsg( + "If an object is passed to $out it must have exactly 2 fields: 'db' and 'coll'"))); + } +} diff --git a/pg_helio_api/src/aggregation/bson_aggregation_pipeline.c b/pg_helio_api/src/aggregation/bson_aggregation_pipeline.c index c5273b07..38c53032 100644 --- a/pg_helio_api/src/aggregation/bson_aggregation_pipeline.c +++ b/pg_helio_api/src/aggregation/bson_aggregation_pipeline.c @@ -523,7 +523,7 @@ static const AggregationStageDefinition StageDefinitions[] = }, { .stage = "$out", - .mutateFunc = NULL, + .mutateFunc = &HandleOut, .requiresPersistentCursor = &RequiresPersistentCursorTrue, .canInlineLookupStageFunc = NULL, .preservesStableSortOrder = false, diff --git a/pg_helio_api/src/helio_api_init.c b/pg_helio_api/src/helio_api_init.c index 6d89a3f5..95865776 100644 --- a/pg_helio_api/src/helio_api_init.c +++ b/pg_helio_api/src/helio_api_init.c @@ -244,6 +244,9 @@ bool EnableRumIndexScan = DEFAULT_ENABLE_RUM_INDEX_SCAN; #define DEFAULT_ENABLE_MERGE_STAGE true bool EnableMergeStage = DEFAULT_ENABLE_MERGE_STAGE; +#define DEFAULT_ENABLE_OUT_STAGE false +bool EnableOutStage = DEFAULT_ENABLE_OUT_STAGE; + #define DEFAULT_ENABLE_MERGE_TARGET_CREATION false bool EnableMergeTargetCreation = DEFAULT_ENABLE_MERGE_TARGET_CREATION; @@ -711,6 +714,13 @@ InitApiConfigurations(char *prefix) NULL, &EnableMergeStage, DEFAULT_ENABLE_MERGE_STAGE, PGC_USERSET, 0, NULL, NULL, NULL); + DefineCustomBoolVariable( + "helio_api.enableOutStage", + gettext_noop( + "Enables support for out stage in pg_helio_api."), + NULL, &EnableOutStage, DEFAULT_ENABLE_OUT_STAGE, + PGC_USERSET, 0, NULL, NULL, NULL); + DefineCustomBoolVariable( "helio_api.enableMergeTargetCreation", gettext_noop( diff --git a/pg_helio_api/src/infrastructure/feature_counter.c b/pg_helio_api/src/infrastructure/feature_counter.c index 8fc0e7db..c605b69c 100644 --- a/pg_helio_api/src/infrastructure/feature_counter.c +++ b/pg_helio_api/src/infrastructure/feature_counter.c @@ -265,6 +265,7 @@ static char FeatureMapping[MAX_FEATURE_COUNT][MAX_FEATURE_NAME_LENGTH] = { [FEATURE_STAGE_LOOKUP] = "lookup", [FEATURE_STAGE_MATCH] = "match", [FEATURE_STAGE_MERGE] = "merge", + [FEATURE_STAGE_OUT] = "out", [FEATURE_STAGE_PROJECT] = "project", [FEATURE_STAGE_PROJECT_FIND] = "project_find", [FEATURE_STAGE_REPLACE_ROOT] = "replace_root", diff --git a/pg_helio_api/src/metadata/metadata_cache.c b/pg_helio_api/src/metadata/metadata_cache.c index b324e731..12e91433 100644 --- a/pg_helio_api/src/metadata/metadata_cache.c +++ b/pg_helio_api/src/metadata/metadata_cache.c @@ -362,6 +362,9 @@ typedef struct HelioApiOidCacheData /* OID of the $type function for bson */ Oid BsonTypeMatchFunctionId; + /* OID of the command_bson_get_value function */ + Oid BsonGetValueFunctionId; + /* OID of the $exists function for bson */ Oid BsonExistsMatchFunctionId; @@ -618,9 +621,6 @@ typedef struct HelioApiOidCacheData /* OID of the bson_dollar_project_expression function */ Oid ApiCatalogBsonDollarLookupExpressionEvalMergeOid; - /* OID of the command_bson_get_value function */ - Oid ApiCatalogBsonGetValueFunctionId; - /* OID of the bson_dollar_project_find function */ Oid ApiCatalogBsonDollarProjectFindFunctionOid; @@ -3147,8 +3147,20 @@ BsonDollarMergeJoinFunctionOid(void) Oid BsonGetValueFunctionOid(void) { - return GetBinaryOperatorFunctionId(&Cache.ApiCatalogBsonGetValueFunctionId, - "bson_get_value", BsonTypeId(), TEXTOID); + InitializeHelioApiExtensionCache(); + + if (Cache.BsonGetValueFunctionId == InvalidOid) + { + List *functionNameList = list_make2(makeString(CoreSchemaName), + makeString("bson_get_value")); + Oid paramOids[2] = { BsonTypeId(), TEXTOID }; + bool missingOK = false; + + Cache.BsonGetValueFunctionId = + LookupFuncName(functionNameList, 2, paramOids, missingOK); + } + + return Cache.BsonGetValueFunctionId; } diff --git a/pg_helio_core/include/utils/helio_codes.txt b/pg_helio_core/include/utils/helio_codes.txt index 8251da2e..3695ffb0 100644 --- a/pg_helio_core/include/utils/helio_codes.txt +++ b/pg_helio_core/include/utils/helio_codes.txt @@ -96,7 +96,7 @@ Location16879,M002L,16879,94 Location16880,M002M,16880,95 Location16882,M002N,16882,96 Location16883,M002O,16883,97 -DollarOutTempCollectionCantBeCreated,M002P,16994,98 +Location16994,M002P,16994,98 Location17040,M002Q,17040,99 Location17041,M002R,17041,100 Location17042,M002S,17042,101 @@ -458,3 +458,5 @@ Location5371603,M00CN,5371603,456 DocumentFailedValidation,M00CO,121,457 Location605001,M00CP,605001,458 Location6050106,M00CQ,6050106,459 +Location16990,M00CR,16990,460 +Location13111,M00CS,13111,461 diff --git a/pg_helio_core/include/utils/helio_errors.h b/pg_helio_core/include/utils/helio_errors.h index 80920ff9..3ab2769f 100644 --- a/pg_helio_core/include/utils/helio_errors.h +++ b/pg_helio_core/include/utils/helio_errors.h @@ -310,9 +310,8 @@ #define ERRCODE_HELIO_LOCATION16883 MAKE_SQLSTATE('M', '0', '0', '2', 'O') #define MONGO_CODE_LOCATION16883 16883 -#define ERRCODE_HELIO_DOLLAROUTTEMPCOLLECTIONCANTBECREATED \ - MAKE_SQLSTATE('M', '0', '0', '2', 'P') -#define MONGO_CODE_DOLLAROUTTEMPCOLLECTIONCANTBECREATED 16994 +#define ERRCODE_HELIO_LOCATION16994 MAKE_SQLSTATE('M', '0', '0', '2', 'P') +#define MONGO_CODE_LOCATION16994 16994 #define ERRCODE_HELIO_LOCATION17040 MAKE_SQLSTATE('M', '0', '0', '2', 'Q') #define MONGO_CODE_LOCATION17040 17040 @@ -1441,4 +1440,10 @@ #define ERRCODE_HELIO_LOCATION6050106 MAKE_SQLSTATE('M', '0', '0', 'C', 'Q') #define MONGO_CODE_LOCATION6050106 6050106 +#define ERRCODE_HELIO_LOCATION16990 MAKE_SQLSTATE('M', '0', '0', 'C', 'R') +#define MONGO_CODE_LOCATION16990 16990 + +#define ERRCODE_HELIO_LOCATION13111 MAKE_SQLSTATE('M', '0', '0', 'C', 'S') +#define MONGO_CODE_LOCATION13111 13111 + #endif