Skip to content

armgit / dbx

Public Imported from GitHub
0

25 MB lightweight cross-platform database client for 100+ databases, including MySQL, PostgreSQL, SQLite, Redis, MongoDB, DuckDB, SQL Server, and Dameng. Built-in AI, MCP Server, CLI, desktop and Docker. | 轻量级跨平台数据库管理工具,支持 MySQL、PostgreSQL、SQLite、Redis、MongoDB、达梦等 100+ 数据库,提供桌面端、Docker、CLI、内置 AI 助手和 MCP。

fix(mongo): error when querying a non-existent collection

Loc Nguyen92ad833181a8
diff --git a/crates/dbx-core/src/query/mongo_ops.rs b/crates/dbx-core/src/query/mongo_ops.rs
index f13f5320fe..124ccd6fce 100644
--- a/crates/dbx-core/src/query/mongo_ops.rs
+++ b/crates/dbx-core/src/query/mongo_ops.rs
@@ -88,6 +88,25 @@ pub async fn mongo_list_collections_core(
crate::document_ops::list_collections_core(state, connection_id, database).await
}
+pub async fn ensure_collection_exists_for_query(
+ state: &AppState,
+ connection_id: &str,
+ database: &str,
+ collection: &str,
+) -> Result<(), String> {
+ match mongo_list_collections_core(state, connection_id, database).await {
+ Ok(collections) => {
+ if !collections.iter().any(|c| c.name == collection) {
+ return Err(format!("Collection '{}' does not exist in database '{}'", collection, database));
+ }
+ }
+ Err(e) => {
+ log::warn!("Could not list collections to verify existence of '{}': {}", collection, e);
+ }
+ }
+ Ok(())
+}
+
pub async fn mongo_create_database_core(state: &AppState, connection_id: &str, database: &str) -> Result<(), String> {
ensure_document_pool(state, connection_id).await?;
let pool = state.pool_handle(connection_id).await.ok_or("Not found")?;
@@ -306,7 +325,7 @@ pub async fn mongo_find_documents_core(
sort: Option<&str>,
collation: Option<&str>,
) -> Result<MongoDocumentResult, String> {
- crate::document_ops::find_documents_core(
+ let result = crate::document_ops::find_documents_core(
state,
connection_id,
database,
@@ -320,7 +339,13 @@ pub async fn mongo_find_documents_core(
None,
false,
)
- .await
+ .await?;
+
+ if result.documents.is_empty() {
+ ensure_collection_exists_for_query(state, connection_id, database, collection).await?;
+ }
+
+ Ok(result)
}
#[allow(clippy::too_many_arguments)]
@@ -338,7 +363,7 @@ async fn mongo_find_documents_without_total_core(
) -> Result<MongoDocumentResult, String> {
ensure_document_pool(state, connection_id).await?;
let pool = state.pool_handle(connection_id).await.ok_or("Not found")?;
- match &pool {
+ let result = match &pool {
PoolKind::MongoDb(client) => {
mongo_driver::find_documents_without_total(
client, database, collection, skip, limit, filter, projection, sort, collation,
@@ -364,7 +389,12 @@ async fn mongo_find_documents_without_total_core(
client.mongo_find_documents(params).await
}
_ => Err("Not a MongoDB connection".to_string()),
+ }?;
+
+ if result.documents.is_empty() {
+ ensure_collection_exists_for_query(state, connection_id, database, collection).await?;
}
+ Ok(result)
}
pub async fn mongo_find_one_core(
@@ -378,7 +408,7 @@ pub async fn mongo_find_one_core(
) -> Result<MongoDocumentResult, String> {
ensure_document_pool(state, connection_id).await?;
let pool = state.pool_handle(connection_id).await.ok_or("Not found")?;
- match &pool {
+ let result = match &pool {
PoolKind::MongoDb(client) => {
mongo_driver::find_one(client, database, collection, filter, projection, options).await
}
@@ -395,7 +425,12 @@ pub async fn mongo_find_one_core(
.await
}
_ => Err("Not a MongoDB connection".to_string()),
+ }?;
+
+ if result.documents.is_empty() {
+ ensure_collection_exists_for_query(state, connection_id, database, collection).await?;
}
+ Ok(result)
}
#[allow(clippy::too_many_arguments)]
@@ -452,7 +487,7 @@ pub async fn mongo_count_documents_core(
let accurate = mode != Some("legacy");
ensure_document_pool(state, connection_id).await?;
let pool = state.pool_handle(connection_id).await.ok_or("Not found")?;
- match &pool {
+ let total = match &pool {
PoolKind::MongoDb(client) => {
mongo_driver::count_documents(client, database, collection, filter, accurate).await
}
@@ -482,7 +517,12 @@ pub async fn mongo_count_documents_core(
}
}
_ => Err("Not a MongoDB connection".to_string()),
+ }?;
+
+ if total == 0 {
+ ensure_collection_exists_for_query(state, connection_id, database, collection).await?;
}
+ Ok(total)
}
/// Read MongoDB documents as relaxed Extended JSON for MongoDB transfer paths.
@@ -500,7 +540,7 @@ pub async fn mongo_find_documents_extended_json_core(
) -> Result<MongoDocumentResult, String> {
ensure_document_pool(state, connection_id).await?;
let pool = state.pool_handle(connection_id).await.ok_or("Not found")?;
- match &pool {
+ let result = match &pool {
PoolKind::MongoDb(client) => {
mongo_driver::find_documents_extended_json(
client, database, collection, skip, limit, filter, projection, sort, None,
@@ -529,7 +569,12 @@ pub async fn mongo_find_documents_extended_json_core(
}
}
_ => Err("Not a MongoDB connection".to_string()),
+ }?;
+
+ if result.documents.is_empty() {
+ ensure_collection_exists_for_query(state, connection_id, database, collection).await?;
}
+ Ok(result)
}
pub(crate) fn is_unknown_agent_method_error(error: &str, method: &str) -> bool {
@@ -555,7 +600,7 @@ pub async fn mongo_aggregate_documents_core(
) -> Result<MongoDocumentResult, String> {
ensure_document_pool(state, connection_id).await?;
let pool = state.pool_handle(connection_id).await.ok_or("Not found")?;
- match &pool {
+ let result = match &pool {
PoolKind::MongoDb(client) => {
mongo_driver::aggregate_documents(client, database, collection, pipeline_json, max_rows, options_json).await
}
@@ -578,7 +623,12 @@ pub async fn mongo_aggregate_documents_core(
}
}
_ => Err("Not a MongoDB connection".to_string()),
+ }?;
+
+ if result.documents.is_empty() {
+ ensure_collection_exists_for_query(state, connection_id, database, collection).await?;
}
+ Ok(result)
}
pub async fn mongo_distinct_core(
@@ -591,7 +641,7 @@ pub async fn mongo_distinct_core(
) -> Result<MongoDocumentResult, String> {
ensure_document_pool(state, connection_id).await?;
let pool = state.pool_handle(connection_id).await.ok_or("Not found")?;
- match &pool {
+ let result = match &pool {
PoolKind::MongoDb(client) => mongo_driver::distinct(client, database, collection, field, filter).await,
PoolKind::Agent(client) => {
let command = mongo_driver::distinct_command(collection, field, filter)?;
@@ -599,7 +649,12 @@ pub async fn mongo_distinct_core(
mongo_driver::distinct_response_result(response)
}
_ => Err("Not a MongoDB connection".to_string()),
+ }?;
+
+ if result.documents.is_empty() {
+ ensure_collection_exists_for_query(state, connection_id, database, collection).await?;
}
+ Ok(result)
}
/// Read every index of a collection with its full MongoDB option set.
diff --git a/crates/dbx-core/tests/live_mongodb_legacy_agent_commands.rs b/crates/dbx-core/tests/live_mongodb_legacy_agent_commands.rs
index 1bba622b45..846a3f6336 100644
--- a/crates/dbx-core/tests/live_mongodb_legacy_agent_commands.rs
+++ b/crates/dbx-core/tests/live_mongodb_legacy_agent_commands.rs
@@ -372,3 +372,26 @@ async fn dump_and_export_resolve_the_per_database_pool() {
command(&state, id, &restored, doc! { "dropDatabase": 1 }).await;
command(&state, id, &database, doc! { "dropDatabase": 1 }).await;
}
+
+#[tokio::test]
+#[ignore = "opt-in: DBX_MONGO_LEGACY_DUMP_TEST_HOST (host:port, MongoDB 3.6+ without auth) and an installed MongoDB Legacy Agent; creates a temporary database"]
+async fn missing_collection_returns_error() {
+ let endpoint = std::env::var("DBX_MONGO_LEGACY_DUMP_TEST_HOST").expect("DBX_MONGO_LEGACY_DUMP_TEST_HOST");
+ let (host, port) = endpoint.split_once(':').expect("host:port");
+ let files = tempfile::tempdir().unwrap();
+ let database = format!("dbx_legacy_missing_{}", uuid::Uuid::new_v4().simple());
+ let state =
+ AppState::new(dbx_core::persistence::test_storage::open(&files.path().join("storage.db")).await.unwrap());
+ let id = "legacy-missing-collection-test";
+ let config: ConnectionConfig = serde_json::from_value(serde_json::json!({ "id": id, "name": "Legacy missing test", "db_type": "mongodb", "host": host, "port": port.parse::<u16>().unwrap(), "username": "", "password": "", "database": database, "driver_profile": "mongodb-legacy" })).unwrap();
+ state.configs.write().await.insert(id.into(), config);
+ let key = state.get_or_create_pool(id, Some(&database)).await.unwrap();
+ assert!(matches!(state.pool_handle(&key).await, Some(PoolKind::Agent(_))), "test must run over the legacy agent");
+
+ mongo_create_database_core(&state, id, &database).await.unwrap();
+
+ let err = shell(&state, id, &database, "db.getCollection('does_not_exist').find()").await.unwrap_err();
+ assert!(err.contains("does not exist"), "Expected error about missing collection, got: {err}");
+
+ command(&state, id, &database, doc! { "dropDatabase": 1 }).await;
+}
diff --git a/crates/dbx-web/src/routes/mongo.rs b/crates/dbx-web/src/routes/mongo.rs
index 6b757769a5..1f64e64007 100644
--- a/crates/dbx-web/src/routes/mongo.rs
+++ b/crates/dbx-web/src/routes/mongo.rs
@@ -474,6 +474,15 @@ pub async fn find_documents(
),
)
.await?;
+ if result.documents.is_empty() {
+ dbx_core::mongo_ops::ensure_collection_exists_for_query(
+ &state.app,
+ &req.connection_id,
+ &database,
+ &req.collection,
+ )
+ .await?;
+ }
Ok(Json(serde_json::to_value(result).map_err(|e| AppError::from(e.to_string()))?))
}
diff --git a/src-tauri/src/commands/mongo_cmd.rs b/src-tauri/src/commands/mongo_cmd.rs
index 733d1a49e6..e87e68a991 100644
--- a/src-tauri/src/commands/mongo_cmd.rs
+++ b/src-tauri/src/commands/mongo_cmd.rs
@@ -126,11 +126,12 @@ pub async fn mongo_find_documents(
if mcp_request == Some(true) {
crate::commands::mcp_bridge::ensure_mcp_read_allowed_by_id(state.inner(), &connection_id, &database).await?;
}
- crate::commands::document_cmd::document_find_documents(
+ let app_state = state.inner().clone();
+ let result = crate::commands::document_cmd::document_find_documents(
state,
- connection_id,
- database,
- collection,
+ connection_id.clone(),
+ database.clone(),
+ collection.clone(),
skip,
limit,
filter,
@@ -141,7 +142,15 @@ pub async fn mongo_find_documents(
None,
execution_id,
)
- .await
+ .await?;
+ // The editor's `find` goes through the document-store core instead of the
+ // mongo shell command path, so surface the missing-collection error here on
+ // empty results just like the read cores do (#6032).
+ if result.documents.is_empty() {
+ dbx_core::mongo_ops::ensure_collection_exists_for_query(&app_state, &connection_id, &database, &collection)
+ .await?;
+ }
+ Ok(result)
}
#[tauri::command]