fix(mongodb): support getIndexes shell command
This commit is contained in:
@@ -18,6 +18,10 @@ export interface MongoAggregateCommand {
|
||||
pipeline: string;
|
||||
}
|
||||
|
||||
export interface MongoGetIndexesCommand {
|
||||
collection: string;
|
||||
}
|
||||
|
||||
export type MongoWriteCommand =
|
||||
| { kind: "insert"; collection: string; docsJson: string }
|
||||
| { kind: "update"; collection: string; filter: string; update: string; many: boolean }
|
||||
@@ -112,6 +116,23 @@ export function parseMongoAggregateCommand(input: string): MongoAggregateCommand
|
||||
};
|
||||
}
|
||||
|
||||
export function parseMongoGetIndexesCommand(input: string): MongoGetIndexesCommand | null {
|
||||
const source = input.trim().replace(/;$/, "").trim();
|
||||
const target = parseCollectionMethodTarget(source, "getIndexes");
|
||||
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.some((arg) => arg.trim())) return null;
|
||||
|
||||
return {
|
||||
collection: target.collection,
|
||||
};
|
||||
}
|
||||
|
||||
export function parseMongoWriteCommand(input: string): MongoWriteCommand | null {
|
||||
const source = input.trim().replace(/;$/, "").trim();
|
||||
const insertOne = parseCollectionMethodTarget(source, "insertOne");
|
||||
@@ -238,6 +259,34 @@ export function mongoWriteToQueryResult(affectedRows: number, executionTimeMs: n
|
||||
};
|
||||
}
|
||||
|
||||
export function mongoIndexesToQueryResult(
|
||||
indexes: {
|
||||
name: string;
|
||||
columns: string[];
|
||||
is_unique: boolean;
|
||||
is_primary: boolean;
|
||||
filter?: string | null;
|
||||
index_type?: string | null;
|
||||
included_columns?: string[] | null;
|
||||
comment?: string | null;
|
||||
}[],
|
||||
executionTimeMs: number,
|
||||
): QueryResult {
|
||||
return {
|
||||
columns: ["name", "columns", "unique", "primary", "type", "filter"],
|
||||
rows: indexes.map((index) => [
|
||||
index.name,
|
||||
index.columns.join(", "),
|
||||
index.is_unique,
|
||||
index.is_primary,
|
||||
index.index_type ?? null,
|
||||
index.filter ?? null,
|
||||
]),
|
||||
affected_rows: indexes.length,
|
||||
execution_time_ms: Math.max(0, Math.round(executionTimeMs)),
|
||||
};
|
||||
}
|
||||
|
||||
function parseFindTarget(source: string): { collection: string; findCallIndex: number } | null {
|
||||
const direct = parseCollectionMethodTarget(source, "find");
|
||||
if (direct) {
|
||||
|
||||
@@ -18,10 +18,12 @@ import {
|
||||
evaluateMongoAggregateSafety,
|
||||
mongoCountToQueryResult,
|
||||
mongoDocumentsToQueryResult,
|
||||
mongoIndexesToQueryResult,
|
||||
mongoWriteToQueryResult,
|
||||
parseMongoAggregateCommand,
|
||||
parseMongoCountDocumentsCommand,
|
||||
parseMongoFindCommand,
|
||||
parseMongoGetIndexesCommand,
|
||||
parseMongoWriteCommand,
|
||||
type MongoAggregateSafetyOptions,
|
||||
} from "@/lib/mongoShellCommand";
|
||||
@@ -1091,6 +1093,32 @@ export const useQueryStore = defineStore("query", () => {
|
||||
return;
|
||||
}
|
||||
|
||||
const mongoGetIndexes = conn?.db_type === "mongodb" ? parseMongoGetIndexesCommand(sql) : null;
|
||||
if (mongoGetIndexes) {
|
||||
await connStore.ensureConnected(tab.connectionId);
|
||||
console.info("[DBX][executeTabSql:mongo-indexes:start]", { traceId, collection: mongoGetIndexes.collection });
|
||||
const indexes = await api.listIndexes(tab.connectionId, tab.database, "", mongoGetIndexes.collection);
|
||||
console.info("[DBX][executeTabSql:mongo-indexes:done]", {
|
||||
traceId,
|
||||
indexCount: indexes.length,
|
||||
elapsed: elapsed(),
|
||||
});
|
||||
const current = tabs.value.find((t) => t.id === id);
|
||||
if (current?.executionId === executionId) {
|
||||
current.results = undefined;
|
||||
current.activeResultIndex = undefined;
|
||||
current.result = markQueryResultRowsRaw(mongoIndexesToQueryResult(indexes, performance.now() - startedAt));
|
||||
touchResult(current);
|
||||
current.queryAnalysis = undefined;
|
||||
current.querySourceColumns = undefined;
|
||||
current.queryEditabilityReason = undefined;
|
||||
current.tableMeta = undefined;
|
||||
current.resultBaseSql = options?.resultBaseSql ?? sql;
|
||||
current.resultSortedSql = options?.resultSortedSql;
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
const mongoWrite = conn?.db_type === "mongodb" ? parseMongoWriteCommand(sql) : null;
|
||||
if (mongoWrite) {
|
||||
await connStore.ensureConnected(tab.connectionId);
|
||||
|
||||
@@ -6,6 +6,8 @@ use mongodb::{
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
use super::with_connection_timeout;
|
||||
use crate::types::IndexInfo;
|
||||
use futures::TryStreamExt;
|
||||
use std::time::Duration;
|
||||
|
||||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||
@@ -42,6 +44,39 @@ pub async fn list_collections(client: &Client, database: &str) -> Result<Vec<Str
|
||||
client.database(database).list_collection_names().await.map_err(|e| e.to_string())
|
||||
}
|
||||
|
||||
pub async fn list_indexes(client: &Client, database: &str, collection: &str) -> Result<Vec<IndexInfo>, String> {
|
||||
let col = client.database(database).collection::<Document>(collection);
|
||||
let mut cursor = col.list_indexes().await.map_err(|e| e.to_string())?;
|
||||
let mut indexes = Vec::new();
|
||||
while let Some(model) = cursor.try_next().await.map_err(|e| e.to_string())? {
|
||||
let name = model.options.as_ref().and_then(|options| options.name.clone()).unwrap_or_else(|| {
|
||||
model.keys.iter().map(|(field, value)| format!("{field}_{value}")).collect::<Vec<_>>().join("_")
|
||||
});
|
||||
let columns = model.keys.keys().cloned().collect::<Vec<_>>();
|
||||
let index_type = if model.keys.is_empty() {
|
||||
None
|
||||
} else {
|
||||
Some(model.keys.iter().map(|(field, value)| format!("{field}: {value}")).collect::<Vec<_>>().join(", "))
|
||||
};
|
||||
let filter = model
|
||||
.options
|
||||
.as_ref()
|
||||
.and_then(|options| options.partial_filter_expression.as_ref())
|
||||
.map(|filter| bson_to_json(&Bson::Document(filter.clone())).to_string());
|
||||
indexes.push(IndexInfo {
|
||||
is_unique: model.options.as_ref().and_then(|options| options.unique).unwrap_or(false),
|
||||
is_primary: name == "_id_",
|
||||
name,
|
||||
columns,
|
||||
filter,
|
||||
index_type,
|
||||
included_columns: None,
|
||||
comment: None,
|
||||
});
|
||||
}
|
||||
Ok(indexes)
|
||||
}
|
||||
|
||||
pub async fn find_documents(
|
||||
client: &Client,
|
||||
database: &str,
|
||||
|
||||
@@ -1264,6 +1264,7 @@ pub async fn list_indexes_core(
|
||||
PoolKind::Postgres(p) => db::postgres::list_indexes(p, schema, table).await,
|
||||
PoolKind::Sqlite(p) => db::sqlite::list_indexes(p, schema, table).await,
|
||||
PoolKind::Rqlite(client) => db::rqlite_driver::list_indexes(client, schema, table).await,
|
||||
PoolKind::MongoDb(client) => db::mongo_driver::list_indexes(client, database, table).await,
|
||||
_ => Ok(vec![]),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -5,9 +5,11 @@ import {
|
||||
mongoAggregateWriteStage,
|
||||
mongoCountToQueryResult,
|
||||
mongoDocumentsToQueryResult,
|
||||
mongoIndexesToQueryResult,
|
||||
parseMongoAggregateCommand,
|
||||
parseMongoCountDocumentsCommand,
|
||||
parseMongoFindCommand,
|
||||
parseMongoGetIndexesCommand,
|
||||
parseMongoWriteCommand,
|
||||
} from "../../apps/desktop/src/lib/mongoShellCommand.ts";
|
||||
|
||||
@@ -117,6 +119,16 @@ test("parseMongoAggregateCommand normalises ObjectId arguments with either quote
|
||||
}
|
||||
});
|
||||
|
||||
test("parseMongoGetIndexesCommand parses collection index commands", () => {
|
||||
assert.deepEqual(parseMongoGetIndexesCommand("db.web_log.getIndexes();"), {
|
||||
collection: "web_log",
|
||||
});
|
||||
assert.deepEqual(parseMongoGetIndexesCommand('db.getCollection("audit.logs").getIndexes()'), {
|
||||
collection: "audit.logs",
|
||||
});
|
||||
assert.equal(parseMongoGetIndexesCommand("db.web_log.getIndexes({})"), null);
|
||||
});
|
||||
|
||||
test("evaluateMongoAggregateSafety blocks write stages unless MCP write flags allow them", () => {
|
||||
const out = parseMongoAggregateCommand('db.products.aggregate([{"$out":"products_copy"}])');
|
||||
assert.ok(out);
|
||||
@@ -133,6 +145,30 @@ test("evaluateMongoAggregateSafety blocks write stages unless MCP write flags al
|
||||
assert.equal(evaluateMongoAggregateSafety(merge, { allowWrites: true, allowDangerous: true }).allowed, true);
|
||||
});
|
||||
|
||||
test("mongoIndexesToQueryResult formats index metadata", () => {
|
||||
assert.deepEqual(
|
||||
mongoIndexesToQueryResult(
|
||||
[
|
||||
{
|
||||
name: "_id_",
|
||||
columns: ["_id"],
|
||||
is_unique: false,
|
||||
is_primary: true,
|
||||
index_type: "_id: 1",
|
||||
filter: null,
|
||||
},
|
||||
],
|
||||
7,
|
||||
),
|
||||
{
|
||||
columns: ["name", "columns", "unique", "primary", "type", "filter"],
|
||||
rows: [["_id_", "_id", false, true, "_id: 1", null]],
|
||||
affected_rows: 1,
|
||||
execution_time_ms: 7,
|
||||
},
|
||||
);
|
||||
});
|
||||
|
||||
test("mongoCountToQueryResult returns a single count row", () => {
|
||||
assert.deepEqual(mongoCountToQueryResult(42, 5), {
|
||||
columns: ["count"],
|
||||
|
||||
@@ -513,6 +513,14 @@ export async function executeQuery(config: ConnectionConfig, sql: string, option
|
||||
);
|
||||
return mongoDocumentsToQueryResult(result.documents.slice(0, resolveMaxRows(options)), result.total);
|
||||
}
|
||||
const getIndexes = parseMongoGetIndexesCommand(sql);
|
||||
if (getIndexes) {
|
||||
const result = await withTimeout(
|
||||
mongoAggregateDocuments(config, getIndexes.collection, '[{"$indexStats":{}}]', resolveMaxRows(options)),
|
||||
resolveTimeoutMs(options),
|
||||
);
|
||||
return mongoDocumentsToQueryResult(result.documents.slice(0, resolveMaxRows(options)), result.total);
|
||||
}
|
||||
const write = parseMongoWriteCommand(sql);
|
||||
if (write) {
|
||||
const safety = evaluateMongoWriteSafety(write, sqlSafetyFromEnv());
|
||||
@@ -521,7 +529,7 @@ export async function executeQuery(config: ConnectionConfig, sql: string, option
|
||||
return { columns: [], rows: [], row_count: affected };
|
||||
}
|
||||
throw new Error(
|
||||
"Use MongoDB shell-style commands, for example: db.projects.find({}).limit(100), db.projects.countDocuments({}), db.projects.insertOne({...}), db.projects.updateOne({...}, {$set: {...}}), or db.projects.deleteOne({...})",
|
||||
"Use MongoDB shell-style commands, for example: db.projects.find({}).limit(100), db.projects.countDocuments({}), db.projects.getIndexes(), db.projects.insertOne({...}), db.projects.updateOne({...}, {$set: {...}}), or db.projects.deleteOne({...})",
|
||||
);
|
||||
}
|
||||
if (isDirectQueryType(config.db_type)) {
|
||||
@@ -758,6 +766,10 @@ interface MongoAggregateCommand {
|
||||
pipeline: string;
|
||||
}
|
||||
|
||||
interface MongoGetIndexesCommand {
|
||||
collection: string;
|
||||
}
|
||||
|
||||
export type MongoWriteCommand =
|
||||
| { kind: "insert"; collection: string; docsJson: string }
|
||||
| { kind: "update"; collection: string; filter: string; update: string; many: boolean }
|
||||
@@ -812,6 +824,15 @@ export function parseMongoAggregateCommand(input: string): MongoAggregateCommand
|
||||
return Array.isArray(JSON.parse(pipeline)) ? { collection: target.collection, pipeline } : null;
|
||||
}
|
||||
|
||||
export function parseMongoGetIndexesCommand(input: string): MongoGetIndexesCommand | null {
|
||||
const source = input.trim().replace(/;$/, "").trim();
|
||||
const target = parseCollectionMethodTarget(source, "getIndexes");
|
||||
if (!target) return null;
|
||||
const args = parseMethodArgs(source, target.methodCallIndex);
|
||||
if (!args || args.some((arg) => arg.trim())) return null;
|
||||
return { collection: target.collection };
|
||||
}
|
||||
|
||||
export function mongoAggregateWriteStage(pipelineJson: string): "$out" | "$merge" | null {
|
||||
try {
|
||||
const pipeline = JSON.parse(pipelineJson);
|
||||
|
||||
@@ -8,6 +8,7 @@ import {
|
||||
parseMongoAggregateCommand,
|
||||
parseMongoCountDocumentsCommand,
|
||||
parseMongoFindCommand,
|
||||
parseMongoGetIndexesCommand,
|
||||
parseMongoWriteCommand,
|
||||
type MongoWriteCommand,
|
||||
} from "./database.js";
|
||||
@@ -188,6 +189,21 @@ export async function executeQuery(config: ConnectionConfig, sql: string, option
|
||||
const result = (await res.json()) as { documents: unknown[]; total: number };
|
||||
return mongoDocumentsToQueryResult(result.documents.slice(0, options?.maxRows ?? result.documents.length), result.total);
|
||||
}
|
||||
const getIndexes = parseMongoGetIndexesCommand(sql);
|
||||
if (getIndexes) {
|
||||
const res = await apiFetch("/api/mongo/aggregate-documents", {
|
||||
method: "POST",
|
||||
body: JSON.stringify({
|
||||
connectionId: config.id,
|
||||
database: config.database || "",
|
||||
collection: getIndexes.collection,
|
||||
pipelineJson: '[{"$indexStats":{}}]',
|
||||
maxRows: options?.maxRows ?? 100,
|
||||
}),
|
||||
});
|
||||
const result = (await res.json()) as { documents: unknown[]; total: number };
|
||||
return mongoDocumentsToQueryResult(result.documents.slice(0, options?.maxRows ?? result.documents.length), result.total);
|
||||
}
|
||||
const write = parseMongoWriteCommand(sql);
|
||||
if (write) {
|
||||
const safety = evaluateMongoWriteSafety(write, sqlSafetyFromEnv());
|
||||
@@ -196,7 +212,7 @@ export async function executeQuery(config: ConnectionConfig, sql: string, option
|
||||
return { columns: [], rows: [], row_count: affected };
|
||||
}
|
||||
throw new Error(
|
||||
"Use MongoDB shell-style commands, for example: db.projects.find({}).limit(100), db.projects.countDocuments({}), db.projects.insertOne({...}), db.projects.updateOne({...}, {$set: {...}}), or db.projects.deleteOne({...})",
|
||||
"Use MongoDB shell-style commands, for example: db.projects.find({}).limit(100), db.projects.countDocuments({}), db.projects.getIndexes(), db.projects.insertOne({...}), db.projects.updateOne({...}, {$set: {...}}), or db.projects.deleteOne({...})",
|
||||
);
|
||||
}
|
||||
const res = await apiFetch("/api/query/execute", {
|
||||
|
||||
@@ -8,6 +8,7 @@ import {
|
||||
parseMongoAggregateCommand,
|
||||
parseMongoCountDocumentsCommand,
|
||||
parseMongoFindCommand,
|
||||
parseMongoGetIndexesCommand,
|
||||
parseMongoWriteCommand,
|
||||
} from "../src/database.js";
|
||||
|
||||
@@ -53,6 +54,16 @@ test("parseMongoAggregateCommand accepts aggregate pipelines", () => {
|
||||
});
|
||||
});
|
||||
|
||||
test("parseMongoGetIndexesCommand accepts shell-style index commands", () => {
|
||||
assert.deepEqual(parseMongoGetIndexesCommand("db.web_log.getIndexes();"), {
|
||||
collection: "web_log",
|
||||
});
|
||||
assert.deepEqual(parseMongoGetIndexesCommand('db.getCollection("audit.logs").getIndexes()'), {
|
||||
collection: "audit.logs",
|
||||
});
|
||||
assert.equal(parseMongoGetIndexesCommand("db.web_log.getIndexes({})"), null);
|
||||
});
|
||||
|
||||
test("mongoAggregateWriteStage detects write stages", () => {
|
||||
assert.equal(mongoAggregateWriteStage('[{"$match":{"active":true}}]'), null);
|
||||
assert.equal(mongoAggregateWriteStage('[{"$match":{}},{"$out":"projects_dump"}]'), "$out");
|
||||
|
||||
Reference in New Issue
Block a user