From 8233bf2fb3180ff83c2cdbb77c1effdd0f080418 Mon Sep 17 00:00:00 2001 From: Parag Jain Date: Mon, 12 May 2025 08:23:14 +0000 Subject: [PATCH] Merged PR 1661768: [Perf] Write Optimization for new tables. Creating new tables with 3 columns ### Does this PR have any customer impact? ### Type (Feature, Refactoring, Bugfix, DevOps, Testing, Perf, etc) ### Does it involve schema level changes? (Table, Column, Index, UDF, etc level changes) ### Are you introducing any new config? If yes, do you have tests with and without them being set? ### ChangeLog (Refer [Template](../oss/CHANGELOG.md)) ### Description 1. Creating New tables without creation_time column. This under a GUC. 2. support of 4 col table as well as 3 col table in all code path. ---- #### AI description (iteration 1) #### PR Classification Performance optimization for creating new tables with three columns. #### PR Summary This pull request introduces performance improvements for creating new tables with three columns in the document database. It includes tests for operations on both three-column and four-column tables. - Added `three_column_data_table.out` to test the creation and operations on tables with three columns, including insert, update, and aggregate operations. - Demonstrated the use of GUC (Grand Unified Configuration) to enable and disable creation time for data tables, affecting table operations. --- .../src/test/regress/basic_schedule_core | 7 +- .../expected/three_column_data_table.out | 242 ++++++++++++++++++ .../regress/sql/three_column_data_table.sql | 86 +++++++ .../bson_aggregation_output_pipeline.c | 16 +- .../aggregation/bson_aggregation_pipeline.c | 11 +- .../src/commands/create_collection_core.c | 18 +- pg_documentdb/src/commands/insert.c | 104 +++++--- .../src/configs/feature_flag_configs.c | 12 + pg_documentdb/src/metadata/collection.c | 5 +- pg_documentdb/src/sharding/sharding.c | 21 +- 10 files changed, 473 insertions(+), 49 deletions(-) create mode 100644 internal/pg_documentdb_distributed/src/test/regress/expected/three_column_data_table.out create mode 100644 internal/pg_documentdb_distributed/src/test/regress/sql/three_column_data_table.sql diff --git a/internal/pg_documentdb_distributed/src/test/regress/basic_schedule_core b/internal/pg_documentdb_distributed/src/test/regress/basic_schedule_core index 3ae72bf2..1d16325b 100644 --- a/internal/pg_documentdb_distributed/src/test/regress/basic_schedule_core +++ b/internal/pg_documentdb_distributed/src/test/regress/basic_schedule_core @@ -132,4 +132,9 @@ test: cursors_seqscan_sharded # # See comments written for lock acquisition steps performed between Phase-1 # and Phase-2 index builds in DefineIndex(): -test: collection_management \ No newline at end of file +test: collection_management + +# We want to test the merge stage with the GUC enableDataTableWithoutCreationTime enabled. +# However, since the merge operation does not work within a transaction, +# we cannot set this GUC inside one. This is why the test is not being run concurrently. +test: three_column_data_table \ No newline at end of file diff --git a/internal/pg_documentdb_distributed/src/test/regress/expected/three_column_data_table.out b/internal/pg_documentdb_distributed/src/test/regress/expected/three_column_data_table.out new file mode 100644 index 00000000..438d87cb --- /dev/null +++ b/internal/pg_documentdb_distributed/src/test/regress/expected/three_column_data_table.out @@ -0,0 +1,242 @@ +SET search_path TO documentdb_core,documentdb_api,documentdb_api_catalog,documentdb_api_internal; +SET citus.next_shard_id TO 2930000; +SET documentdb.next_collection_id TO 293000; +SET documentdb.next_collection_index_id TO 293000; +-- create table with 4 columns first +SELECT documentdb_api.create_collection('db', '4col'); +NOTICE: creating collection + create_collection +--------------------------------------------------------------------- + t +(1 row) + +\d documentdb_data.documents_293000 + Table "documentdb_data.documents_293000" + Column | Type | Collation | Nullable | Default +--------------------------------------------------------------------- + shard_key_value | bigint | | not null | + object_id | bson | | not null | + document | bson | | not null | + creation_time | timestamp with time zone | | | +Indexes: + "collection_pk_293000" PRIMARY KEY, btree (shard_key_value, object_id) +Check constraints: + "shard_key_value_check" CHECK (shard_key_value = '293000'::bigint) + +SELECT documentdb_api.insert_one('db', '4col', '{ "_id": 1}'); + insert_one +--------------------------------------------------------------------- + { "n" : { "$numberInt" : "1" }, "ok" : { "$numberDouble" : "1.0" } } +(1 row) + +-- enable GUC +SET documentdb.enableDataTableWithoutCreationTime to on; +-- [1] let's test 4 column table after enabling GUC +-- (1.1) insert to 4 column collection +SELECT documentdb_api.insert_one('db', '4col', '{ "_id": 2}'); + insert_one +--------------------------------------------------------------------- + { "n" : { "$numberInt" : "1" }, "ok" : { "$numberDouble" : "1.0" } } +(1 row) + +-- (1.2) multiple-insert to 4 column collection +SELECT documentdb_api.insert('db', '{"insert":"4col", "documents":[ { "_id" : 3}, { "_id" : 4}, { "_id" : 5}]}'); + insert +--------------------------------------------------------------------- + ("{ ""n"" : { ""$numberInt"" : ""3"" }, ""ok"" : { ""$numberDouble"" : ""1.0"" } }",t) +(1 row) + +-- (1.3) update to 4 column collection +SELECT documentdb_api.update('db', '{"update":"4col", "updates":[{"q":{"_id":{"$eq":1}},"u":[{"$set":{"a" : 1} }]}]}'); + update +--------------------------------------------------------------------- + ("{ ""ok"" : { ""$numberDouble"" : ""1.0"" }, ""nModified"" : { ""$numberLong"" : ""1"" }, ""n"" : { ""$numberLong"" : ""1"" } }",t) +(1 row) + +-- (1.4) aggregate to 4 column collection +SELECT * FROM aggregate_cursor_first_page('db', '{ "aggregate": "4col", "pipeline": [ {"$match" : {}} ] , "cursor": { "batchSize": 10 } }', 4294967294); + cursorpage | continuation | persistconnection | cursorid +--------------------------------------------------------------------- + { "cursor" : { "id" : { "$numberLong" : "0" }, "ns" : "db.4col", "firstBatch" : [ { "_id" : { "$numberInt" : "1" }, "a" : { "$numberInt" : "1" } }, { "_id" : { "$numberInt" : "2" } }, { "_id" : { "$numberInt" : "3" } }, { "_id" : { "$numberInt" : "4" } }, { "_id" : { "$numberInt" : "5" } } ] }, "ok" : { "$numberDouble" : "1.0" } } | | f | 0 +(1 row) + +-- (1.5) aggregate to 4 column collection +SELECT * FROM aggregate_cursor_first_page('db', '{ "aggregate": "4col", "pipeline": [ {"$project" : {"a" : "GUC IS ENABLED"}},{"$merge" : { "into": "4col", "whenMatched" : "replace" , "whenNotMatched" : "insert" }} ] , "cursor": { "batchSize": 1 } }', 4294967294); + cursorpage | continuation | persistconnection | cursorid +--------------------------------------------------------------------- + { "cursor" : { "id" : { "$numberLong" : "0" }, "ns" : "db.4col", "firstBatch" : [ ] }, "ok" : { "$numberDouble" : "1.0" } } | | f | 0 +(1 row) + +SELECT * FROM aggregate_cursor_first_page('db', '{ "aggregate": "4col", "pipeline": [ {"$match" : {}} ] , "cursor": { "batchSize": 10 } }', 4294967294); + cursorpage | continuation | persistconnection | cursorid +--------------------------------------------------------------------- + { "cursor" : { "id" : { "$numberLong" : "0" }, "ns" : "db.4col", "firstBatch" : [ { "_id" : { "$numberInt" : "1" }, "a" : "GUC IS ENABLED" }, { "_id" : { "$numberInt" : "2" }, "a" : "GUC IS ENABLED" }, { "_id" : { "$numberInt" : "3" }, "a" : "GUC IS ENABLED" }, { "_id" : { "$numberInt" : "4" }, "a" : "GUC IS ENABLED" }, { "_id" : { "$numberInt" : "5" }, "a" : "GUC IS ENABLED" } ] }, "ok" : { "$numberDouble" : "1.0" } } | | f | 0 +(1 row) + +-- [2] let's test 3 column table after enabling GUC +SELECT documentdb_api.create_collection('db', '3col'); +NOTICE: creating collection + create_collection +--------------------------------------------------------------------- + t +(1 row) + +\d documentdb_data.documents_293001 + Table "documentdb_data.documents_293001" + Column | Type | Collation | Nullable | Default +--------------------------------------------------------------------- + shard_key_value | bigint | | not null | + object_id | bson | | not null | + document | bson | | not null | +Indexes: + "collection_pk_293001" PRIMARY KEY, btree (shard_key_value, object_id) +Check constraints: + "shard_key_value_check" CHECK (shard_key_value = '293001'::bigint) + +-- (2.1) insert to 3 column collection +SELECT documentdb_api.insert_one('db', '3col', '{ "_id": 2}'); + insert_one +--------------------------------------------------------------------- + { "n" : { "$numberInt" : "1" }, "ok" : { "$numberDouble" : "1.0" } } +(1 row) + +-- (2.2) multiple-insert to 3 column collection +SELECT documentdb_api.insert('db', '{"insert":"3col", "documents":[ { "_id" : 3}, { "_id" : 4}, { "_id" : 5}]}'); + insert +--------------------------------------------------------------------- + ("{ ""n"" : { ""$numberInt"" : ""3"" }, ""ok"" : { ""$numberDouble"" : ""1.0"" } }",t) +(1 row) + +-- (2.3) update to 3 column collection +SELECT documentdb_api.update('db', '{"update":"3col", "updates":[{"q":{"_id":{"$eq":1}},"u":[{"$set":{"a" : 1} }]}]}'); + update +--------------------------------------------------------------------- + ("{ ""ok"" : { ""$numberDouble"" : ""1.0"" }, ""nModified"" : { ""$numberLong"" : ""0"" }, ""n"" : { ""$numberLong"" : ""0"" } }",t) +(1 row) + +-- (2.4) aggregate to 3 column collection +SELECT * FROM aggregate_cursor_first_page('db', '{ "aggregate": "3col", "pipeline": [ {"$project" : {"a" : "GUC IS ENABLED"}},{"$merge" : { "into": "3col", "whenMatched" : "replace" , "whenNotMatched" : "insert" }} ] , "cursor": { "batchSize": 1 } }', 4294967294); + cursorpage | continuation | persistconnection | cursorid +--------------------------------------------------------------------- + { "cursor" : { "id" : { "$numberLong" : "0" }, "ns" : "db.3col", "firstBatch" : [ ] }, "ok" : { "$numberDouble" : "1.0" } } | | f | 0 +(1 row) + +SELECT * FROM aggregate_cursor_first_page('db', '{ "aggregate": "3col", "pipeline": [ {"$match" : {}} ] , "cursor": { "batchSize": 10 } }', 4294967294); + cursorpage | continuation | persistconnection | cursorid +--------------------------------------------------------------------- + { "cursor" : { "id" : { "$numberLong" : "0" }, "ns" : "db.3col", "firstBatch" : [ { "_id" : { "$numberInt" : "2" }, "a" : "GUC IS ENABLED" }, { "_id" : { "$numberInt" : "3" }, "a" : "GUC IS ENABLED" }, { "_id" : { "$numberInt" : "4" }, "a" : "GUC IS ENABLED" }, { "_id" : { "$numberInt" : "5" }, "a" : "GUC IS ENABLED" } ] }, "ok" : { "$numberDouble" : "1.0" } } | | f | 0 +(1 row) + +--3. let's disable GUC +SET documentdb.enableDataTableWithoutCreationTime to off; +-- (3.1) insert to 3 column collection +SELECT documentdb_api.insert_one('db', '3col', '{ "_id": 200}'); + insert_one +--------------------------------------------------------------------- + { "n" : { "$numberInt" : "1" }, "ok" : { "$numberDouble" : "1.0" } } +(1 row) + +-- (3.2) multiple-insert to 3 column collection +SELECT documentdb_api.insert('db', '{"insert":"3col", "documents":[ { "_id" : 300}, { "_id" : 400}, { "_id" : 500}]}'); + insert +--------------------------------------------------------------------- + ("{ ""n"" : { ""$numberInt"" : ""3"" }, ""ok"" : { ""$numberDouble"" : ""1.0"" } }",t) +(1 row) + +-- (3.3) update to 3 column collection +SELECT documentdb_api.update('db', '{"update":"3col", "updates":[{"q":{"_id":{"$eq":1}},"u":[{"$set":{"a" : 1} }]}]}'); + update +--------------------------------------------------------------------- + ("{ ""ok"" : { ""$numberDouble"" : ""1.0"" }, ""nModified"" : { ""$numberLong"" : ""0"" }, ""n"" : { ""$numberLong"" : ""0"" } }",t) +(1 row) + +-- (3.4) aggregate to 3 column collection +SELECT * FROM aggregate_cursor_first_page('db', '{ "aggregate": "3col", "pipeline": [ {"$match" : {}} ] , "cursor": { "batchSize": 1 } }', 4294967294); + cursorpage | continuation | persistconnection | cursorid +--------------------------------------------------------------------- + { "cursor" : { "id" : { "$numberLong" : "4294967294" }, "ns" : "db.3col", "firstBatch" : [ { "_id" : { "$numberInt" : "2" }, "a" : "GUC IS ENABLED" } ] }, "ok" : { "$numberDouble" : "1.0" } } | { "qi" : { "$numberLong" : "4294967294" }, "qp" : false, "qk" : { "$numberInt" : "2" }, "qc" : { "aggregate" : "3col", "pipeline" : [ { "$match" : { } } ], "cursor" : { "batchSize" : { "$numberInt" : "1" } } }, "continuation" : [ { "table_name" : "documents_293001_2930020", "value" : { "$binary" : { "base64" : "AAAAAAUA", "subType" : "00" } } } ], "numIters" : { "$numberInt" : "1" }, "sn" : NOW_SYS_VARIABLE } | f | 4294967294 +(1 row) + +-- (3.5) $merge to 4 column collection +SELECT * FROM aggregate_cursor_first_page('db', '{ "aggregate": "3col", "pipeline": [ {"$project" : {"a" : "GUC IS DISBALE"}},{"$merge" : { "into": "3col", "whenMatched" : "replace" , "whenNotMatched" : "insert" }} ] , "cursor": { "batchSize": 1 } }', 4294967294); + cursorpage | continuation | persistconnection | cursorid +--------------------------------------------------------------------- + { "cursor" : { "id" : { "$numberLong" : "0" }, "ns" : "db.3col", "firstBatch" : [ ] }, "ok" : { "$numberDouble" : "1.0" } } | | f | 0 +(1 row) + +SELECT * FROM aggregate_cursor_first_page('db', '{ "aggregate": "3col", "pipeline": [ {"$match" : {}} ] , "cursor": { "batchSize": 10 } }', 4294967294); + cursorpage | continuation | persistconnection | cursorid +--------------------------------------------------------------------- + { "cursor" : { "id" : { "$numberLong" : "0" }, "ns" : "db.3col", "firstBatch" : [ { "_id" : { "$numberInt" : "2" }, "a" : "GUC IS DISBALE" }, { "_id" : { "$numberInt" : "3" }, "a" : "GUC IS DISBALE" }, { "_id" : { "$numberInt" : "4" }, "a" : "GUC IS DISBALE" }, { "_id" : { "$numberInt" : "5" }, "a" : "GUC IS DISBALE" }, { "_id" : { "$numberInt" : "200" }, "a" : "GUC IS DISBALE" }, { "_id" : { "$numberInt" : "300" }, "a" : "GUC IS DISBALE" }, { "_id" : { "$numberInt" : "400" }, "a" : "GUC IS DISBALE" }, { "_id" : { "$numberInt" : "500" }, "a" : "GUC IS DISBALE" } ] }, "ok" : { "$numberDouble" : "1.0" } } | | f | 0 +(1 row) + +-- lookup test +-- create 4 column table for lookup +SELECT documentdb_api.insert_one('db','pipelinefroms',' {"_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 documentdb_api.insert_one('db','pipelinefroms','{ "_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) + +\d documentdb_data.documents_293002 + Table "documentdb_data.documents_293002" + Column | Type | Collation | Nullable | Default +--------------------------------------------------------------------- + shard_key_value | bigint | | not null | + object_id | bson | | not null | + document | bson | | not null | + creation_time | timestamp with time zone | | | +Indexes: + "collection_pk_293002" PRIMARY KEY, btree (shard_key_value, object_id) +Check constraints: + "shard_key_value_check" CHECK (shard_key_value = '293002'::bigint) + +-- now create table with 3 column +SET documentdb.enableDataTableWithoutCreationTime to on; +SELECT documentdb_api.insert_one('db','pipelinetos','{ "_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 documentdb_api.insert_one('db','pipelinetos','{ "_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 documentdb_api.insert_one('db','pipelinetos','{ "_id": 3, "item": "cheese pizza", "restaurant_name": "Honest John Pizza", "drink": "soda"}', NULL); + insert_one +--------------------------------------------------------------------- + { "n" : { "$numberInt" : "1" }, "ok" : { "$numberDouble" : "1.0" } } +(1 row) + +\d documentdb_data.documents_293003 + Table "documentdb_data.documents_293003" + Column | Type | Collation | Nullable | Default +--------------------------------------------------------------------- + shard_key_value | bigint | | not null | + object_id | bson | | not null | + document | bson | | not null | +Indexes: + "collection_pk_293003" PRIMARY KEY, btree (shard_key_value, object_id) +Check constraints: + "shard_key_value_check" CHECK (shard_key_value = '293003'::bigint) + +SELECT document from bson_aggregation_pipeline('db', + '{ "aggregate": "pipelinetos", "pipeline": [ { "$lookup": { "from": "pipelinefroms", "pipeline": [ { "$match": { "quantity": { "$gt": 110 } }}], "as": "matched_docs", "localField": "restaurant_name", "foreignField": "name" }} ], "cursor": {} }'); + document +--------------------------------------------------------------------- + { "_id" : { "$numberInt" : "1" }, "item" : "filet", "restaurant_name" : "American Steak House", "matched_docs" : [ ] } + { "_id" : { "$numberInt" : "2" }, "item" : "cheese pizza", "restaurant_name" : "Honest John Pizza", "drink" : "lemonade", "matched_docs" : [ { "_id" : { "$numberInt" : "2" }, "name" : "Honest John Pizza", "food" : [ "cheese pizza", "pepperoni pizza" ], "quantity" : { "$numberInt" : "120" }, "beverages" : [ "soda" ] } ] } + { "_id" : { "$numberInt" : "3" }, "item" : "cheese pizza", "restaurant_name" : "Honest John Pizza", "drink" : "soda", "matched_docs" : [ { "_id" : { "$numberInt" : "2" }, "name" : "Honest John Pizza", "food" : [ "cheese pizza", "pepperoni pizza" ], "quantity" : { "$numberInt" : "120" }, "beverages" : [ "soda" ] } ] } +(3 rows) + diff --git a/internal/pg_documentdb_distributed/src/test/regress/sql/three_column_data_table.sql b/internal/pg_documentdb_distributed/src/test/regress/sql/three_column_data_table.sql new file mode 100644 index 00000000..8c8727cf --- /dev/null +++ b/internal/pg_documentdb_distributed/src/test/regress/sql/three_column_data_table.sql @@ -0,0 +1,86 @@ +SET search_path TO documentdb_core,documentdb_api,documentdb_api_catalog,documentdb_api_internal; + +SET citus.next_shard_id TO 2930000; +SET documentdb.next_collection_id TO 293000; +SET documentdb.next_collection_index_id TO 293000; + +-- create table with 4 columns first +SELECT documentdb_api.create_collection('db', '4col'); + +\d documentdb_data.documents_293000 +SELECT documentdb_api.insert_one('db', '4col', '{ "_id": 1}'); + + +-- enable GUC +SET documentdb.enableDataTableWithoutCreationTime to on; +-- [1] let's test 4 column table after enabling GUC + +-- (1.1) insert to 4 column collection +SELECT documentdb_api.insert_one('db', '4col', '{ "_id": 2}'); + +-- (1.2) multiple-insert to 4 column collection +SELECT documentdb_api.insert('db', '{"insert":"4col", "documents":[ { "_id" : 3}, { "_id" : 4}, { "_id" : 5}]}'); + +-- (1.3) update to 4 column collection +SELECT documentdb_api.update('db', '{"update":"4col", "updates":[{"q":{"_id":{"$eq":1}},"u":[{"$set":{"a" : 1} }]}]}'); + +-- (1.4) aggregate to 4 column collection +SELECT * FROM aggregate_cursor_first_page('db', '{ "aggregate": "4col", "pipeline": [ {"$match" : {}} ] , "cursor": { "batchSize": 10 } }', 4294967294); + +-- (1.5) aggregate to 4 column collection +SELECT * FROM aggregate_cursor_first_page('db', '{ "aggregate": "4col", "pipeline": [ {"$project" : {"a" : "GUC IS ENABLED"}},{"$merge" : { "into": "4col", "whenMatched" : "replace" , "whenNotMatched" : "insert" }} ] , "cursor": { "batchSize": 1 } }', 4294967294); +SELECT * FROM aggregate_cursor_first_page('db', '{ "aggregate": "4col", "pipeline": [ {"$match" : {}} ] , "cursor": { "batchSize": 10 } }', 4294967294); + + +-- [2] let's test 3 column table after enabling GUC +SELECT documentdb_api.create_collection('db', '3col'); + +\d documentdb_data.documents_293001 + +-- (2.1) insert to 3 column collection +SELECT documentdb_api.insert_one('db', '3col', '{ "_id": 2}'); + +-- (2.2) multiple-insert to 3 column collection +SELECT documentdb_api.insert('db', '{"insert":"3col", "documents":[ { "_id" : 3}, { "_id" : 4}, { "_id" : 5}]}'); + +-- (2.3) update to 3 column collection +SELECT documentdb_api.update('db', '{"update":"3col", "updates":[{"q":{"_id":{"$eq":1}},"u":[{"$set":{"a" : 1} }]}]}'); + +-- (2.4) aggregate to 3 column collection +SELECT * FROM aggregate_cursor_first_page('db', '{ "aggregate": "3col", "pipeline": [ {"$project" : {"a" : "GUC IS ENABLED"}},{"$merge" : { "into": "3col", "whenMatched" : "replace" , "whenNotMatched" : "insert" }} ] , "cursor": { "batchSize": 1 } }', 4294967294); +SELECT * FROM aggregate_cursor_first_page('db', '{ "aggregate": "3col", "pipeline": [ {"$match" : {}} ] , "cursor": { "batchSize": 10 } }', 4294967294); + +--3. let's disable GUC +SET documentdb.enableDataTableWithoutCreationTime to off; + +-- (3.1) insert to 3 column collection +SELECT documentdb_api.insert_one('db', '3col', '{ "_id": 200}'); + +-- (3.2) multiple-insert to 3 column collection +SELECT documentdb_api.insert('db', '{"insert":"3col", "documents":[ { "_id" : 300}, { "_id" : 400}, { "_id" : 500}]}'); + +-- (3.3) update to 3 column collection +SELECT documentdb_api.update('db', '{"update":"3col", "updates":[{"q":{"_id":{"$eq":1}},"u":[{"$set":{"a" : 1} }]}]}'); + +-- (3.4) aggregate to 3 column collection +SELECT * FROM aggregate_cursor_first_page('db', '{ "aggregate": "3col", "pipeline": [ {"$match" : {}} ] , "cursor": { "batchSize": 1 } }', 4294967294); +-- (3.5) $merge to 4 column collection +SELECT * FROM aggregate_cursor_first_page('db', '{ "aggregate": "3col", "pipeline": [ {"$project" : {"a" : "GUC IS DISBALE"}},{"$merge" : { "into": "3col", "whenMatched" : "replace" , "whenNotMatched" : "insert" }} ] , "cursor": { "batchSize": 1 } }', 4294967294); +SELECT * FROM aggregate_cursor_first_page('db', '{ "aggregate": "3col", "pipeline": [ {"$match" : {}} ] , "cursor": { "batchSize": 10 } }', 4294967294); + + +-- lookup test +-- create 4 column table for lookup +SELECT documentdb_api.insert_one('db','pipelinefroms',' {"_id": 1, "name": "American Steak House", "food": ["filet", "sirloin"], "quantity": 100 , "beverages": ["beer", "wine"]}', NULL); +SELECT documentdb_api.insert_one('db','pipelinefroms','{ "_id": 2, "name": "Honest John Pizza", "food": ["cheese pizza", "pepperoni pizza"], "quantity": 120, "beverages": ["soda"]}', NULL); +\d documentdb_data.documents_293002 +-- now create table with 3 column +SET documentdb.enableDataTableWithoutCreationTime to on; +SELECT documentdb_api.insert_one('db','pipelinetos','{ "_id": 1, "item": "filet", "restaurant_name": "American Steak House"}', NULL); +SELECT documentdb_api.insert_one('db','pipelinetos','{ "_id": 2, "item": "cheese pizza", "restaurant_name": "Honest John Pizza", "drink": "lemonade"}', NULL); +SELECT documentdb_api.insert_one('db','pipelinetos','{ "_id": 3, "item": "cheese pizza", "restaurant_name": "Honest John Pizza", "drink": "soda"}', NULL); +\d documentdb_data.documents_293003 + +SELECT document from bson_aggregation_pipeline('db', + '{ "aggregate": "pipelinetos", "pipeline": [ { "$lookup": { "from": "pipelinefroms", "pipeline": [ { "$match": { "quantity": { "$gt": 110 } }}], "as": "matched_docs", "localField": "restaurant_name", "foreignField": "name" }} ], "cursor": {} }'); + diff --git a/pg_documentdb/src/aggregation/bson_aggregation_output_pipeline.c b/pg_documentdb/src/aggregation/bson_aggregation_output_pipeline.c index ce33f6b3..fa784912 100644 --- a/pg_documentdb/src/aggregation/bson_aggregation_output_pipeline.c +++ b/pg_documentdb/src/aggregation/bson_aggregation_output_pipeline.c @@ -896,7 +896,7 @@ MakeActionWhenNotMatched(WhenNotMatchedAction whenNotMatched, Var *sourceDocVar, InvalidOid, COERCE_EXPLICIT_CALL); /* for insert operation */ - action->targetList = list_make4( + action->targetList = list_make3( makeTargetEntry((Expr *) sourceShardKeyVar, DOCUMENT_DATA_TABLE_SHARD_KEY_VALUE_VAR_ATTR_NUMBER, "target_shard_key_value", false), @@ -905,12 +905,18 @@ MakeActionWhenNotMatched(WhenNotMatchedAction whenNotMatched, Var *sourceDocVar, false), makeTargetEntry((Expr *) addObjecIdFuncExpr, DOCUMENT_DATA_TABLE_DOCUMENT_VAR_ATTR_NUMBER, "document", - false), - makeTargetEntry((Expr *) nowValue, - targetCollection->mongoDataCreationTimeVarAttrNumber, - "creation_time", false)); + if (targetCollection->mongoDataCreationTimeVarAttrNumber != -1) + { + action->targetList = lappend(action->targetList, + makeTargetEntry((Expr *) nowValue, + targetCollection-> + mongoDataCreationTimeVarAttrNumber, + "creation_time", + false)); + } + return action; } diff --git a/pg_documentdb/src/aggregation/bson_aggregation_pipeline.c b/pg_documentdb/src/aggregation/bson_aggregation_pipeline.c index 42201c26..21e6aa61 100644 --- a/pg_documentdb/src/aggregation/bson_aggregation_pipeline.c +++ b/pg_documentdb/src/aggregation/bson_aggregation_pipeline.c @@ -6456,8 +6456,8 @@ GenerateBaseTableQuery(text *databaseDatum, const StringView *collectionNameView RangeTblEntry *rte = makeNode(RangeTblEntry); /* Match spec for ApiSchema.collection() function */ - List *colNames = list_make4(makeString("shard_key_value"), makeString("object_id"), - makeString("document"), makeString("creation_time")); + List *colNames = list_make3(makeString("shard_key_value"), makeString("object_id"), + makeString("document")); const char *collectionAlias = "collection"; if (context->numNestedLevels > 0 || context->nestedPipelineLevel > 0) @@ -6470,6 +6470,8 @@ GenerateBaseTableQuery(text *databaseDatum, const StringView *collectionNameView if (collection == NULL) { + colNames = lappend(colNames, makeString("creation_time")); + /* Here: Special case, if the database is config, try to see if we can create a base * table out of the system metadata. */ @@ -6516,6 +6518,11 @@ GenerateBaseTableQuery(text *databaseDatum, const StringView *collectionNameView rte->rtekind = RTE_RELATION; rte->relid = collection->relationId; + if (collection->mongoDataCreationTimeVarAttrNumber != -1) + { + colNames = lappend(colNames, makeString("creation_time")); + } + if (context->allowShardBaseTable) { Oid shardOid = TryGetCollectionShardTable(collection, AccessShareLock); diff --git a/pg_documentdb/src/commands/create_collection_core.c b/pg_documentdb/src/commands/create_collection_core.c index 9ba2791e..39ae85d3 100644 --- a/pg_documentdb/src/commands/create_collection_core.c +++ b/pg_documentdb/src/commands/create_collection_core.c @@ -25,6 +25,7 @@ extern bool EnableNativeColocation; extern bool EnableNativeTableColocation; +extern bool EnableDataTableWithoutCreationTime; static bool CanColocateAtDatabaseLevel(text *databaseDatum); static const char * CreatePostgresDataTable(uint64_t collectionId, @@ -226,13 +227,20 @@ CreatePostgresDataTable(uint64_t collectionId, const char *colocateWith, const * defined in collection.h if you decide changing definiton * or position of document column. */ - "document %s.bson not null," - - /* creation time (for TTL) */ - "creation_time timestamptz" - ")", dataTableNameInfo->data, + "document %s.bson not null", + dataTableNameInfo->data, CoreSchemaName, CoreSchemaName); + /* Let's add creation_time column only when EnableDataTableWithoutCreationTime GUC is off */ + if (EnableDataTableWithoutCreationTime) + { + appendStringInfo(createTableStringInfo, ")"); + } + else + { + appendStringInfo(createTableStringInfo, ", creation_time timestamptz)"); + } + bool readOnly = false; bool isNull = false; int shardCount = 0; diff --git a/pg_documentdb/src/commands/insert.c b/pg_documentdb/src/commands/insert.c index d1061db3..02d34280 100644 --- a/pg_documentdb/src/commands/insert.c +++ b/pg_documentdb/src/commands/insert.c @@ -129,6 +129,9 @@ static uint64 CallInsertWorkerForInsertOne(MongoCollection *collection, int64 pgbson *document, text *transactionId); static Datum CommandInsertCore(PG_FUNCTION_ARGS, bool isTransactional, MemoryContext allocContext); +static inline List * CreateValuesListForInsert(Const *shardKey, Expr *objectId, + Expr *document, AttrNumber + creationTimeVarAttNum); /* * ApiGucPrefix.enable_create_collection_on_insert GUC determines whether @@ -538,13 +541,8 @@ DoMultiInsertWithoutTransactionId(MongoCollection *collection, List *inserts, Oi PG_TRY(); { List *valuesList = NIL; - ListCell *insertCell; - TimestampTz nowValueTime = GetCurrentTimestamp(); - Const *nowValue = makeConst(TIMESTAMPTZOID, -1, InvalidOid, 8, - TimestampTzGetDatum(nowValueTime), false, true); - /* Make params for all the BSONs - we have 2 per insert - objectId/insertDoc */ int expectedNumParams = Min(list_length(inserts), BatchWriteSubTransactionCount); ParamListInfo paramListInfo = makeParamList(expectedNumParams * 2); @@ -571,8 +569,11 @@ DoMultiInsertWithoutTransactionId(MongoCollection *collection, List *inserts, Oi Expr *documentParam = CreateBsonParam(paramIndex, paramListInfo, insertDoc); paramIndex++; - List *values = list_make4(shardKeyConst, objectidParam, documentParam, - nowValue); + + List *values = CreateValuesListForInsert(shardKeyConst, objectidParam, + documentParam, + collection-> + mongoDataCreationTimeVarAttrNumber); valuesList = lappend(valuesList, values); insertCount++; @@ -873,11 +874,12 @@ ProcessInsertion(MongoCollection *collection, Int64GetDatum(shardKeyHash), false, true); Expr *objectidParam = CreateBsonParam(0, paramListInfo, objectIdPtr); Expr *documentParam = CreateBsonParam(1, paramListInfo, insertDoc); - TimestampTz nowValueTime = GetCurrentTimestamp(); - Const *nowValue = makeConst(TIMESTAMPTZOID, -1, InvalidOid, 8, - TimestampTzGetDatum(nowValueTime), false, true); - List *singleInsertList = list_make4(shardKeyConst, objectidParam, documentParam, - nowValue); + + List *singleInsertList = CreateValuesListForInsert(shardKeyConst, objectidParam, + documentParam, + collection-> + mongoDataCreationTimeVarAttrNumber); + Query *query = CreateInsertQuery(collection, optionalInsertShardOid, list_make1( singleInsertList)); uint64_t insertResult = RunInsertQuery(query, paramListInfo); @@ -1345,13 +1347,17 @@ CreateInsertQuery(MongoCollection *collection, Oid shardOid, List *valuesLists) /* Make the base table RTE */ RangeTblEntry *rte = makeNode(RangeTblEntry); - List *colNames = list_make4(makeString("shard_key_value"), makeString("object_id"), - makeString("document"), - makeString("creation_time")); + List *colNames = list_make3(makeString("shard_key_value"), makeString("object_id"), + makeString("document")); - /* If "creation_time" is the fifth column, then we should include "change_description" in the RTE. */ - if (collection->mongoDataCreationTimeVarAttrNumber == 5) + + if (collection->mongoDataCreationTimeVarAttrNumber == 4) { + colNames = lappend(colNames, makeString("creation_time")); + } + else if (collection->mongoDataCreationTimeVarAttrNumber == 5) + { + /* If "creation_time" is the fifth column, then we should include "change_description" in the RTE. */ colNames = ModifyTableColumnNames(colNames); } @@ -1385,10 +1391,15 @@ CreateInsertQuery(MongoCollection *collection, Oid shardOid, List *valuesLists) query->resultRelation = 1; /* Make the VALUES RTE */ - List *valuesColNames = list_make4(makeString("shard_key_value"), + List *valuesColNames = list_make3(makeString("shard_key_value"), makeString("object_id"), - makeString("document"), - makeString("creation_time")); + makeString("document")); + + if (collection->mongoDataCreationTimeVarAttrNumber != -1) + { + valuesColNames = lappend(valuesColNames, makeString("creation_time")); + } + RangeTblEntry *valuesRte = makeNode(RangeTblEntry); valuesRte->rtekind = RTE_VALUES; valuesRte->alias = valuesRte->eref = makeAlias("values", valuesColNames); @@ -1398,11 +1409,20 @@ CreateInsertQuery(MongoCollection *collection, Oid shardOid, List *valuesLists) valuesRte->inh = false; valuesRte->inFromCl = true; - valuesRte->coltypes = list_make4_oid(INT8OID, BsonTypeId(), BsonTypeId(), - TIMESTAMPTZOID); - valuesRte->coltypmods = list_make4_int(-1, -1, -1, -1); - valuesRte->colcollations = list_make4_oid(InvalidOid, InvalidOid, InvalidOid, - InvalidOid); + if (collection->mongoDataCreationTimeVarAttrNumber != -1) + { + valuesRte->coltypes = list_make4_oid(INT8OID, BsonTypeId(), BsonTypeId(), + TIMESTAMPTZOID); + valuesRte->coltypmods = list_make4_int(-1, -1, -1, -1); + valuesRte->colcollations = list_make4_oid(InvalidOid, InvalidOid, InvalidOid, + InvalidOid); + } + else + { + valuesRte->coltypes = list_make3_oid(INT8OID, BsonTypeId(), BsonTypeId()); + valuesRte->coltypmods = list_make3_int(-1, -1, -1); + valuesRte->colcollations = list_make3_oid(InvalidOid, InvalidOid, InvalidOid); + } query->rtable = lappend(query->rtable, valuesRte); RangeTblRef *valuesRteRef = makeNode(RangeTblRef); @@ -1412,7 +1432,7 @@ CreateInsertQuery(MongoCollection *collection, Oid shardOid, List *valuesLists) query->jointree = makeFromExpr(fromList, NULL); /* Now create the targetlist */ - query->targetList = list_make4( + query->targetList = list_make3( makeTargetEntry((Expr *) makeVar(2, 1, INT8OID, -1, InvalidOid, 0), DOCUMENT_DATA_TABLE_SHARD_KEY_VALUE_VAR_ATTR_NUMBER, "shard_key_value", false), @@ -1421,12 +1441,19 @@ CreateInsertQuery(MongoCollection *collection, Oid shardOid, List *valuesLists) false), makeTargetEntry((Expr *) makeVar(2, 3, BsonTypeId(), -1, InvalidOid, 0), DOCUMENT_DATA_TABLE_DOCUMENT_VAR_ATTR_NUMBER, "document", - false), - makeTargetEntry((Expr *) makeVar(2, 4, TIMESTAMPTZOID, -1, InvalidOid, 0), - collection->mongoDataCreationTimeVarAttrNumber, "creation_time", false) ); + if (collection->mongoDataCreationTimeVarAttrNumber != -1) + { + query->targetList = lappend(query->targetList, + makeTargetEntry((Expr *) makeVar(2, 4, TIMESTAMPTZOID, + -1, InvalidOid, 0), + collection-> + mongoDataCreationTimeVarAttrNumber, + "creation_time", false)); + } + /* In order to use a portal & SPI we create a returning list of a const */ query->returningList = list_make1( makeTargetEntry((Expr *) makeConst(INT4OID, -1, InvalidOid, 4, Int32GetDatum(1), @@ -1479,3 +1506,22 @@ RunInsertQuery(Query *insertQuery, ParamListInfo paramListInfo) return numRowsProcessed; } + + +/* indicates the presence of a creation_time column in the table, either at attribute number 4 or 5 */ +static inline List * +CreateValuesListForInsert(Const *shardKey, Expr *objectId, Expr *document, AttrNumber + creationTimeVarAttNum) +{ + if (creationTimeVarAttNum != -1) + { + TimestampTz nowValueTime = (TimestampTz) 000000000000000LL; /* "2000-01-01 00:00:00+00" */ + Const *nowValue = makeConst(TIMESTAMPTZOID, -1, InvalidOid, 8, + TimestampTzGetDatum(nowValueTime), false, true); + return list_make4(shardKey, objectId, document, nowValue); + } + else + { + return list_make3(shardKey, objectId, document); + } +} diff --git a/pg_documentdb/src/configs/feature_flag_configs.c b/pg_documentdb/src/configs/feature_flag_configs.c index be055aa7..a08a4ded 100644 --- a/pg_documentdb/src/configs/feature_flag_configs.c +++ b/pg_documentdb/src/configs/feature_flag_configs.c @@ -154,6 +154,10 @@ bool AlterCreationTimeInCompleteUpgrade = ALTER_CREATION_TIME_IN_COMPLETE_UPGRAD #define DEFAULT_ENABLE_USERNAME_PASSWORD_CONSTRAINTS true bool EnableUsernamePasswordConstraints = DEFAULT_ENABLE_USERNAME_PASSWORD_CONSTRAINTS; +#define DEFAULT_ENABLE_DATA_TABLES_WITHOUT_CREATION_TIME false +bool EnableDataTableWithoutCreationTime = + DEFAULT_ENABLE_DATA_TABLES_WITHOUT_CREATION_TIME; + /* Remove after v105 */ #define DEFAULT_SKIP_ENFORCE_TRANSACTION_READ_ONLY false bool SkipEnforceTransactionReadOnly = DEFAULT_SKIP_ENFORCE_TRANSACTION_READ_ONLY; @@ -427,4 +431,12 @@ InitializeFeatureFlagConfigurations(const char *prefix, const char *newGucPrefix NULL, &SkipEnforceTransactionReadOnly, DEFAULT_SKIP_ENFORCE_TRANSACTION_READ_ONLY, PGC_USERSET, 0, NULL, NULL, NULL); + + DefineCustomBoolVariable( + psprintf("%s.enableDataTableWithoutCreationTime", newGucPrefix), + gettext_noop( + "Create data table without creation_time column."), + NULL, &EnableDataTableWithoutCreationTime, + DEFAULT_ENABLE_DATA_TABLES_WITHOUT_CREATION_TIME, + PGC_USERSET, 0, NULL, NULL, NULL); } diff --git a/pg_documentdb/src/metadata/collection.c b/pg_documentdb/src/metadata/collection.c index 49105301..2c6a0c17 100644 --- a/pg_documentdb/src/metadata/collection.c +++ b/pg_documentdb/src/metadata/collection.c @@ -104,6 +104,7 @@ static const StringView SystemPrefix = { .length = 7, .string = "system." }; extern bool UseLocalExecutionShardQueries; extern bool EnableSchemaValidation; extern int MaxSchemaValidatorSize; +extern bool EnableDataTableWithoutCreationTime; /* user-defined functions */ PG_FUNCTION_INFO_V1(command_collection_table); @@ -1179,8 +1180,8 @@ GetMongoDataCreationTimeVarAttrNumber(Oid collectionOid) if (!HeapTupleIsValid(tuple)) { - /* If collection doesn't exist, we'll arrive here */ - return (AttrNumber) 4; + /* creation_time column is not present */ + return (AttrNumber) - 1; } Form_pg_attribute targetatt = (Form_pg_attribute) GETSTRUCT(tuple); diff --git a/pg_documentdb/src/sharding/sharding.c b/pg_documentdb/src/sharding/sharding.c index dbeaf493..9342ebba 100644 --- a/pg_documentdb/src/sharding/sharding.c +++ b/pg_documentdb/src/sharding/sharding.c @@ -1124,11 +1124,22 @@ ShardCollectionCore(ShardCollectionArgs *args) insertArgValues[1] = UInt64GetDatum(collection->collectionId); - appendStringInfo(queryInfo, - "INSERT INTO %s (shard_key_value, object_id, document, creation_time)" - " SELECT %s.get_shard_key_value($1, $2, document), object_id, document, creation_time" - " FROM %s", - tmpDataTableName, ApiInternalSchemaName, qualifiedDataTableName); + if (collection->mongoDataCreationTimeVarAttrNumber != -1) + { + appendStringInfo(queryInfo, + "INSERT INTO %s (shard_key_value, object_id, document, creation_time)" + " SELECT %s.get_shard_key_value($1, $2, document), object_id, document, creation_time" + " FROM %s", + tmpDataTableName, ApiInternalSchemaName, qualifiedDataTableName); + } + else + { + appendStringInfo(queryInfo, + "INSERT INTO %s (shard_key_value, object_id, document)" + " SELECT %s.get_shard_key_value($1, $2, document), object_id, document" + " FROM %s", + tmpDataTableName, ApiInternalSchemaName, qualifiedDataTableName); + } ExtensionExecuteQueryWithArgsViaSPI(queryInfo->data, nargs, insertArgTypes, insertArgValues, insertArgNulls, readOnly,