use std::marker::PhantomData;
use mongodb::options::{Collation, DeleteOptions, Hint, WriteConcern};
use crate::collection::Collection;
use crate::filter::{AsFilter, Filter};
use crate::r#async::Client;
use bson::Document;
#[derive(Clone)]
pub struct Delete<C: Collection> {
filter: Option<bson::Document>,
many: bool,
options: DeleteOptions,
query_type: std::marker::PhantomData<C>,
}
impl<C: Collection> Default for Delete<C> {
fn default() -> Self {
Self::new()
}
}
impl<C: Collection> Delete<C> {
pub fn new() -> Self {
Self {
filter: None,
many: true,
options: DeleteOptions::default(),
query_type: PhantomData,
}
}
pub fn collation(mut self, collation: Collation) -> Self {
self.options.collation = Some(collation);
self
}
pub fn filter<F>(mut self, filter: F) -> crate::Result<Self>
where
C: AsFilter<F>,
F: Filter,
{
self.filter = Some(filter.into_document()?);
Ok(self)
}
pub fn hint(mut self, hint: Hint) -> Self {
self.options.hint = Some(hint);
self
}
pub fn many(mut self, many: bool) -> Self {
self.many = many;
self
}
pub fn write_concern(mut self, write_concern: WriteConcern) -> Self {
self.options.write_concern = Some(write_concern);
self
}
pub async fn query(self, client: &Client) -> crate::Result<u64> {
let filter = match self.filter {
Some(f) => f,
None => bson::Document::new(),
};
let result = if self.many {
client
.database()
.collection::<Document>(C::COLLECTION)
.delete_many(filter, Some(self.options))
.await
} else {
client
.database()
.collection::<Document>(C::COLLECTION)
.delete_one(filter, Some(self.options))
.await
}
.map_err(crate::error::mongodb)?;
Ok(result.deleted_count)
}
#[cfg(feature = "blocking")]
pub fn blocking(self, client: &crate::blocking::Client) -> crate::Result<u64> {
let filter = match self.filter {
Some(f) => f,
None => bson::Document::new(),
};
let resp = client.execute(crate::blocking::Request::Delete(
self.many,
C::COLLECTION,
filter,
self.options,
))?;
if let crate::blocking::Response::Delete(r) = resp {
return Ok(r.deleted_count);
}
Err(crate::error::runtime(
"incorrect response from blocking client",
))
}
}