feat(mongodb): support replaceOne

This commit is contained in:
Loc Nguyen authored and GitHub committed 2026-09-16 12:18:54 +08:00
1 parent 72be4ad9eb
commit 9eafac706e
24 files changed
+496 -16

No files matched your search

+19 -3
View File
@@ -1041,6 +1041,7 @@ pub enum AgentCapability {
MongoCloneCollection,
MongoRunCommand,
MongoInsertDocuments,
MongoReplaceDocument,
MultiSession,
StructuredErrorV1,
}
@@ -1123,7 +1124,7 @@ fn parse_agent_rpc_error_header(header: &str) -> (Option<i64>, String) {
}
impl AgentCapability {
pub const ALL: [Self; 24] = [
pub const ALL: [Self; 25] = [
Self::Connect,
Self::TestConnection,
Self::Metadata,
@@ -1146,6 +1147,7 @@ impl AgentCapability {
Self::MongoCloneCollection,
Self::MongoRunCommand,
Self::MongoInsertDocuments,
Self::MongoReplaceDocument,
Self::MultiSession,
Self::StructuredErrorV1,
];
@@ -1174,6 +1176,7 @@ impl AgentCapability {
Self::MongoCloneCollection => "mongo_clone_collection",
Self::MongoRunCommand => "mongo_run_command",
Self::MongoInsertDocuments => "mongo_insert_documents",
Self::MongoReplaceDocument => "mongo_replace_document",
Self::MultiSession => "multi_session",
Self::StructuredErrorV1 => "structured_error_v1",
}
@@ -1376,13 +1379,14 @@ pub enum MongoAgentMethod {
InsertDocuments,
UpdateDocument,
UpdateDocuments,
ReplaceDocument,
DeleteDocument,
DeleteDocuments,
RunCommand,
}
impl MongoAgentMethod {
pub const ALL: [Self; 22] = [
pub const ALL: [Self; 23] = [
Self::ListDatabases,
Self::ListCollections,
Self::FindDocuments,
@@ -1402,6 +1406,7 @@ impl MongoAgentMethod {
Self::InsertDocuments,
Self::UpdateDocument,
Self::UpdateDocuments,
Self::ReplaceDocument,
Self::DeleteDocument,
Self::DeleteDocuments,
Self::RunCommand,
@@ -1428,6 +1433,7 @@ impl MongoAgentMethod {
Self::InsertDocuments => "insert_documents",
Self::UpdateDocument => "update_document",
Self::UpdateDocuments => "update_documents",
Self::ReplaceDocument => "replace_document",
Self::DeleteDocument => "delete_document",
Self::DeleteDocuments => "delete_documents",
Self::RunCommand => "run_command",
@@ -2803,6 +2809,13 @@ impl AgentDriverClient {
self.call_mongo_method(MongoAgentMethod::UpdateDocuments, params).await
}
pub async fn mongo_replace_document<T: DeserializeOwned + Send + 'static>(
&mut self,
params: Value,
) -> Result<T, String> {
self.call_mongo_method(MongoAgentMethod::ReplaceDocument, params).await
}
pub async fn mongo_delete_document<T: DeserializeOwned + Send + 'static>(
&mut self,
params: Value,
@@ -2958,6 +2971,7 @@ pub fn agent_supports_capability(handshake: Option<&AgentHandshake>, capability:
| AgentCapability::MongoCloneCollection
| AgentCapability::MongoRunCommand
| AgentCapability::MongoInsertDocuments
| AgentCapability::MongoReplaceDocument
) {
return handshake.map(|value| value.supports(capability)).unwrap_or(false);
}
@@ -4991,9 +5005,10 @@ for line in sys.stdin:
assert_eq!(AgentCapability::MongoCloneCollection.as_str(), "mongo_clone_collection");
assert_eq!(AgentCapability::MongoRunCommand.as_str(), "mongo_run_command");
assert_eq!(AgentCapability::MongoInsertDocuments.as_str(), "mongo_insert_documents");
assert_eq!(AgentCapability::MongoReplaceDocument.as_str(), "mongo_replace_document");
assert_eq!(AgentCapability::MultiSession.as_str(), "multi_session");
assert_eq!(AgentCapability::StructuredErrorV1.as_str(), "structured_error_v1");
assert_eq!(AgentCapability::ALL.len(), 24);
assert_eq!(AgentCapability::ALL.len(), 25);
}
#[test]
@@ -5055,6 +5070,7 @@ for line in sys.stdin:
assert_eq!(MongoAgentMethod::InsertDocuments.as_str(), "insert_documents");
assert_eq!(MongoAgentMethod::UpdateDocument.as_str(), "update_document");
assert_eq!(MongoAgentMethod::UpdateDocuments.as_str(), "update_documents");
assert_eq!(MongoAgentMethod::ReplaceDocument.as_str(), "replace_document");
assert_eq!(MongoAgentMethod::DeleteDocument.as_str(), "delete_document");
assert_eq!(MongoAgentMethod::DeleteDocuments.as_str(), "delete_documents");
}
+44
View File
@@ -2120,6 +2120,50 @@ pub async fn update_documents(
Ok(result.modified_count)
}
/// replaceOne(filter, replacement[, { upsert }]): the whole document is swapped, so
/// unlike update there are no array filters to apply.
pub async fn replace_document(
client: &Client,
database: &str,
collection: &str,
filter_json: &str,
replacement_json: &str,
options_json: Option<&str>,
) -> Result<u64, String> {
let filter_value: serde_json::Value =
serde_json::from_str(filter_json).map_err(|e| format!("Invalid filter JSON: {e}"))?;
let replacement_value: serde_json::Value =
serde_json::from_str(replacement_json).map_err(|e| format!("Invalid replacement JSON: {e}"))?;
let filter = json_filter_to_document(&filter_value).map_err(|e| format!("Invalid filter: {e}"))?;
let replacement = json_object_to_document(&replacement_value).map_err(|e| format!("Invalid replacement: {e}"))?;
if let Some(operator) = replacement.keys().find(|key| key.starts_with('$')) {
return Err(format!("Replacement document must not contain update operators such as {operator}"));
}
let upsert = parse_replace_options(options_json)?;
let col = client.database(database).collection::<Document>(collection);
let mut action = col.replace_one(filter, replacement);
if let Some(upsert) = upsert {
action = action.upsert(upsert);
}
let result = action.await.map_err(|e| e.to_string())?;
Ok(result.modified_count)
}
#[derive(Default, Deserialize)]
#[serde(rename_all = "camelCase", deny_unknown_fields)]
struct MongoReplaceOptions {
upsert: Option<bool>,
}
fn parse_replace_options(options_json: Option<&str>) -> Result<Option<bool>, String> {
let Some(raw) = options_json.filter(|value| !value.trim().is_empty()) else {
return Ok(None);
};
let options: MongoReplaceOptions =
serde_json::from_str(raw).map_err(|e| format!("Invalid replace options: {e}"))?;
Ok(options.upsert)
}
#[derive(Default, Deserialize)]
#[serde(rename_all = "camelCase")]
struct MongoUpdateOptions {