Skip to content

Commit 9269180

Browse files
various cleanup
1 parent 6376b32 commit 9269180

23 files changed

+203
-301
lines changed

Diff for: src/action.rs

+1-7
Original file line numberDiff line numberDiff line change
@@ -8,13 +8,7 @@ mod session;
88
mod shutdown;
99
mod watch;
1010

11-
pub use bulk_write::{
12-
error::BulkWriteError,
13-
results::BulkWriteResult,
14-
write_models::WriteModel,
15-
BulkWrite,
16-
BulkWriteOptions,
17-
};
11+
pub use bulk_write::BulkWrite;
1812
pub use drop::{DropDatabase, DropDatabaseFuture};
1913
pub use list_databases::{ListDatabases, ListSpecificationsFuture};
2014
pub use perf::{WarmConnectionPool, WarmConnectionPoolFuture};

Diff for: src/action/bulk_write.rs

+50-33
Original file line numberDiff line numberDiff line change
@@ -117,6 +117,55 @@ impl<'a> BulkWrite<'a> {
117117
}
118118
}
119119

120+
action_impl! {
121+
impl Action<'a> for BulkWrite<'a> {
122+
type Future = BulkWriteFuture;
123+
124+
async fn execute(mut self) -> Result<BulkWriteResult> {
125+
let mut total_attempted = 0;
126+
let mut execution_status = ExecutionStatus::None;
127+
128+
while total_attempted < self.models.len()
129+
&& execution_status.should_continue(self.is_ordered())
130+
{
131+
let mut operation = BulkWriteOperation::new(
132+
self.client.clone(),
133+
&self.models[total_attempted..],
134+
total_attempted,
135+
self.options.as_ref(),
136+
)
137+
.await;
138+
let result = self
139+
.client
140+
.execute_operation::<BulkWriteOperation>(
141+
&mut operation,
142+
self.session.as_deref_mut(),
143+
)
144+
.await;
145+
total_attempted += operation.n_attempted;
146+
147+
match result {
148+
Ok(result) => {
149+
execution_status = execution_status.with_success(result);
150+
}
151+
Err(error) => {
152+
execution_status = execution_status.with_failure(error);
153+
}
154+
}
155+
}
156+
157+
match execution_status {
158+
ExecutionStatus::Success(bulk_write_result) => Ok(bulk_write_result),
159+
ExecutionStatus::Error(error) => Err(error),
160+
ExecutionStatus::None => Err(ErrorKind::InvalidArgument {
161+
message: "bulk_write must be provided at least one write operation".into(),
162+
}
163+
.into()),
164+
}
165+
}
166+
}
167+
}
168+
120169
enum ExecutionStatus {
121170
Success(BulkWriteResult),
122171
Error(Error),
@@ -155,7 +204,7 @@ impl ExecutionStatus {
155204
let bulk_write_error: Error = ErrorKind::ClientBulkWrite(BulkWriteError {
156205
write_errors: HashMap::new(),
157206
write_concern_errors: Vec::new(),
158-
partial_result: Some(current_result),
207+
partial_result: current_result,
159208
})
160209
.into();
161210
Self::Error(bulk_write_error.with_source(error))
@@ -206,35 +255,3 @@ impl ExecutionStatus {
206255
}
207256
}
208257
}
209-
210-
action_impl! {
211-
impl Action<'a> for BulkWrite<'a> {
212-
type Future = SummaryBulkWrite;
213-
214-
async fn execute(mut self) -> Result<BulkWriteResult> {
215-
let mut total_attempted = 0;
216-
let mut execution_status = ExecutionStatus::None;
217-
218-
while total_attempted < self.models.len() && execution_status.should_continue(self.is_ordered()) {
219-
let mut operation = BulkWriteOperation::new(self.client.clone(), &self.models[total_attempted..], total_attempted, self.options.as_ref()).await;
220-
let result = self.client.execute_operation::<BulkWriteOperation>(&mut operation, self.session.as_deref_mut()).await;
221-
total_attempted += operation.n_attempted;
222-
223-
match result {
224-
Ok(result) => {
225-
execution_status = execution_status.with_success(result);
226-
}
227-
Err(error) => {
228-
execution_status = execution_status.with_failure(error);
229-
}
230-
}
231-
}
232-
233-
match execution_status {
234-
ExecutionStatus::Success(bulk_write_result) => Ok(bulk_write_result),
235-
ExecutionStatus::Error(error) => Err(error),
236-
ExecutionStatus::None => Err(ErrorKind::InvalidArgument { message: "bulk_write must be provided at least one write operation".into() }.into())
237-
}
238-
}
239-
}
240-
}

Diff for: src/action/bulk_write/error.rs

+3-19
Original file line numberDiff line numberDiff line change
@@ -9,33 +9,17 @@ use super::results::BulkWriteResult;
99
pub struct BulkWriteError {
1010
pub write_concern_errors: Vec<WriteConcernError>,
1111
pub write_errors: HashMap<usize, WriteError>,
12-
pub partial_result: Option<BulkWriteResult>,
12+
pub partial_result: BulkWriteResult,
1313
}
1414

1515
impl BulkWriteError {
16-
pub(crate) fn is_empty(&self) -> bool {
17-
self.write_concern_errors.is_empty()
18-
&& self.write_errors.is_empty()
19-
&& self
20-
.partial_result
21-
.as_ref()
22-
.map(|r| r.is_empty())
23-
.unwrap_or(true)
24-
}
25-
2616
pub(crate) fn merge(&mut self, other: BulkWriteError) {
2717
self.write_concern_errors.extend(other.write_concern_errors);
2818
self.write_errors.extend(other.write_errors);
29-
if let Some(other_partial_result) = other.partial_result {
30-
self.merge_results(other_partial_result);
31-
}
19+
self.merge_results(other.partial_result);
3220
}
3321

3422
pub(crate) fn merge_results(&mut self, other_result: BulkWriteResult) {
35-
if let Some(ref mut partial_result) = self.partial_result {
36-
partial_result.merge(other_result);
37-
} else {
38-
self.partial_result = Some(other_result);
39-
}
23+
self.partial_result.merge(other_result);
4024
}
4125
}

Diff for: src/action/bulk_write/results.rs

-24
Original file line numberDiff line numberDiff line change
@@ -28,30 +28,6 @@ pub struct BulkWriteResult {
2828
}
2929

3030
impl BulkWriteResult {
31-
pub(crate) fn new() -> Self {
32-
Self {
33-
inserted_count: 0,
34-
upserted_count: 0,
35-
matched_count: 0,
36-
modified_count: 0,
37-
deleted_count: 0,
38-
insert_results: HashMap::new(),
39-
update_results: HashMap::new(),
40-
delete_results: HashMap::new(),
41-
}
42-
}
43-
44-
pub(crate) fn is_empty(&self) -> bool {
45-
self.inserted_count == 0
46-
&& self.upserted_count == 0
47-
&& self.matched_count == 0
48-
&& self.modified_count == 0
49-
&& self.deleted_count == 0
50-
&& self.insert_results.is_empty()
51-
&& self.update_results.is_empty()
52-
&& self.delete_results.is_empty()
53-
}
54-
5531
pub(crate) fn populate_summary_info(&mut self, summary_info: &BulkWriteSummaryInfo) {
5632
self.inserted_count += summary_info.n_inserted;
5733
self.upserted_count += summary_info.n_upserted;

Diff for: src/action/bulk_write/write_models.rs

+14-21
Original file line numberDiff line numberDiff line change
@@ -2,8 +2,8 @@ use serde::Serialize;
22
use serde_with::skip_serializing_none;
33

44
use crate::{
5-
bson::{rawdoc, Array, Bson, Document, RawBson, RawDocumentBuf},
6-
bson_util::{extend_raw_document_buf, prepend_id_field},
5+
bson::{rawdoc, Array, Bson, Document, RawDocumentBuf},
6+
bson_util::get_or_prepend_id_field,
77
error::Result,
88
options::UpdateModifications,
99
Namespace,
@@ -18,7 +18,7 @@ pub enum WriteModel {
1818
InsertOne {
1919
#[serde(skip)]
2020
namespace: Namespace,
21-
document: RawDocumentBuf,
21+
document: Document,
2222
},
2323
#[non_exhaustive]
2424
#[serde(rename_all = "camelCase")]
@@ -125,32 +125,25 @@ impl WriteModel {
125125
}
126126
}
127127

128-
// Returns this model as a document within the bulkWrite ops list and, if this is an insert
129-
// model, the document's _id field.
130-
pub(crate) fn to_ops_document(
131-
&self,
132-
namespace_index: usize,
133-
) -> Result<(RawDocumentBuf, Option<RawBson>)> {
134-
let mut operation = rawdoc! { self.operation_name(): namespace_index as i32 };
135-
136-
let inserted_id = match self {
128+
// Returns the operation-specific fields that should be included in this model's entry in the
129+
// ops array. Also returns an inserted ID if this is an insert operation.
130+
pub(crate) fn get_ops_document_contents(&self) -> Result<(RawDocumentBuf, Option<Bson>)> {
131+
let (mut model_document, inserted_id) = match self {
137132
Self::InsertOne { document, .. } => {
138-
let mut document = document.clone();
139-
let inserted_id = prepend_id_field(&mut document)?;
140-
operation.append("document", document);
141-
Some(inserted_id)
133+
let mut insert_document = RawDocumentBuf::from_document(document)?;
134+
let inserted_id = get_or_prepend_id_field(&mut insert_document)?;
135+
(rawdoc! { "document": insert_document }, Some(inserted_id))
142136
}
143137
_ => {
144-
let operation_fields = bson::to_raw_document_buf(&self)?;
145-
extend_raw_document_buf(&mut operation, operation_fields)?;
146-
None
138+
let model_document = bson::to_raw_document_buf(&self)?;
139+
(model_document, None)
147140
}
148141
};
149142

150143
if let Some(multi) = self.multi() {
151-
operation.append("multi", multi);
144+
model_document.append("multi", multi);
152145
}
153146

154-
Ok((operation, inserted_id))
147+
Ok((model_document, inserted_id))
155148
}
156149
}

Diff for: src/bson_util.rs

+2-2
Original file line numberDiff line numberDiff line change
@@ -145,9 +145,9 @@ pub(crate) fn extend_raw_document_buf(
145145

146146
/// Returns the _id field of this document, prepending the field to the document if one is not
147147
/// already present.
148-
pub(crate) fn prepend_id_field(doc: &mut RawDocumentBuf) -> Result<RawBson> {
148+
pub(crate) fn get_or_prepend_id_field(doc: &mut RawDocumentBuf) -> Result<Bson> {
149149
match doc.get("_id")? {
150-
Some(id) => Ok(id.to_raw_bson()),
150+
Some(id) => Ok(id.try_into()?),
151151
None => {
152152
let id = ObjectId::new();
153153
let mut new_bytes = rawdoc! { "_id": id }.into_bytes();

Diff for: src/coll.rs

+7-24
Original file line numberDiff line numberDiff line change
@@ -1158,10 +1158,6 @@ where
11581158
}
11591159

11601160
let ordered = options.as_ref().and_then(|o| o.ordered).unwrap_or(true);
1161-
#[cfg(feature = "in-use-encryption-unstable")]
1162-
let encrypted = self.client().auto_encryption_opts().await.is_some();
1163-
#[cfg(not(feature = "in-use-encryption-unstable"))]
1164-
let encrypted = false;
11651161

11661162
let mut cumulative_failure: Option<BulkWriteFailure> = None;
11671163
let mut error_labels: HashSet<String> = Default::default();
@@ -1175,7 +1171,7 @@ where
11751171
self.namespace(),
11761172
docs,
11771173
options.clone(),
1178-
encrypted,
1174+
self.client().should_auto_encrypt().await,
11791175
self.inner.human_readable_serialization,
11801176
);
11811177

@@ -1300,16 +1296,11 @@ where
13001296
let mut options = options.into();
13011297
resolve_write_concern_with_session!(self, options, session.as_ref())?;
13021298

1303-
#[cfg(feature = "in-use-encryption-unstable")]
1304-
let encrypted = self.client().auto_encryption_opts().await.is_some();
1305-
#[cfg(not(feature = "in-use-encryption-unstable"))]
1306-
let encrypted = false;
1307-
13081299
let insert = Insert::new(
13091300
self.namespace(),
13101301
vec![doc],
13111302
options.map(InsertManyOptions::from_insert_one_options),
1312-
encrypted,
1303+
self.client().should_auto_encrypt().await,
13131304
self.inner.human_readable_serialization,
13141305
);
13151306
self.client()
@@ -1459,24 +1450,16 @@ impl<'de> Deserialize<'de> for Namespace {
14591450
where
14601451
D: Deserializer<'de>,
14611452
{
1462-
#[derive(Deserialize)]
1463-
struct NamespaceHelper {
1464-
db: String,
1465-
coll: String,
1466-
}
14671453
#[derive(Deserialize)]
14681454
#[serde(untagged)]
1469-
enum NamespaceOptions {
1455+
enum NamespaceHelper {
14701456
String(String),
1471-
Object(NamespaceHelper),
1457+
Object { db: String, coll: String },
14721458
}
1473-
match NamespaceOptions::deserialize(deserializer)? {
1474-
NamespaceOptions::String(string) => Self::from_str(&string)
1459+
match NamespaceHelper::deserialize(deserializer)? {
1460+
NamespaceHelper::String(string) => Self::from_str(&string)
14751461
.ok_or_else(|| D::Error::custom("Missing one or more fields in namespace")),
1476-
NamespaceOptions::Object(object) => Ok(Self {
1477-
db: object.db,
1478-
coll: object.coll,
1479-
}),
1462+
NamespaceHelper::Object { db, coll } => Ok(Self { db, coll }),
14801463
}
14811464
}
14821465
}

Diff for: src/error.rs

+3-2
Original file line numberDiff line numberDiff line change
@@ -12,7 +12,7 @@ use serde::{Deserialize, Serialize};
1212
use thiserror::Error;
1313

1414
use crate::{
15-
action::BulkWriteError as ClientBulkWriteError,
15+
action::bulk_write::error::BulkWriteError as ClientBulkWriteError,
1616
bson::Document,
1717
options::ServerAddress,
1818
sdam::TopologyVersion,
@@ -287,7 +287,7 @@ impl Error {
287287
}
288288

289289
/// Gets the code from this error.
290-
#[allow(unused)]
290+
#[cfg(test)]
291291
pub(crate) fn code(&self) -> Option<i32> {
292292
match self.kind.as_ref() {
293293
ErrorKind::Command(command_error) => Some(command_error.code),
@@ -878,6 +878,7 @@ impl WriteFailure {
878878
}
879879
}
880880

881+
#[cfg(test)]
881882
pub(crate) fn code(&self) -> i32 {
882883
match self {
883884
Self::WriteConcernError(e) => e.code,

Diff for: src/operation/abort_transaction.rs

+5-15
Original file line numberDiff line numberDiff line change
@@ -50,28 +50,18 @@ impl OperationWithDefaults for AbortTransaction {
5050
))
5151
}
5252

53-
fn handle_response<'a>(
54-
&'a self,
53+
fn handle_response(
54+
&self,
5555
response: RawCommandResponse,
56-
_description: &'a StreamDescription,
57-
_session: Option<&'a mut ClientSession>,
58-
) -> OperationResponse<'a, Self::O> {
56+
_description: &StreamDescription,
57+
_session: Option<&mut ClientSession>,
58+
) -> OperationResponse<'static, Self::O> {
5959
handle_response_sync! {{
6060
let response: WriteConcernOnlyBody = response.body()?;
6161
response.validate()
6262
}}
6363
}
6464

65-
// handle_response!((
66-
// &self,
67-
// response: RawCommandResponse,
68-
// description: &StreamDescription,
69-
// session: Option<&mut ClientSession
70-
// ) -> Result<Self::O> {
71-
// let response: WriteConcernOnlyBody = response.body()?;
72-
// response.validate()
73-
// });
74-
7565
fn selection_criteria(&self) -> Option<&SelectionCriteria> {
7666
match &self.pinned {
7767
Some(TransactionPin::Mongos(s)) => Some(s),

0 commit comments

Comments
 (0)