From 9700c8450f12bcc9055c910495cf8cdd0d7ba42e Mon Sep 17 00:00:00 2001 From: Patrick Freed Date: Thu, 8 Apr 2021 14:07:12 -0400 Subject: [PATCH 1/6] remove Document as default generic --- src/client/session/test.rs | 9 ++--- src/coll/mod.rs | 4 +-- src/cursor/mod.rs | 4 +-- src/cursor/session.rs | 4 +-- src/db/mod.rs | 31 ++++------------ .../server_selection/test/in_window.rs | 3 +- src/sync/coll.rs | 6 ++-- src/sync/cursor.rs | 4 +-- src/sync/db.rs | 35 +++++-------------- src/sync/test.rs | 8 ++--- src/test/atlas_connectivity.rs | 3 +- src/test/auth_aws.rs | 3 +- src/test/client.rs | 3 +- src/test/coll.rs | 18 +++++----- src/test/documentation_examples.rs | 5 +-- src/test/util/mod.rs | 4 +-- 16 files changed, 56 insertions(+), 88 deletions(-) diff --git a/src/client/session/test.rs b/src/client/session/test.rs index e073ee877..4d88c0ed9 100644 --- a/src/client/session/test.rs +++ b/src/client/session/test.rs @@ -1,5 +1,6 @@ use std::{future::Future, time::Duration}; +use bson::Document; use futures::stream::StreamExt; use tokio::sync::RwLockReadGuard; @@ -38,7 +39,7 @@ macro_rules! db_op { macro_rules! collection_op { ($test_name:expr, $coll:ident, $body:expr) => { |client| async move { - let $coll = client.database($test_name).collection($test_name); + let $coll = client.database($test_name).collection::($test_name); $body.await.unwrap(); } }; @@ -285,7 +286,7 @@ async fn cluster_time_in_commands() { cluster_time_test("aggregate", |client| async move { client .database(function_name!()) - .collection(function_name!()) + .collection::(function_name!()) .aggregate(vec![doc! { "$match": { "x": 1 } }], None) .await }) @@ -294,7 +295,7 @@ async fn cluster_time_in_commands() { cluster_time_test("find", |client| async move { client .database(function_name!()) - .collection(function_name!()) + .collection::(function_name!()) .find(doc! {}, None) .await }) @@ -303,7 +304,7 @@ async fn cluster_time_in_commands() { cluster_time_test("insert", |client| async move { client .database(function_name!()) - .collection(function_name!()) + .collection::(function_name!()) .insert_one(doc! {}, None) .await }) diff --git a/src/coll/mod.rs b/src/coll/mod.rs index d006f800d..8dcb98a42 100644 --- a/src/coll/mod.rs +++ b/src/coll/mod.rs @@ -215,7 +215,7 @@ where &self, pipeline: impl IntoIterator, options: impl Into>, - ) -> Result { + ) -> Result> { let mut options = options.into(); resolve_options!( self, @@ -240,7 +240,7 @@ where pipeline: impl IntoIterator, options: impl Into>, session: &mut ClientSession, - ) -> Result { + ) -> Result> { let mut options = options.into(); resolve_options!( self, diff --git a/src/cursor/mod.rs b/src/cursor/mod.rs index d019d0b6d..b89e8eca5 100644 --- a/src/cursor/mod.rs +++ b/src/cursor/mod.rs @@ -81,7 +81,7 @@ use common::{GenericCursor, GetMoreProvider, GetMoreProviderResult}; /// # } /// ``` #[derive(Debug)] -pub struct Cursor +pub struct Cursor where T: DeserializeOwned + Unpin, { @@ -139,7 +139,7 @@ where let coll = self .client .database(ns.db.as_str()) - .collection(ns.coll.as_str()); + .collection::(ns.coll.as_str()); let cursor_id = self.wrapped_cursor.id(); RUNTIME.execute(async move { coll.kill_cursor(cursor_id).await }); } diff --git a/src/cursor/session.rs b/src/cursor/session.rs index eddf170ab..360edd96e 100644 --- a/src/cursor/session.rs +++ b/src/cursor/session.rs @@ -40,7 +40,7 @@ use crate::{ /// # } /// ``` #[derive(Debug)] -pub struct SessionCursor +pub struct SessionCursor where T: DeserializeOwned + Unpin, { @@ -105,7 +105,7 @@ where let coll = self .client .database(ns.db.as_str()) - .collection(ns.coll.as_str()); + .collection::(ns.coll.as_str()); let cursor_id = self.info.id; RUNTIME.execute(async move { coll.kill_cursor(cursor_id).await }); } diff --git a/src/db/mod.rs b/src/db/mod.rs index b768be653..4b6d66f16 100644 --- a/src/db/mod.rs +++ b/src/db/mod.rs @@ -129,45 +129,26 @@ impl Database { self.inner.write_concern.as_ref() } - /// Gets a handle to a collection specified by `name` of the database. The `Collection` options - /// (e.g. read preference and write concern) will default to those of the `Database`. - /// - /// This method does not send or receive anything across the wire to the database, so it can be - /// used repeatedly without incurring any costs from I/O. - pub fn collection(&self, name: &str) -> Collection { - Collection::new(self.clone(), name, None) - } - /// Gets a handle to a collection with type `T` specified by `name` of the database. The /// `Collection` options (e.g. read preference and write concern) will default to those of the /// `Database`. /// /// This method does not send or receive anything across the wire to the database, so it can be /// used repeatedly without incurring any costs from I/O. - pub fn collection_with_type(&self, name: &str) -> Collection + pub fn collection(&self, name: &str) -> Collection where T: Serialize + DeserializeOwned + Unpin + Debug, { Collection::new(self.clone(), name, None) } - /// Gets a handle to a collection specified by `name` in the cluster the `Client` is connected - /// to. Operations done with this `Collection` will use the options specified by `options` by - /// default and will otherwise default to those of the `Database`. - /// - /// This method does not send or receive anything across the wire to the database, so it can be - /// used repeatedly without incurring any costs from I/O. - pub fn collection_with_options(&self, name: &str, options: CollectionOptions) -> Collection { - Collection::new(self.clone(), name, Some(options)) - } - /// Gets a handle to a collection with type `T` specified by `name` in the cluster the `Client` /// is connected to. Operations done with this `Collection` will use the options specified by /// `options` by default and will otherwise default to those of the `Database`. /// /// This method does not send or receive anything across the wire to the database, so it can be /// used repeatedly without incurring any costs from I/O. - pub fn collection_with_type_and_options( + pub fn collection_with_options( &self, name: &str, options: CollectionOptions, @@ -213,7 +194,7 @@ impl Database { &self, filter: impl Into>, options: impl Into>, - ) -> Result { + ) -> Result> { let list_collections = ListCollections::new( self.name().to_string(), filter.into(), @@ -234,7 +215,7 @@ impl Database { filter: impl Into>, options: impl Into>, session: &mut ClientSession, - ) -> Result { + ) -> Result> { let list_collections = ListCollections::new( self.name().to_string(), filter.into(), @@ -392,7 +373,7 @@ impl Database { &self, pipeline: impl IntoIterator, options: impl Into>, - ) -> Result { + ) -> Result> { let mut options = options.into(); resolve_options!( self, @@ -417,7 +398,7 @@ impl Database { pipeline: impl IntoIterator, options: impl Into>, session: &mut ClientSession, - ) -> Result { + ) -> Result> { let mut options = options.into(); resolve_options!( self, diff --git a/src/sdam/description/topology/server_selection/test/in_window.rs b/src/sdam/description/topology/server_selection/test/in_window.rs index c5695309f..08d3b2c8f 100644 --- a/src/sdam/description/topology/server_selection/test/in_window.rs +++ b/src/sdam/description/topology/server_selection/test/in_window.rs @@ -1,6 +1,7 @@ use std::{collections::HashMap, sync::Arc, time::Duration}; use approx::abs_diff_eq; +use bson::Document; use semver::VersionReq; use serde::Deserialize; use tokio::sync::RwLockWriteGuard; @@ -157,7 +158,7 @@ async fn load_balancing_test() { for _ in 0..10 { let collection = client .database("load_balancing_test") - .collection("load_balancing_test"); + .collection::("load_balancing_test"); handles.push( RUNTIME .spawn(async move { diff --git a/src/sync/coll.rs b/src/sync/coll.rs index df19a0067..370918d0f 100644 --- a/src/sync/coll.rs +++ b/src/sync/coll.rs @@ -74,7 +74,7 @@ use crate::{ /// ``` #[derive(Clone, Debug)] -pub struct Collection +pub struct Collection where T: Serialize + DeserializeOwned + Unpin + Debug + Send + Sync, { @@ -153,7 +153,7 @@ where &self, pipeline: impl IntoIterator, options: impl Into>, - ) -> Result { + ) -> Result> { let pipeline: Vec = pipeline.into_iter().collect(); RUNTIME .block_on(self.async_collection.aggregate(pipeline, options.into())) @@ -169,7 +169,7 @@ where pipeline: impl IntoIterator, options: impl Into>, session: &mut ClientSession, - ) -> Result { + ) -> Result> { let pipeline: Vec = pipeline.into_iter().collect(); RUNTIME .block_on(self.async_collection.aggregate_with_session( diff --git a/src/sync/cursor.rs b/src/sync/cursor.rs index 5e1218df1..9b1de4065 100644 --- a/src/sync/cursor.rs +++ b/src/sync/cursor.rs @@ -69,7 +69,7 @@ use crate::{ /// # } /// ``` #[derive(Debug)] -pub struct Cursor +pub struct Cursor where T: DeserializeOwned + Unpin + Send, { @@ -116,7 +116,7 @@ where /// # } /// ``` #[derive(Debug)] -pub struct SessionCursor +pub struct SessionCursor where T: DeserializeOwned + Unpin + Send, { diff --git a/src/sync/db.rs b/src/sync/db.rs index 336f00deb..718474cec 100644 --- a/src/sync/db.rs +++ b/src/sync/db.rs @@ -86,36 +86,17 @@ impl Database { self.async_database.write_concern() } - /// Gets a handle to a collection specified by `name` of the database. The `Collection` options - /// (e.g. read preference and write concern) will default to those of the `Database`. - /// - /// This method does not send or receive anything across the wire to the database, so it can be - /// used repeatedly without incurring any costs from I/O. - pub fn collection(&self, name: &str) -> Collection { - Collection::new(self.async_database.collection(name)) - } - /// Gets a handle to a collection with type `T` specified by `name` of the database. The /// `Collection` options (e.g. read preference and write concern) will default to those of the /// `Database`. /// /// This method does not send or receive anything across the wire to the database, so it can be /// used repeatedly without incurring any costs from I/O. - pub fn collection_with_type(&self, name: &str) -> Collection + pub fn collection(&self, name: &str) -> Collection where T: Serialize + DeserializeOwned + Unpin + Debug + Send + Sync, { - Collection::new(self.async_database.collection_with_type(name)) - } - - /// Gets a handle to a collection specified by `name` in the cluster the `Client` is connected - /// to. Operations done with this `Collection` will use the options specified by `options` by - /// default and will otherwise default to those of the `Database`. - /// - /// This method does not send or receive anything across the wire to the database, so it can be - /// used repeatedly without incurring any costs from I/O. - pub fn collection_with_options(&self, name: &str, options: CollectionOptions) -> Collection { - Collection::new(self.async_database.collection_with_options(name, options)) + Collection::new(self.async_database.collection(name)) } /// Gets a handle to a collection with type `T` specified by `name` in the cluster the `Client` @@ -124,7 +105,7 @@ impl Database { /// /// This method does not send or receive anything across the wire to the database, so it can be /// used repeatedly without incurring any costs from I/O. - pub fn collection_with_type_and_options( + pub fn collection_with_options( &self, name: &str, options: CollectionOptions, @@ -134,7 +115,7 @@ impl Database { { Collection::new( self.async_database - .collection_with_type_and_options(name, options), + .collection_with_options(name, options), ) } @@ -162,7 +143,7 @@ impl Database { &self, filter: impl Into>, options: impl Into>, - ) -> Result { + ) -> Result> { RUNTIME .block_on( self.async_database @@ -179,7 +160,7 @@ impl Database { filter: impl Into>, options: impl Into>, session: &mut ClientSession, - ) -> Result { + ) -> Result> { RUNTIME .block_on(self.async_database.list_collections_with_session( filter.into(), @@ -281,7 +262,7 @@ impl Database { &self, pipeline: impl IntoIterator, options: impl Into>, - ) -> Result { + ) -> Result> { let pipeline: Vec = pipeline.into_iter().collect(); RUNTIME .block_on(self.async_database.aggregate(pipeline, options.into())) @@ -297,7 +278,7 @@ impl Database { pipeline: impl IntoIterator, options: impl Into>, session: &mut ClientSession, - ) -> Result { + ) -> Result> { let pipeline: Vec = pipeline.into_iter().collect(); RUNTIME .block_on( diff --git a/src/sync/test.rs b/src/sync/test.rs index d3dadebab..85d89b118 100644 --- a/src/sync/test.rs +++ b/src/sync/test.rs @@ -22,7 +22,7 @@ use crate::{ test::CLIENT_OPTIONS, }; -fn init_db_and_coll(client: &Client, db_name: &str, coll_name: &str) -> Collection { +fn init_db_and_coll(client: &Client, db_name: &str, coll_name: &str) -> Collection { let coll = client.database(db_name).collection(coll_name); drop_collection(&coll); coll @@ -32,7 +32,7 @@ fn init_db_and_typed_coll(client: &Client, db_name: &str, coll_name: &str) -> where T: Serialize + DeserializeOwned + Unpin + Debug + Send + Sync, { - let coll = client.database(db_name).collection_with_type(coll_name); + let coll = client.database(db_name).collection(coll_name); drop_collection(&coll); coll } @@ -166,7 +166,7 @@ fn collection() { let db_options = DatabaseOptions::builder().write_concern(wc.clone()).build(); let coll = client .database_with_options(function_name!(), db_options) - .collection(function_name!()); + .collection::(function_name!()); assert_eq!(coll.write_concern(), Some(&wc)); let coll_options = CollectionOptions::builder() @@ -174,7 +174,7 @@ fn collection() { .build(); let coll = client .database(function_name!()) - .collection_with_options(function_name!(), coll_options); + .collection_with_options::(function_name!(), coll_options); assert_eq!(coll.write_concern(), Some(&wc)); } diff --git a/src/test/atlas_connectivity.rs b/src/test/atlas_connectivity.rs index c42f1db98..905de0766 100644 --- a/src/test/atlas_connectivity.rs +++ b/src/test/atlas_connectivity.rs @@ -1,4 +1,5 @@ use crate::{bson::doc, options::ClientOptions, Client}; +use bson::Document; use trust_dns_resolver::config::ResolverConfig; async fn run_test(uri_env_var: &str, resolver_config: Option) { @@ -27,7 +28,7 @@ async fn run_test(uri_env_var: &str, resolver_config: Option) { .await .expect("isMaster should succeed"); - let coll = db.collection("test"); + let coll = db.collection::("test"); coll.find_one(None, None) .await .expect("findOne should succeed"); diff --git a/src/test/auth_aws.rs b/src/test/auth_aws.rs index 2cc44091e..95b52ac39 100644 --- a/src/test/auth_aws.rs +++ b/src/test/auth_aws.rs @@ -1,3 +1,4 @@ +use bson::Document; use tokio::sync::RwLockReadGuard; use super::{TestClient, LOCK}; @@ -8,7 +9,7 @@ async fn auth_aws() { let _guard: RwLockReadGuard<()> = LOCK.run_concurrently().await; let client = TestClient::new().await; - let coll = client.database("aws").collection("somecoll"); + let coll = client.database("aws").collection::("somecoll"); coll.find_one(None, None).await.unwrap(); } diff --git a/src/test/client.rs b/src/test/client.rs index a9db5fdcd..6c94933b3 100644 --- a/src/test/client.rs +++ b/src/test/client.rs @@ -1,5 +1,6 @@ use std::{borrow::Cow, collections::HashMap, time::Duration}; +use bson::Document; use serde::Deserialize; use tokio::sync::{RwLockReadGuard, RwLockWriteGuard}; @@ -604,7 +605,7 @@ async fn x509_auth() { let client = TestClient::with_options(Some(options)).await; client .database(function_name!()) - .collection(function_name!()) + .collection::(function_name!()) .find_one(None, None) .await .unwrap(); diff --git a/src/test/coll.rs b/src/test/coll.rs index 6d179cd86..a6c47d992 100644 --- a/src/test/coll.rs +++ b/src/test/coll.rs @@ -234,7 +234,7 @@ async fn aggregate_out() { .unwrap(); assert_eq!(result.inserted_ids.len(), 5); - let out_coll = db.collection(&format!("{}_1", function_name!())); + let out_coll = db.collection::(&format!("{}_1", function_name!())); let pipeline = vec![ doc! { "$match": { @@ -291,7 +291,7 @@ async fn kill_cursors_on_drop() { let event_client = EventClient::new().await; let coll = event_client .database(function_name!()) - .collection(function_name!()); + .collection::(function_name!()); let cursor = coll .find(None, FindOptions::builder().batch_size(1).build()) @@ -329,7 +329,7 @@ async fn no_kill_cursors_on_exhausted() { let event_client = EventClient::new().await; let coll = event_client .database(function_name!()) - .collection(function_name!()); + .collection::(function_name!()); let cursor = coll .find(None, FindOptions::builder().build()) @@ -538,7 +538,7 @@ async fn empty_insert() { let client = TestClient::new().await; let coll = client .database(function_name!()) - .collection(function_name!()); + .collection::(function_name!()); match coll .insert_many(Vec::new(), None) .await @@ -581,7 +581,7 @@ async fn allow_disk_use_test(options: FindOptions, expected_value: Option) } let coll = event_client .database(function_name!()) - .collection(function_name!()); + .collection::(function_name!()); coll.find(None, options).await.unwrap(); let events = event_client.get_command_started_events(&["find"]); @@ -607,7 +607,7 @@ async fn delete_hint_test(options: Option, name: &str) { let _guard: RwLockReadGuard<()> = LOCK.run_concurrently().await; let client = EventClient::new().await; - let coll = client.database(name).collection(name); + let coll = client.database(name).collection::(name); let _: Result = coll.delete_many(doc! {}, options.clone()).await; let events = client.get_command_started_events(&["delete"]); @@ -703,7 +703,7 @@ async fn find_one_and_delete_hint_server_version() { let _guard: RwLockReadGuard<()> = LOCK.run_concurrently().await; let client = EventClient::new().await; - let coll = client.database(function_name!()).collection("coll"); + let coll = client.database(function_name!()).collection::("coll"); let options = FindOneAndDeleteOptions::builder() .hint(Hint::Name(String::new())) @@ -745,7 +745,7 @@ async fn no_read_preference_to_standalone() { client .database(function_name!()) - .collection(function_name!()) + .collection::(function_name!()) .find_one(None, options) .await .unwrap(); @@ -984,7 +984,7 @@ async fn collection_options_inherited() { .build(); let coll = client .database(function_name!()) - .collection_with_options(function_name!(), options); + .collection_with_options::(function_name!(), options); coll.find(None, None).await.unwrap(); assert_options_inherited(&client, "find").await; diff --git a/src/test/documentation_examples.rs b/src/test/documentation_examples.rs index f7dadf911..abad822e0 100644 --- a/src/test/documentation_examples.rs +++ b/src/test/documentation_examples.rs @@ -1,3 +1,4 @@ +use bson::Document; use futures::TryStreamExt; use tokio::sync::RwLockReadGuard; @@ -1385,7 +1386,7 @@ async fn versioned_api_examples() -> Result<()> { let client = Client::with_options(options)?; let cursor = client .database("versioned_api_example") - .collection("example") + .collection::("example") .find(None, None) .await?; // End 1. @@ -1404,7 +1405,7 @@ async fn versioned_api_examples() -> Result<()> { .build(); let cursor = client .database("versioned_api_example") - .collection("example") + .collection::("example") .find(None, find_options) .await .expect_err("should fail"); diff --git a/src/test/util/mod.rs b/src/test/util/mod.rs index 48c6d992f..5cb800c64 100644 --- a/src/test/util/mod.rs +++ b/src/test/util/mod.rs @@ -192,7 +192,7 @@ impl TestClient { where T: Serialize + DeserializeOwned + Unpin + Debug, { - let coll = self.database(db_name).collection_with_type(coll_name); + let coll = self.database(db_name).collection(coll_name); drop_collection(&coll).await; coll } @@ -301,7 +301,7 @@ impl TestClient { if self.is_sharded() { let shard_info = self .database("config") - .collection("shards") + .collection::("shards") .find_one(None, None) .await .unwrap() From 7e49bd8666b25f08591565d827885ea447834f3f Mon Sep 17 00:00:00 2001 From: Patrick Freed Date: Thu, 8 Apr 2021 14:16:30 -0400 Subject: [PATCH 2/6] update doctests --- src/client/mod.rs | 4 ++-- src/client/session/test.rs | 4 +++- src/cursor/mod.rs | 4 ++-- src/cursor/session.rs | 4 ++-- src/db/mod.rs | 4 ++-- src/sync/db.rs | 5 +---- src/test/coll.rs | 4 +++- 7 files changed, 15 insertions(+), 14 deletions(-) diff --git a/src/client/mod.rs b/src/client/mod.rs index 7ab59c705..ea80dd667 100644 --- a/src/client/mod.rs +++ b/src/client/mod.rs @@ -42,7 +42,7 @@ const DEFAULT_SERVER_SELECTION_TIMEOUT: Duration = Duration::from_secs(30); /// /// ```rust /// # #[cfg(not(feature = "sync"))] -/// # use mongodb::{Client, error::Result}; +/// # use mongodb::{bson::Document, Client, error::Result}; /// # #[cfg(feature = "async-std-runtime")] /// # use async_std::task; /// # #[cfg(feature = "tokio-runtime")] @@ -56,7 +56,7 @@ const DEFAULT_SERVER_SELECTION_TIMEOUT: Duration = Duration::from_secs(30); /// let client_ref = client.clone(); /// /// task::spawn(async move { -/// let collection = client_ref.database("items").collection(&format!("coll{}", i)); +/// let collection = client_ref.database("items").collection::(&format!("coll{}", i)); /// /// // Do something with the collection /// }); diff --git a/src/client/session/test.rs b/src/client/session/test.rs index 4d88c0ed9..4ca07f1a8 100644 --- a/src/client/session/test.rs +++ b/src/client/session/test.rs @@ -39,7 +39,9 @@ macro_rules! db_op { macro_rules! collection_op { ($test_name:expr, $coll:ident, $body:expr) => { |client| async move { - let $coll = client.database($test_name).collection::($test_name); + let $coll = client + .database($test_name) + .collection::($test_name); $body.await.unwrap(); } }; diff --git a/src/cursor/mod.rs b/src/cursor/mod.rs index b89e8eca5..9a12e6da9 100644 --- a/src/cursor/mod.rs +++ b/src/cursor/mod.rs @@ -43,11 +43,11 @@ use common::{GenericCursor, GetMoreProvider, GetMoreProviderResult}; /// /// ```rust /// # use futures::stream::StreamExt; -/// # use mongodb::{Client, error::Result}; +/// # use mongodb::{bson::Document, Client, error::Result}; /// # /// # async fn do_stuff() -> Result<()> { /// # let client = Client::with_uri_str("mongodb://example.com").await?; -/// # let coll = client.database("foo").collection("bar"); +/// # let coll = client.database("foo").collection::("bar"); /// # let mut cursor = coll.find(None, None).await?; /// # /// while let Some(doc) = cursor.next().await { diff --git a/src/cursor/session.rs b/src/cursor/session.rs index 360edd96e..ca234f5f8 100644 --- a/src/cursor/session.rs +++ b/src/cursor/session.rs @@ -24,12 +24,12 @@ use crate::{ /// /// ```rust /// # use futures::stream::StreamExt; -/// # use mongodb::{Client, error::Result, ClientSession, SessionCursor}; +/// # use mongodb::{bson::Document, Client, error::Result, ClientSession, SessionCursor}; /// # /// # async fn do_stuff() -> Result<()> { /// # let client = Client::with_uri_str("mongodb://example.com").await?; /// # let mut session = client.start_session(None).await?; -/// # let coll = client.database("foo").collection("bar"); +/// # let coll = client.database("foo").collection::("bar"); /// # let mut cursor = coll.find_with_session(None, None, &mut session).await?; /// # /// while let Some(doc) = cursor.with_session(&mut session).next().await { diff --git a/src/db/mod.rs b/src/db/mod.rs index 4b6d66f16..738708bef 100644 --- a/src/db/mod.rs +++ b/src/db/mod.rs @@ -39,7 +39,7 @@ use crate::{ /// ```rust /// /// # #[cfg(not(feature = "sync"))] -/// # use mongodb::{Client, error::Result}; +/// # use mongodb::{bson::Document, Client, error::Result}; /// # #[cfg(feature = "async-std-runtime")] /// # use async_std::task; /// # #[cfg(feature = "tokio-runtime")] @@ -55,7 +55,7 @@ use crate::{ /// let db_ref = db.clone(); /// /// task::spawn(async move { -/// let collection = db_ref.collection(&format!("coll{}", i)); +/// let collection = db_ref.collection::(&format!("coll{}", i)); /// /// // Do something with the collection /// }); diff --git a/src/sync/db.rs b/src/sync/db.rs index 718474cec..1427f1e35 100644 --- a/src/sync/db.rs +++ b/src/sync/db.rs @@ -113,10 +113,7 @@ impl Database { where T: Serialize + DeserializeOwned + Unpin + Debug + Send + Sync, { - Collection::new( - self.async_database - .collection_with_options(name, options), - ) + Collection::new(self.async_database.collection_with_options(name, options)) } /// Drops the database, deleting all data, collections, users, and indexes stored in it. diff --git a/src/test/coll.rs b/src/test/coll.rs index a6c47d992..f47f653ca 100644 --- a/src/test/coll.rs +++ b/src/test/coll.rs @@ -703,7 +703,9 @@ async fn find_one_and_delete_hint_server_version() { let _guard: RwLockReadGuard<()> = LOCK.run_concurrently().await; let client = EventClient::new().await; - let coll = client.database(function_name!()).collection::("coll"); + let coll = client + .database(function_name!()) + .collection::("coll"); let options = FindOneAndDeleteOptions::builder() .hint(Hint::Name(String::new())) From 546ef0f277a461195150a925742a3a922b9e9e25 Mon Sep 17 00:00:00 2001 From: Patrick Freed Date: Thu, 8 Apr 2021 15:07:01 -0400 Subject: [PATCH 3/6] fix sync doctests --- src/sync/client.rs | 4 ++-- src/sync/cursor.rs | 8 ++++---- src/sync/db.rs | 4 ++-- 3 files changed, 8 insertions(+), 8 deletions(-) diff --git a/src/sync/client.rs b/src/sync/client.rs index c5ad8e9c7..f54e37927 100644 --- a/src/sync/client.rs +++ b/src/sync/client.rs @@ -26,7 +26,7 @@ use crate::{ /// so it can safely be shared across threads. For example: /// /// ```rust -/// # use mongodb::{sync::Client, error::Result}; +/// # use mongodb::{bson::Document, sync::Client, error::Result}; /// # /// # fn start_workers() -> Result<()> { /// let client = Client::with_uri_str("mongodb://example.com")?; @@ -35,7 +35,7 @@ use crate::{ /// let client_ref = client.clone(); /// /// std::thread::spawn(move || { -/// let collection = client_ref.database("items").collection(&format!("coll{}", i)); +/// let collection = client_ref.database("items").collection::(&format!("coll{}", i)); /// /// // Do something with the collection /// }); diff --git a/src/sync/cursor.rs b/src/sync/cursor.rs index 9b1de4065..2ca4409e4 100644 --- a/src/sync/cursor.rs +++ b/src/sync/cursor.rs @@ -32,11 +32,11 @@ use crate::{ /// documents it yields: /// /// ```rust -/// # use mongodb::{sync::Client, error::Result}; +/// # use mongodb::{bson::Document, sync::Client, error::Result}; /// # /// # fn do_stuff() -> Result<()> { /// # let client = Client::with_uri_str("mongodb://example.com")?; -/// # let coll = client.database("foo").collection("bar"); +/// # let coll = client.database("foo").collection::("bar"); /// # let mut cursor = coll.find(None, None)?; /// # /// for doc in cursor { @@ -100,12 +100,12 @@ where /// one. To iterate, retrieve a `SessionCursorHandle` using `SessionCursor::with_session`: /// /// ```rust -/// # use mongodb::{sync::Client, error::Result}; +/// # use mongodb::{bson::Document, sync::Client, error::Result}; /// # /// # fn do_stuff() -> Result<()> { /// # let client = Client::with_uri_str("mongodb://example.com")?; /// # let mut session = client.start_session(None)?; -/// # let coll = client.database("foo").collection("bar"); +/// # let coll = client.database("foo").collection::("bar"); /// # let mut cursor = coll.find_with_session(None, None, &mut session)?; /// # /// for doc in cursor.with_session(&mut session) { diff --git a/src/sync/db.rs b/src/sync/db.rs index 1427f1e35..28921a860 100644 --- a/src/sync/db.rs +++ b/src/sync/db.rs @@ -34,7 +34,7 @@ use crate::{ /// so it can safely be shared across threads. For example: /// /// ```rust -/// # use mongodb::{sync::Client, error::Result}; +/// # use mongodb::{bson::Document, sync::Client, error::Result}; /// /// # fn start_workers() -> Result<()> { /// # let client = Client::with_uri_str("mongodb://example.com")?; @@ -44,7 +44,7 @@ use crate::{ /// let db_ref = db.clone(); /// /// std::thread::spawn(move || { -/// let collection = db_ref.collection(&format!("coll{}", i)); +/// let collection = db_ref.collection::(&format!("coll{}", i)); /// /// // Do something with the collection /// }); From 861fb506e027dacc560fe24f36e5b6743b770803 Mon Sep 17 00:00:00 2001 From: Patrick Freed Date: Fri, 9 Apr 2021 16:58:42 -0400 Subject: [PATCH 4/6] update readme examples, add tests that ensure they compile --- README.md | 8 +-- tests/readme_examples.rs | 127 +++++++++++++++++++++++++++++++++++++++ 2 files changed, 131 insertions(+), 4 deletions(-) create mode 100644 tests/readme_examples.rs diff --git a/README.md b/README.md index fdbf9f40d..6cc95a3de 100644 --- a/README.md +++ b/README.md @@ -97,11 +97,11 @@ for collection_name in db.list_collection_names(None).await? { ``` #### Inserting documents into a collection ```rust -use mongodb::bson::doc; +use mongodb::bson::{doc, Document}; ``` ```rust // Get a handle to a collection in the database. -let collection = db.collection("books"); +let collection = db.collection::("books"); let docs = vec![ doc! { "title": "1984", "author": "George Orwell" }, @@ -147,14 +147,14 @@ The driver also provides a blocking sync API. See the [Installation](#enabling-t The various sync-specific types are found in the `mongodb::sync` submodule rather than in the crate's top level like in the async API. The sync API calls through to the async API internally though, so it looks and behaves similarly to it. ```rust use mongodb::{ - bson::{doc, Bson}, + bson::{doc, Bson, Document}, sync::Client, }; ``` ```rust let client = Client::with_uri_str("mongodb://localhost:27017")?; let database = client.database("mydb"); -let collection = database.collection("books"); +let collection = database.collection::("books"); let docs = vec![ doc! { "title": "1984", "author": "George Orwell" }, diff --git a/tests/readme_examples.rs b/tests/readme_examples.rs new file mode 100644 index 000000000..f35ebcc5b --- /dev/null +++ b/tests/readme_examples.rs @@ -0,0 +1,127 @@ +// This file ensures the examples from the README compile. +// Be sure not to `use` anything outside of the examples, since the examples are in charge of +// specifying anything that needs to be imported. + +#[cfg(not(feature = "sync"))] +async fn _connecting() -> mongodb::error::Result<()> { + use mongodb::{options::ClientOptions, Client}; + + // Parse a connection string into an options struct. + let mut client_options = ClientOptions::parse("mongodb://localhost:27017").await?; + + // Manually set an option. + client_options.app_name = Some("My App".to_string()); + + // Get a handle to the deployment. + let client = Client::with_options(client_options)?; + + // List the names of the databases in that deployment. + for db_name in client.list_database_names(None, None).await? { + println!("{}", db_name); + } + + Ok(()) +} + +#[cfg(not(feature = "sync"))] +async fn _getting_handle_to_database(client: mongodb::Client) -> mongodb::error::Result<()> { + // Get a handle to a database. + let db = client.database("mydb"); + + // List the names of the collections in that database. + for collection_name in db.list_collection_names(None).await? { + println!("{}", collection_name); + } + + Ok(()) +} + +#[cfg(not(feature = "sync"))] +async fn _inserting_documents_into_a_collection( + db: mongodb::Database, +) -> mongodb::error::Result<()> { + use mongodb::bson::{doc, Document}; + + // Get a handle to a collection in the database. + let collection = db.collection::("books"); + + let docs = vec![ + doc! { "title": "1984", "author": "George Orwell" }, + doc! { "title": "Animal Farm", "author": "George Orwell" }, + doc! { "title": "The Great Gatsby", "author": "F. Scott Fitzgerald" }, + ]; + + // Insert some documents into the "mydb.books" collection. + collection.insert_many(docs, None).await?; + + Ok(()) +} + +#[cfg(not(feature = "sync"))] +async fn _finding_documents_into_a_collection( + collection: mongodb::Collection, +) -> mongodb::error::Result<()> { + use futures::stream::StreamExt; + use mongodb::{ + bson::{doc, Bson}, + options::FindOptions, + }; + + // Query the documents in the collection with a filter and an option. + let filter = doc! { "author": "George Orwell" }; + let find_options = FindOptions::builder().sort(doc! { "title": 1 }).build(); + let mut cursor = collection.find(filter, find_options).await?; + + // Iterate over the results of the cursor. + while let Some(result) = cursor.next().await { + match result { + Ok(document) => { + if let Some(title) = document.get("title").and_then(Bson::as_str) { + println!("title: {}", title); + } else { + println!("no title found"); + } + } + Err(e) => return Err(e.into()), + } + } + + Ok(()) +} + +#[cfg(feature = "sync")] +async fn _using_the_sync_api() -> mongodb::error::Result<()> { + use mongodb::{ + bson::{doc, Bson, Document}, + sync::Client, + }; + + let client = Client::with_uri_str("mongodb://localhost:27017")?; + let database = client.database("mydb"); + let collection = database.collection::("books"); + + let docs = vec![ + doc! { "title": "1984", "author": "George Orwell" }, + doc! { "title": "Animal Farm", "author": "George Orwell" }, + doc! { "title": "The Great Gatsby", "author": "F. Scott Fitzgerald" }, + ]; + + // Insert some documents into the "mydb.books" collection. + collection.insert_many(docs, None)?; + + let cursor = collection.find(doc! { "author": "George Orwell" }, None)?; + for result in cursor { + match result { + Ok(document) => { + if let Some(title) = document.get("title").and_then(Bson::as_str) { + println!("title: {}", title); + } else { + println!("no title found"); + } + } + Err(e) => return Err(e.into()), + } + } + + Ok(()) +} From af9f755dac336856e0844dbe05169b6dafa8db98 Mon Sep 17 00:00:00 2001 From: Patrick Freed Date: Fri, 9 Apr 2021 17:47:04 -0400 Subject: [PATCH 5/6] fix aws-ecs-test --- .evergreen/aws-ecs-test/src/main.rs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/.evergreen/aws-ecs-test/src/main.rs b/.evergreen/aws-ecs-test/src/main.rs index fa4c6c766..27c9bf7bd 100644 --- a/.evergreen/aws-ecs-test/src/main.rs +++ b/.evergreen/aws-ecs-test/src/main.rs @@ -1,4 +1,4 @@ -use mongodb::Client; +use mongodb::{bson::Document, Client}; #[tokio::main] async fn main() { @@ -7,7 +7,7 @@ async fn main() { client .database("aws") - .collection("somecoll") + .collection::("somecoll") .find_one(None, None) .await .unwrap(); From 7196276f67d3ce0fafc8230bab064f9480c2c8b4 Mon Sep 17 00:00:00 2001 From: Patrick Freed Date: Fri, 9 Apr 2021 17:54:22 -0400 Subject: [PATCH 6/6] fix clippy --- tests/readme_examples.rs | 21 ++++++++++++++------- 1 file changed, 14 insertions(+), 7 deletions(-) diff --git a/tests/readme_examples.rs b/tests/readme_examples.rs index f35ebcc5b..d792d76d4 100644 --- a/tests/readme_examples.rs +++ b/tests/readme_examples.rs @@ -2,8 +2,17 @@ // Be sure not to `use` anything outside of the examples, since the examples are in charge of // specifying anything that needs to be imported. +struct Err {} +impl From for Err { + fn from(_error: mongodb::error::Error) -> Self { + Err {} + } +} +#[allow(dead_code)] +type Result = std::result::Result; + #[cfg(not(feature = "sync"))] -async fn _connecting() -> mongodb::error::Result<()> { +async fn _connecting() -> Result<()> { use mongodb::{options::ClientOptions, Client}; // Parse a connection string into an options struct. @@ -24,7 +33,7 @@ async fn _connecting() -> mongodb::error::Result<()> { } #[cfg(not(feature = "sync"))] -async fn _getting_handle_to_database(client: mongodb::Client) -> mongodb::error::Result<()> { +async fn _getting_handle_to_database(client: mongodb::Client) -> Result<()> { // Get a handle to a database. let db = client.database("mydb"); @@ -37,9 +46,7 @@ async fn _getting_handle_to_database(client: mongodb::Client) -> mongodb::error: } #[cfg(not(feature = "sync"))] -async fn _inserting_documents_into_a_collection( - db: mongodb::Database, -) -> mongodb::error::Result<()> { +async fn _inserting_documents_into_a_collection(db: mongodb::Database) -> Result<()> { use mongodb::bson::{doc, Document}; // Get a handle to a collection in the database. @@ -60,7 +67,7 @@ async fn _inserting_documents_into_a_collection( #[cfg(not(feature = "sync"))] async fn _finding_documents_into_a_collection( collection: mongodb::Collection, -) -> mongodb::error::Result<()> { +) -> Result<()> { use futures::stream::StreamExt; use mongodb::{ bson::{doc, Bson}, @@ -90,7 +97,7 @@ async fn _finding_documents_into_a_collection( } #[cfg(feature = "sync")] -async fn _using_the_sync_api() -> mongodb::error::Result<()> { +async fn _using_the_sync_api() -> Result<()> { use mongodb::{ bson::{doc, Bson, Document}, sync::Client,