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。
TypeScript aicliclickhousedatabasedatabase-clientdatabase-managementdockerguimcpmongodbmysqlpostgresqlredisrustsql-serversqlitetaurivue
fix(mongo): preserve auth database for commands
t8y26c83b10b42f5
diff --git a/apps/desktop/src/lib/mongoShellCommand.ts b/apps/desktop/src/lib/mongoShellCommand.tsindex 3effba6e27..c722adb24d 100644--- a/apps/desktop/src/lib/mongoShellCommand.ts+++ b/apps/desktop/src/lib/mongoShellCommand.ts@@ -8,6 +8,11 @@ export interface MongoFindCommand {sort?: string;}+export interface MongoCountDocumentsCommand {+ collection: string;+ filter: string;+}+const DEFAULT_LIMIT = 100;export function parseMongoFindCommand(input: string): MongoFindCommand | null {@@ -47,6 +52,26 @@ export function parseMongoFindCommand(input: string): MongoFindCommand | null {};}+export function parseMongoCountDocumentsCommand(input: string): MongoCountDocumentsCommand | null {+ const source = input.trim().replace(/;$/, "").trim();+ const target = parseCollectionMethodTarget(source, "countDocuments");+ if (!target) return null;++ const openIndex = source.indexOf("(", target.methodCallIndex);+ const closeIndex = findMatchingParen(source, openIndex);+ if (closeIndex < 0 || source.slice(closeIndex + 1).trim()) return null;++ const args = splitTopLevel(source.slice(openIndex + 1, closeIndex));+ if (args.length > 1 && args.slice(1).some((arg) => arg.trim())) return null;+ const filter = normalizeJsonArgument(args[0] || "{}");+ if (!filter) return null;++ return {+ collection: target.collection,+ filter,+ };+}+export function mongoDocumentsToQueryResult(documents: unknown[], executionTimeMs: number, total: number): QueryResult {const columns: string[] = [];@@ -74,17 +99,44 @@ export function mongoDocumentsToQueryResult(documents: unknown[], executionTimeM};}+export function mongoCountToQueryResult(total: number, executionTimeMs: number): QueryResult {+ return {+ columns: ["count"],+ rows: [[total]],+ affected_rows: total,+ execution_time_ms: Math.max(0, Math.round(executionTimeMs)),+ };+}+function parseFindTarget(source: string): { collection: string; findCallIndex: number } | null {- const direct = /^db\.([A-Za-z_$][\w$]*)\.find\s*\(/.exec(source);+ const direct = parseCollectionMethodTarget(source, "find");+ if (direct) {+ return { collection: direct.collection, findCallIndex: direct.methodCallIndex };+ }++ return null;+}++function parseCollectionMethodTarget(+ source: string,+ method: string,+): { collection: string; methodCallIndex: number } | null {+ const escapedMethod = escapeRegExp(method);+ const direct = new RegExp(`^db\\.([A-Za-z_$][\\w$]*)\\.${escapedMethod}\\s*\\(`).exec(source);if (direct) {- return { collection: direct[1], findCallIndex: source.indexOf(".find", direct[0].length - ".find(".length) };+ return {+ collection: direct[1],+ methodCallIndex: source.indexOf(`.${method}`, direct[0].length - `.${method}(`.length),+ };}- const getCollection = /^db\.getCollection\s*\(\s*(["'])(.*?)\1\s*\)\.find\s*\(/.exec(source);+ const getCollection = new RegExp(+ `^db\\.getCollection\\s*\\(\\s*(["'])(.*?)\\1\\s*\\)\\.${escapedMethod}\\s*\\(`,+ ).exec(source);if (getCollection) {return {collection: getCollection[2],- findCallIndex: source.indexOf(".find", getCollection[0].length - ".find(".length),+ methodCallIndex: source.indexOf(`.${method}`, getCollection[0].length - `.${method}(`.length),};}@@ -186,6 +238,10 @@ function findMatchingParen(source: string, openIndex: number): number {return -1;}+function escapeRegExp(value: string): string {+ return value.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");+}+function isRecord(value: unknown): value is Record<string, unknown> {return !!value && typeof value === "object" && !Array.isArray(value);}diff --git a/apps/desktop/src/stores/queryStore.ts b/apps/desktop/src/stores/queryStore.tsindex 142f55f887..04e902ca7c 100644--- a/apps/desktop/src/stores/queryStore.ts+++ b/apps/desktop/src/stores/queryStore.ts@@ -13,7 +13,12 @@ import {sourceColumnsForResult,} from "@/lib/sqlAnalysis";import { restoreOpenTabsState, serializeOpenTabs } from "@/lib/openTabsPersistence";-import { mongoDocumentsToQueryResult, parseMongoFindCommand } from "@/lib/mongoShellCommand";+import {+ mongoCountToQueryResult,+ mongoDocumentsToQueryResult,+ parseMongoCountDocumentsCommand,+ parseMongoFindCommand,+} from "@/lib/mongoShellCommand";import { buildQueryPaginationExecutionPlan } from "@/lib/queryResultPagination";import { AGENT_DRIVER_TYPES } from "@/lib/databaseCapabilities";import { editablePrimaryKeys } from "@/lib/tableEditing";@@ -532,6 +537,36 @@ export const useQueryStore = defineStore("query", () => {}return;}+ const mongoCount = conn?.db_type === "mongodb" ? parseMongoCountDocumentsCommand(sql) : null;+ if (mongoCount) {+ console.info("[DBX][executeTabSql:mongo-count:start]", { traceId, collection: mongoCount.collection });+ const result = await api.mongoFindDocuments(+ tab.connectionId,+ tab.database,+ mongoCount.collection,+ 0,+ 1,+ mongoCount.filter,+ );+ console.info("[DBX][executeTabSql:mongo-count:done]", {+ traceId,+ total: result.total,+ elapsed: elapsed(),+ });+ const current = tabs.value.find((t) => t.id === id);+ if (current?.executionId === executionId) {+ current.results = undefined;+ current.activeResultIndex = undefined;+ current.result = mongoCountToQueryResult(result.total, performance.now() - startedAt);+ current.queryAnalysis = undefined;+ current.querySourceColumns = undefined;+ current.queryEditabilityReason = undefined;+ current.tableMeta = undefined;+ current.resultBaseSql = options?.resultBaseSql ?? sql;+ current.resultSortedSql = options?.resultSortedSql;+ }+ return;+ }console.info("[DBX][executeTabSql:execute-multi:start]", { traceId, elapsed: elapsed() });const executionOptions =diff --git a/crates/dbx-core/assets/database-drivers.manifest.json b/crates/dbx-core/assets/database-drivers.manifest.jsonindex 1a6b548a36..3cdf61b4b4 100644--- a/crates/dbx-core/assets/database-drivers.manifest.json+++ b/crates/dbx-core/assets/database-drivers.manifest.json@@ -75,7 +75,7 @@"runtimeMode": "agent","mcpMode": "bridge","agentKey": "mongodb",- "singleConnectionPool": false,+ "singleConnectionPool": true,"metadataConnectionScoped": false,"skipTcpProbe": true,"defaultPort": 27017diff --git a/crates/dbx-core/src/connection.rs b/crates/dbx-core/src/connection.rsindex 343a9ba51d..651330d385 100644--- a/crates/dbx-core/src/connection.rs+++ b/crates/dbx-core/src/connection.rs@@ -73,7 +73,10 @@ pub fn metadata_connection_config(config: &ConnectionConfig) -> ConnectionConfigpub fn database_connection_config(config: &ConnectionConfig, database: Option<&str>) -> ConnectionConfig {let mut db_config = if database.is_some() { config.clone() } else { metadata_connection_config(config) };if let Some(db) = database {- if !matches!(db_config.db_type, DatabaseType::Oracle | DatabaseType::Dameng | DatabaseType::OceanbaseOracle) {+ if !matches!(+ db_config.db_type,+ DatabaseType::Oracle | DatabaseType::Dameng | DatabaseType::MongoDb | DatabaseType::OceanbaseOracle+ ) {db_config.database = Some(db.to_string());}}@@ -915,6 +918,16 @@ mod tests {assert_eq!(scoped.database.as_deref(), Some("analytics"));}+ #[test]+ fn mongodb_database_connection_keeps_saved_database_for_auth() {+ let mut config = mysql_config(Some("admin"));+ config.db_type = DatabaseType::MongoDb;++ let scoped = database_connection_config(&config, Some("shop"));++ assert_eq!(scoped.database.as_deref(), Some("admin"));+ }+#[test]fn oracle_database_connection_ignores_requested_database() {let mut config = mysql_config(Some("ORCL"));diff --git a/crates/dbx-core/src/database_capabilities.rs b/crates/dbx-core/src/database_capabilities.rsindex f23864e810..fe79f6e8d2 100644--- a/crates/dbx-core/src/database_capabilities.rs+++ b/crates/dbx-core/src/database_capabilities.rs@@ -49,6 +49,7 @@ pub fn is_single_connection_pool(db_type: &DatabaseType) -> bool {db_type,DatabaseType::Sqlite| DatabaseType::DuckDb+ | DatabaseType::MongoDb| DatabaseType::Oracle| DatabaseType::Dameng| DatabaseType::Kingbasediff --git a/crates/dbx-core/tests/database_capabilities.rs b/crates/dbx-core/tests/database_capabilities.rsindex e5ac4a7c14..1a698d925c 100644--- a/crates/dbx-core/tests/database_capabilities.rs+++ b/crates/dbx-core/tests/database_capabilities.rs@@ -92,6 +92,7 @@ fn classifies_agent_database_types() {fn identifies_single_connection_pool_types() {assert!(is_single_connection_pool(&DatabaseType::Sqlite));assert!(is_single_connection_pool(&DatabaseType::DuckDb));+ assert!(is_single_connection_pool(&DatabaseType::MongoDb));assert!(is_single_connection_pool(&DatabaseType::Oracle));assert!(is_single_connection_pool(&DatabaseType::Dameng));assert!(is_single_connection_pool(&DatabaseType::Access));diff --git a/packages/app-tests/mongoShellCommand.test.ts b/packages/app-tests/mongoShellCommand.test.tsindex e60949dd2b..673c4e3ada 100644--- a/packages/app-tests/mongoShellCommand.test.ts+++ b/packages/app-tests/mongoShellCommand.test.ts@@ -1,6 +1,11 @@import { strict as assert } from "node:assert";import test from "node:test";-import { mongoDocumentsToQueryResult, parseMongoFindCommand } from "../../apps/desktop/src/lib/mongoShellCommand.ts";+import {+ mongoCountToQueryResult,+ mongoDocumentsToQueryResult,+ parseMongoCountDocumentsCommand,+ parseMongoFindCommand,+} from "../../apps/desktop/src/lib/mongoShellCommand.ts";test("parseMongoFindCommand parses db collection find with an empty JSON filter", () => {assert.deepEqual(parseMongoFindCommand("db.users.find({})"), {@@ -31,6 +36,22 @@ test("parseMongoFindCommand rejects unsupported mongo shell commands", () => {assert.equal(parseMongoFindCommand("db.users.insertOne({})"), null);});+test("parseMongoCountDocumentsCommand parses db collection countDocuments", () => {+ assert.deepEqual(parseMongoCountDocumentsCommand("db.products.countDocuments({})"), {+ collection: "products",+ filter: "{}",+ });+});++test("mongoCountToQueryResult returns a single count row", () => {+ assert.deepEqual(mongoCountToQueryResult(42, 5), {+ columns: ["count"],+ rows: [[42]],+ affected_rows: 42,+ execution_time_ms: 5,+ });+});+test("mongoDocumentsToQueryResult turns mongo documents into grid rows", () => {const result = mongoDocumentsToQueryResult([