use std::collections::HashMap;
use std::marker::PhantomData;
use bson::{Bson, Document};
use mongodb::options::{InsertManyOptions, WriteConcern};
use crate::collection::Collection;
use crate::r#async::Client;
#[derive(Clone)]
pub struct Insert<C: Collection> {
options: InsertManyOptions,
query_type: std::marker::PhantomData<C>,
}
impl<C: Collection> Default for Insert<C> {
fn default() -> Self {
Self::new()
}
}
impl<C: Collection> Insert<C> {
pub fn new() -> Self {
Self {
options: InsertManyOptions::default(),
query_type: PhantomData,
}
}
pub fn bypass_document_validation(mut self, enable: bool) -> Self {
self.options.bypass_document_validation = Some(enable);
self
}
pub fn ordered(mut self, enable: bool) -> Self {
self.options.ordered = Some(enable);
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,
documents: Vec<C>,
) -> crate::Result<HashMap<usize, Bson>>
where
C: Collection,
{
let documents = documents
.into_iter()
.map(|s| s.into_document())
.collect::<Result<Vec<Document>, _>>()?;
client
.database()
.collection(C::COLLECTION)
.insert_many(documents, self.options)
.await
.map(|r| r.inserted_ids)
.map_err(crate::error::mongodb)
}
#[cfg(feature = "blocking")]
pub fn blocking(
self,
client: &crate::blocking::Client,
documents: Vec<C>,
) -> crate::Result<HashMap<usize, Bson>>
where
C: Collection,
{
let documents = documents
.into_iter()
.map(|s| s.into_document())
.collect::<Result<Vec<Document>, _>>()
.map_err(crate::error::bson)?;
let resp = client.execute(crate::blocking::Request::Insert(
C::COLLECTION,
documents,
self.options,
))?;
if let crate::blocking::Response::Insert(r) = resp {
return Ok(r.inserted_ids);
}
Err(crate::error::runtime(
"incorrect response from blocking client",
))
}
}