1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362
use futures_util::stream::StreamExt;
use serde::de::{Deserialize, DeserializeOwned};
use super::ClientSession;
use crate::{
bson::{Document, RawDocument},
error::Result,
runtime,
Cursor as AsyncCursor,
SessionCursor as AsyncSessionCursor,
SessionCursorStream,
};
/// A `Cursor` streams the result of a query. When a query is made, a `Cursor` will be returned with
/// the first batch of results from the server; the documents will be returned as the `Cursor` is
/// iterated. When the batch is exhausted and if there are more results, the `Cursor` will fetch the
/// next batch of documents, and so forth until the results are exhausted. Note that because of this
/// batching, additional network I/O may occur on any given call to `Cursor::next`. Because of this,
/// a `Cursor` iterates over `Result<Document>` items rather than simply `Document` items.
///
/// The batch size of the `Cursor` can be configured using the options to the method that returns
/// it. For example, setting the `batch_size` field of
/// [`FindOptions`](options/struct.FindOptions.html) will set the batch size of the
/// `Cursor` returned by [`Collection::find`](struct.Collection.html#method.find).
///
/// Note that the batch size determines both the number of documents stored in memory by the
/// `Cursor` at a given time as well as the total number of network round-trips needed to fetch all
/// results from the server; both of these factors should be taken into account when choosing the
/// optimal batch size.
///
/// A cursor can be used like any other [`Iterator`]. The simplest way is just to iterate over the
/// documents it yields using a for loop:
///
/// ```rust
/// # 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::<Document>("bar");
/// # let mut cursor = coll.find(None, None)?;
/// #
/// for doc in cursor {
/// println!("{}", doc?)
/// }
/// #
/// # Ok(())
/// # }
/// ```
///
/// Additionally, all the other methods that an [`Iterator`] has are available on `Cursor` as well.
/// For instance, if the number of results from a query is known to be small, it might make sense
/// to collect them into a vector:
///
/// ```rust
/// # use mongodb::{
/// # bson::{doc, Document},
/// # error::Result,
/// # sync::Client,
/// # };
/// #
/// # fn do_stuff() -> Result<()> {
/// # let client = Client::with_uri_str("mongodb://example.com")?;
/// # let coll = client.database("foo").collection("bar");
/// # let cursor = coll.find(Some(doc! { "x": 1 }), None)?;
/// #
/// let results: Vec<Result<Document>> = cursor.collect();
/// # Ok(())
/// # }
/// ```
#[derive(Debug)]
pub struct Cursor<T> {
async_cursor: AsyncCursor<T>,
}
impl<T> Cursor<T> {
pub(crate) fn new(async_cursor: AsyncCursor<T>) -> Self {
Self { async_cursor }
}
}
impl<T> Cursor<T> {
/// Move the cursor forward, potentially triggering requests to the database for more results
/// if the local buffer has been exhausted.
///
/// This will keep requesting data from the server until either the cursor is exhausted
/// or batch with results in it has been received.
///
/// The return value indicates whether new results were successfully returned (true) or if
/// the cursor has been closed (false).
///
/// Note: [`Cursor::current`] and [`Cursor::deserialize_current`] must only be called after
/// [`Cursor::advance`] returned `Ok(true)`. It is an error to call either of them without
/// calling [`Cursor::advance`] first or after [`Cursor::advance`] returns an error / false.
///
/// ```
/// # use mongodb::{sync::Client, bson::Document, error::Result};
/// # fn foo() -> Result<()> {
/// # let client = Client::with_uri_str("mongodb://localhost:27017")?;
/// # let coll = client.database("stuff").collection::<Document>("stuff");
/// let mut cursor = coll.find(None, None)?;
/// while cursor.advance()? {
/// println!("{:?}", cursor.deserialize_current()?);
/// }
/// # Ok(())
/// # }
/// ```
pub fn advance(&mut self) -> Result<bool> {
runtime::block_on(self.async_cursor.advance())
}
/// Returns a reference to the current result in the cursor.
///
/// # Panics
/// [`Cursor::advance`] must return `Ok(true)` before [`Cursor::current`] can be
/// invoked. Calling [`Cursor::current`] after [`Cursor::advance`] does not return true
/// or without calling [`Cursor::advance`] at all may result in a panic.
///
/// ```
/// # use mongodb::{sync::Client, bson::Document, error::Result};
/// # fn foo() -> Result<()> {
/// # let client = Client::with_uri_str("mongodb://localhost:27017")?;
/// # let coll = client.database("stuff").collection::<Document>("stuff");
/// let mut cursor = coll.find(None, None)?;
/// while cursor.advance()? {
/// println!("{:?}", cursor.current());
/// }
/// # Ok(())
/// # }
/// ```
pub fn current(&self) -> &RawDocument {
self.async_cursor.current()
}
/// Deserialize the current result to the generic type associated with this cursor.
///
/// # Panics
/// [`Cursor::advance`] must return `Ok(true)` before [`Cursor::deserialize_current`] can be
/// invoked. Calling [`Cursor::deserialize_current`] after [`Cursor::advance`] does not return
/// true or without calling [`Cursor::advance`] at all may result in a panic.
///
/// ```
/// # use mongodb::{sync::Client, error::Result};
/// # fn foo() -> Result<()> {
/// # let client = Client::with_uri_str("mongodb://localhost:27017")?;
/// # let db = client.database("foo");
/// use serde::Deserialize;
///
/// #[derive(Debug, Deserialize)]
/// struct Cat<'a> {
/// #[serde(borrow)]
/// name: &'a str
/// }
///
/// let coll = db.collection::<Cat>("cat");
/// let mut cursor = coll.find(None, None)?;
/// while cursor.advance()? {
/// println!("{:?}", cursor.deserialize_current()?);
/// }
/// # Ok(())
/// # }
/// ```
pub fn deserialize_current<'a>(&'a self) -> Result<T>
where
T: Deserialize<'a>,
{
self.async_cursor.deserialize_current()
}
}
impl<T> Iterator for Cursor<T>
where
T: DeserializeOwned + Unpin + Send + Sync,
{
type Item = Result<T>;
fn next(&mut self) -> Option<Self::Item> {
runtime::block_on(self.async_cursor.next())
}
}
/// A `SessionCursor` is a cursor that was created with a `ClientSession` must be iterated using
/// one. To iterate, retrieve a [`SessionCursorIter]` using [`SessionCursor::iter`]:
///
/// ```rust
/// # 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::<Document>("bar");
/// # let mut cursor = coll.find_with_session(None, None, &mut session)?;
/// #
/// for doc in cursor.iter(&mut session) {
/// println!("{}", doc?)
/// }
/// #
/// # Ok(())
/// # }
/// ```
#[derive(Debug)]
pub struct SessionCursor<T> {
async_cursor: AsyncSessionCursor<T>,
}
impl<T> SessionCursor<T> {
pub(crate) fn new(async_cursor: AsyncSessionCursor<T>) -> Self {
Self { async_cursor }
}
/// Move the cursor forward, potentially triggering requests to the database for more results
/// if the local buffer has been exhausted.
///
/// This will keep requesting data from the server until either the cursor is exhausted
/// or batch with results in it has been received.
///
/// The return value indicates whether new results were successfully returned (true) or if
/// the cursor has been closed (false).
///
/// Note: [`Cursor::current`] and [`Cursor::deserialize_current`] must only be called after
/// [`Cursor::advance`] returned `Ok(true)`. It is an error to call either of them without
/// calling [`Cursor::advance`] first or after [`Cursor::advance`] returns an error / false.
///
/// ```
/// # use mongodb::{sync::Client, bson::Document, error::Result};
/// # fn foo() -> Result<()> {
/// # let client = Client::with_uri_str("mongodb://localhost:27017")?;
/// # let mut session = client.start_session(None)?;
/// # let coll = client.database("stuff").collection::<Document>("stuff");
/// let mut cursor = coll.find_with_session(None, None, &mut session)?;
/// while cursor.advance(&mut session)? {
/// println!("{:?}", cursor.deserialize_current()?);
/// }
/// # Ok(())
/// # }
/// ```
pub fn advance(&mut self, session: &mut ClientSession) -> Result<bool> {
runtime::block_on(self.async_cursor.advance(&mut session.async_client_session))
}
/// Returns a reference to the current result in the cursor.
///
/// # Panics
/// [`Cursor::advance`] must return `Ok(true)` before [`Cursor::current`] can be
/// invoked. Calling [`Cursor::current`] after [`Cursor::advance`] does not return true
/// or without calling [`Cursor::advance`] at all may result in a panic.
///
/// ```
/// # use mongodb::{sync::Client, bson::Document, error::Result};
/// # fn foo() -> Result<()> {
/// # let client = Client::with_uri_str("mongodb://localhost:27017")?;
/// # let mut session = client.start_session(None)?;
/// # let coll = client.database("stuff").collection::<Document>("stuff");
/// let mut cursor = coll.find_with_session(None, None, &mut session)?;
/// while cursor.advance(&mut session)? {
/// println!("{:?}", cursor.current());
/// }
/// # Ok(())
/// # }
/// ```
pub fn current(&self) -> &RawDocument {
self.async_cursor.current()
}
/// Deserialize the current result to the generic type associated with this cursor.
///
/// # Panics
/// [`Cursor::advance`] must return `Ok(true)` before [`Cursor::deserialize_current`] can be
/// invoked. Calling [`Cursor::deserialize_current`] after [`Cursor::advance`] does not return
/// true or without calling [`Cursor::advance`] at all may result in a panic.
///
/// ```
/// # use mongodb::{sync::Client, error::Result};
/// # fn foo() -> Result<()> {
/// # let client = Client::with_uri_str("mongodb://localhost:27017")?;
/// # let mut session = client.start_session(None)?;
/// # let db = client.database("foo");
/// use serde::Deserialize;
///
/// #[derive(Debug, Deserialize)]
/// struct Cat<'a> {
/// #[serde(borrow)]
/// name: &'a str
/// }
///
/// let coll = db.collection::<Cat>("cat");
/// let mut cursor = coll.find_with_session(None, None, &mut session)?;
/// while cursor.advance(&mut session)? {
/// println!("{:?}", cursor.deserialize_current()?);
/// }
/// # Ok(())
/// # }
/// ```
pub fn deserialize_current<'a>(&'a self) -> Result<T>
where
T: Deserialize<'a>,
{
self.async_cursor.deserialize_current()
}
}
impl<T> SessionCursor<T>
where
T: DeserializeOwned + Unpin + Send + Sync,
{
/// Retrieves a [`SessionCursorIter`] to iterate this cursor. The session provided must be
/// the same session used to create the cursor.
pub fn iter<'session>(
&mut self,
session: &'session mut ClientSession,
) -> SessionCursorIter<'_, 'session, T> {
SessionCursorIter {
async_stream: self.async_cursor.stream(&mut session.async_client_session),
}
}
/// Retrieve the next result from the cursor.
/// The session provided must be the same session used to create the cursor.
///
/// Use this method when the session needs to be used again between iterations or when the added
/// functionality of `Iterator` is not needed.
///
/// ```
/// # use bson::{doc, Document};
/// # use mongodb::sync::Client;
/// # fn foo() -> mongodb::error::Result<()> {
/// # let client = Client::with_uri_str("foo")?;
/// # let coll = client.database("foo").collection::<Document>("bar");
/// # let other_coll = coll.clone();
/// # let mut session = client.start_session(None)?;
/// let mut cursor = coll.find_with_session(doc! { "x": 1 }, None, &mut session)?;
/// while let Some(doc) = cursor.next(&mut session).transpose()? {
/// other_coll.insert_one_with_session(doc, None, &mut session)?;
/// }
/// # Ok::<(), mongodb::error::Error>(())
/// # }
/// ```
pub fn next(&mut self, session: &mut ClientSession) -> Option<Result<T>> {
self.iter(session).next()
}
}
/// A handle that borrows a `ClientSession` temporarily for executing getMores or iterating through
/// the current buffer of a `SessionCursor`.
///
/// This updates the buffer of the parent `SessionCursor` when dropped.
pub struct SessionCursorIter<'cursor, 'session, T = Document>
where
T: DeserializeOwned + Unpin + Send + Sync,
{
async_stream: SessionCursorStream<'cursor, 'session, T>,
}
impl<T> Iterator for SessionCursorIter<'_, '_, T>
where
T: DeserializeOwned + Unpin + Send + Sync,
{
type Item = Result<T>;
fn next(&mut self) -> Option<Self::Item> {
runtime::block_on(self.async_stream.next())
}
}