[CXX-2294] Is it safe to use collection after connection (from which it was created) is destroyed? Created: 29/Jun/21  Updated: 27/Oct/23  Resolved: 03/Aug/21

Status: Closed
Project: C++ Driver
Component/s: None
Affects Version/s: None
Fix Version/s: None

Type: Task Priority: Unknown
Reporter: Puya Daravi Assignee: Kevin Albertson
Resolution: Gone away Votes: 0
Labels: post-5.0
Remaining Estimate: Not Specified
Time Spent: Not Specified
Original Estimate: Not Specified


 Description   

The mongocxx driver API is designed such that you get a connection object from the pool and then you get a database from the connection. Any operations then happen over that connection I assume? So my question is do I need to keep the connection object alive while I use database/collection objects? e.g.

CollectionWrapper::CollectionWrapper {
 connection = pool.acquire();
 db = connection.database("my_database");
 m_collection = db.collection("my_collection);
} // << connection object destroyed here but member variable m_collection is still alive

Or does the fact that I am keeping the collection alive is enough to ensure the connection is not returned to the pool?



 Comments   
Comment by Backlog - Core Eng Program Management Team [ 03/Aug/21 ]

There hasn't been any recent activity on this ticket, so we're resolving it. Thanks for reaching out! Please feel free to comment on this if you're able to provide more information.

Comment by Kevin Albertson [ 19/Jul/21 ]

Hi puya@motionmetrics.com, the mongocxx::pool::entry must outlive the derived child mongocxx::collection objects. But mongocxx::collection objects are relatively cheap. They contain a namespace and optional collection specific options (read concern, write concern, read preference). They are intended to be created/destroyed on demand.

The lifetime restrictions come from the C driver. A mongocxx::collection wraps a mongoc_collection_t. And a mongocxx::pool::entry wraps a pooled mongoc_client_t. The Object Lifecycle page documents the restriction. A mongoc_collection_t internally retains a pointer to the parent mongoc_client_t.

Generated at Wed Feb 07 22:05:28 UTC 2024 using Jira 9.7.1#970001-sha1:2222b88b221c4928ef0de3161136cc90c8356a66.