fix(mongodb): support find explain commands

Closes #5619
This commit is contained in:
t8y2 committed 2026-08-07 18:51:04 +08:00
1 parent bac8f4166f
commit 996ce42e80
11 files changed
+544 -2

No files matched your search

+12 -1
View File
@@ -1273,6 +1273,7 @@ pub enum MongoAgentMethod {
ListCollections,
FindDocuments,
FindOne,
ExplainFind,
FindDocumentsExtendedJson,
CountDocuments,
ServerVersion,
@@ -1288,11 +1289,12 @@ pub enum MongoAgentMethod {
}
impl MongoAgentMethod {
pub const ALL: [Self; 16] = [
pub const ALL: [Self; 17] = [
Self::ListDatabases,
Self::ListCollections,
Self::FindDocuments,
Self::FindOne,
Self::ExplainFind,
Self::FindDocumentsExtendedJson,
Self::CountDocuments,
Self::ServerVersion,
@@ -1313,6 +1315,7 @@ impl MongoAgentMethod {
Self::ListCollections => "list_collections",
Self::FindDocuments => "find_documents",
Self::FindOne => "find_one",
Self::ExplainFind => "explain_find",
Self::FindDocumentsExtendedJson => "find_documents_extended_json",
Self::CountDocuments => "count_documents",
Self::ServerVersion => "server_version",
@@ -2471,6 +2474,13 @@ impl AgentDriverClient {
self.call_mongo_method(MongoAgentMethod::FindOne, params).await
}
pub async fn mongo_explain_find<T: DeserializeOwned + Send + 'static>(
&mut self,
params: Value,
) -> Result<T, String> {
self.call_mongo_method(MongoAgentMethod::ExplainFind, params).await
}
/// Calls the Mongo agent read method that returns MongoDB relaxed Extended JSON.
pub async fn mongo_find_documents_extended_json<T: DeserializeOwned + Send + 'static>(
&mut self,
@@ -4322,6 +4332,7 @@ for line in sys.stdin:
assert_eq!(MongoAgentMethod::ListCollections.as_str(), "list_collections");
assert_eq!(MongoAgentMethod::FindDocuments.as_str(), "find_documents");
assert_eq!(MongoAgentMethod::FindOne.as_str(), "find_one");
assert_eq!(MongoAgentMethod::ExplainFind.as_str(), "explain_find");
assert_eq!(MongoAgentMethod::FindDocumentsExtendedJson.as_str(), "find_documents_extended_json");
assert_eq!(MongoAgentMethod::CountDocuments.as_str(), "count_documents");
assert_eq!(MongoAgentMethod::ServerVersion.as_str(), "server_version");
+95
View File
@@ -732,6 +732,70 @@ pub async fn find_documents_without_total(
.await
}
#[allow(clippy::too_many_arguments)]
pub async fn explain_find(
client: &Client,
database: &str,
collection: &str,
skip: u64,
limit: i64,
filter: Option<&str>,
projection: Option<&str>,
sort: Option<&str>,
collation: Option<&str>,
verbosity: &str,
) -> Result<serde_json::Value, String> {
let command = build_find_explain_command(collection, skip, limit, filter, projection, sort, collation, verbosity)?;
let result = client.database(database).run_command(command).await.map_err(|error| error.to_string())?;
Ok(bson_to_json(&Bson::Document(result)))
}
#[allow(clippy::too_many_arguments)]
fn build_find_explain_command(
collection: &str,
skip: u64,
limit: i64,
filter: Option<&str>,
projection: Option<&str>,
sort: Option<&str>,
collation: Option<&str>,
verbosity: &str,
) -> Result<Document, String> {
let mut find = doc! {
"find": collection,
"filter": parse_optional_filter_document(filter)?.unwrap_or_default(),
};
if let Some(projection) = parse_optional_json_document(projection, "projection")? {
find.insert("projection", projection);
}
if let Some(sort) = parse_optional_json_document(sort, "sort")? {
find.insert("sort", sort);
}
if let Some(collation) = parse_find_collation(collation)? {
find.insert(
"collation",
mongodb::bson::to_document(&collation).map_err(|error| format!("Invalid collation: {error}"))?,
);
}
if skip > 0 {
find.insert("skip", i64::try_from(skip).map_err(|_| "MongoDB skip exceeds the supported range")?);
}
if limit > 0 {
find.insert("limit", limit);
}
Ok(doc! {
"explain": find,
"verbosity": validate_find_explain_verbosity(verbosity)?,
})
}
fn validate_find_explain_verbosity(verbosity: &str) -> Result<&str, String> {
match verbosity {
"queryPlanner" | "executionStats" | "allPlansExecution" => Ok(verbosity),
_ => Err("MongoDB explain verbosity must be queryPlanner, executionStats, or allPlansExecution.".to_string()),
}
}
#[allow(clippy::too_many_arguments)]
async fn find_documents_with_total(
client: &Client,
@@ -2240,6 +2304,37 @@ mod tests {
.contains("Invalid collation"));
}
#[test]
fn builds_find_explain_command_with_all_find_options() {
let command = build_find_explain_command(
"im_msg",
2,
5,
Some(r#"{"active":true}"#),
Some(r#"{"email":1}"#),
Some(r#"{"email":1}"#),
Some(r#"{"locale":"en","strength":1}"#),
"executionStats",
)
.unwrap();
let find = command.get_document("explain").unwrap();
assert_eq!(find.get_str("find").unwrap(), "im_msg");
assert_eq!(find.get_document("filter").unwrap().get_bool("active").unwrap(), true);
assert_eq!(find.get_document("projection").unwrap().get_i64("email").unwrap(), 1);
assert_eq!(find.get_document("sort").unwrap().get_i64("email").unwrap(), 1);
assert_eq!(find.get_i64("skip").unwrap(), 2);
assert_eq!(find.get_i64("limit").unwrap(), 5);
assert_eq!(find.get_document("collation").unwrap().get_str("locale").unwrap(), "en");
assert_eq!(command.get_str("verbosity").unwrap(), "executionStats");
}
#[test]
fn rejects_invalid_find_explain_verbosity() {
let error = build_find_explain_command("items", 0, 0, None, None, None, None, "invalid").unwrap_err();
assert!(error.contains("queryPlanner, executionStats, or allPlansExecution"));
}
#[test]
fn mongo_find_count_failure_returns_loaded_lower_bound() {
let error = "invalid type: floating point `2053278871.0`, expected u64".to_string();