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(mongodb): limit cursor methods after aggregate and count

Loc Nguyen57ecec9cf833
diff --git a/apps/desktop/src/lib/mongo/mongoCompletion.ts b/apps/desktop/src/lib/mongo/mongoCompletion.ts
index b735541639..94a10b53ee 100644
--- a/apps/desktop/src/lib/mongo/mongoCompletion.ts
+++ b/apps/desktop/src/lib/mongo/mongoCompletion.ts
@@ -194,6 +194,15 @@ const CURSOR_METHODS = [
*/
const CURSOR_COUNT_METHOD = { label: "count", detail: "Count the documents matched by find()", apply: "count()" } as const;
+/**
+ * Cursor methods that change nothing: results are always materialised, so DBX
+ * drops these calls at execution time. Accepted after both find() and aggregate().
+ */
+const NOOP_CURSOR_METHODS = [
+ { label: "toArray", detail: "Materialise cursor results into an array", apply: "toArray()" },
+ { label: "pretty", detail: "Format results for display", apply: "pretty()" },
+] as const;
+
const ROOT_SNIPPETS = [
{ label: "db.collection.find", detail: "Find documents", apply: "db.${collection}.find({})" },
{ label: "db.collection.aggregate", detail: "Aggregation pipeline", apply: "db.${collection}.aggregate([\n { $match: {} }\n])" },
@@ -334,6 +343,7 @@ export function getMongoCompletionContext(text: string, cursor: number): MongoCo
const cursorChain = matchCursorMethodDot(beforeCursor);
if (cursorChain) {
+ if (cursorChain.terminal) return at("none");
const methodPrefix = readMethodPrefix(beforeCursor);
return { mode: "cursorMethod", prefix: methodPrefix.prefix, from: methodPrefix.from, collection, database, stage: cursorChain.countable ? "countable" : cursorChain.find ? "find" : undefined };
}
@@ -1229,9 +1239,13 @@ function methodItems(prefix: string): MongoCompletionItem[] {
);
}
-/** `collation()` is a find-cursor method only, so it is withheld after `aggregate(…)`. */
+/**
+ * Cursor methods offered after `find(…)` or `aggregate(…)`.
+ * After `aggregate(…)`, only no-op helpers `toArray()` and `pretty()` are accepted;
+ * all other cursor methods are find-only.
+ */
function cursorMethodItems(prefix: string, countable: boolean, find: boolean): MongoCompletionItem[] {
- const methods = [...CURSOR_METHODS.filter((method) => find || method.label !== "collation"), ...(countable ? [CURSOR_COUNT_METHOD] : [])];
+ const methods = find ? [...CURSOR_METHODS, ...(countable ? [CURSOR_COUNT_METHOD] : []), ...NOOP_CURSOR_METHODS] : [...NOOP_CURSOR_METHODS];
return dedupeAndSort(
methods
.filter((method) => matchesFuzzyPrefix(method.label, prefix))
@@ -1240,7 +1254,7 @@ function cursorMethodItems(prefix: string, countable: boolean, find: boolean): M
type: "function" as const,
detail: method.detail,
apply: method.apply,
- boost: method.label === "limit" ? 150 : method.label === "sort" ? 140 : method.label === "skip" ? 130 : method.label === "collation" ? 115 : 120,
+ boost: method.label === "limit" ? 150 : method.label === "sort" ? 140 : method.label === "skip" ? 130 : method.label === "collation" ? 115 : method.label === "toArray" ? 100 : method.label === "pretty" ? 95 : 120,
})),
);
}
@@ -1462,10 +1476,11 @@ function isAfterCollectionDot(beforeCursor: string): boolean {
}
/**
- * `db.x.find(…).…` — and whether `count()` is still legal there, which it only
- * is while no other cursor method has been chained on.
+ * `db.x.find(…).…` or `db.x.aggregate(…).…` — matches cursor method chaining positions.
+ * Recognises find chains (including terminal `count()` and `explain()`), and aggregate
+ * chains (which only accept `toArray()` and `pretty()`).
*/
-function matchCursorMethodDot(beforeCursor: string): { find: boolean; countable: boolean } | null {
+function matchCursorMethodDot(beforeCursor: string): { find: boolean; countable: boolean; terminal?: boolean } | null {
const collectionCall = new RegExp(String.raw`(?:^|[\s;(])${DB_ROOT}\.${COLLECTION_REF}\.(find|aggregate)\s*\(`, "g");
let lastMatch: RegExpExecArray | null = null;
let match: RegExpExecArray | null;
@@ -1477,8 +1492,22 @@ function matchCursorMethodDot(beforeCursor: string): { find: boolean; countable:
if (closeParen < 0) return null;
const chain = beforeCursor.slice(closeParen + 1);
- if (!/^(?:\s*\.\s*(?:sort|skip|limit|collation)\s*\([^()]*\))*\s*\.\s*[\w$-]*$/.test(chain)) return null;
- return { find: lastMatch[1] === "find", countable: lastMatch[1] === "find" && /^\s*\.\s*[\w$-]*$/.test(chain) };
+ if (!/\.\s*[\w$-]*$/.test(chain)) return null;
+
+ const isFind = lastMatch[1] === "find";
+ if (/\.\s*(?:count|explain)\s*\([^()]*\)/.test(chain)) {
+ return { find: isFind, countable: false, terminal: true };
+ }
+
+ if (isFind) {
+ if (!/^(?:\s*\.\s*(?:sort|skip|limit|collation|toArray|pretty)\s*\([^()]*\))*\s*\.\s*[\w$-]*$/.test(chain)) return null;
+ return { find: true, countable: /^\s*\.\s*[\w$-]*$/.test(chain) };
+ }
+
+ if (!/^(?:\s*\.\s*(?:toArray|pretty)\s*\([^()]*\))*\s*\.\s*[\w$-]*$/.test(chain)) {
+ return { find: false, countable: false, terminal: true };
+ }
+ return { find: false, countable: false };
}
function findMatchingParen(text: string, openIndex: number): number {
diff --git a/packages/app-tests/mongoCompletion.test.ts b/packages/app-tests/mongoCompletion.test.ts
index 20c364bd62..040f7eea89 100644
--- a/packages/app-tests/mongoCompletion.test.ts
+++ b/packages/app-tests/mongoCompletion.test.ts
@@ -138,7 +138,7 @@ test("prioritizes common read helpers and keeps destructive helpers last", () =>
assert.deepEqual(methodLabels.slice(0, 6), ["find", "findOne", "aggregate", "countDocuments", "estimatedDocumentCount", "distinct"]);
assert.deepEqual(getCollectionMethodLabels.slice(0, 6), ["find", "findOne", "aggregate", "countDocuments", "estimatedDocumentCount", "distinct"]);
assert.deepEqual(methodLabels.slice(-3), ["dropIndex", "dropIndexes", "drop"]);
- assert.deepEqual(labels("db.users.find({})."), ["limit", "sort", "skip", "count", "explain", "collation"]);
+ assert.deepEqual(labels("db.users.find({})."), ["limit", "sort", "skip", "count", "explain", "collation", "toArray", "pretty"]);
});
test("keeps dotted collection names ahead of methods until the collection is resolved", () => {
@@ -163,7 +163,7 @@ test("suggests cursor methods after find result chains", () => {
assert.deepEqual(
allItems.map((item) => item.label),
- ["limit", "sort", "skip", "count", "explain", "collation"],
+ ["limit", "sort", "skip", "count", "explain", "collation", "toArray", "pretty"],
);
assert.deepEqual(
prefixedItems.map((item) => item.label),
@@ -171,7 +171,7 @@ test("suggests cursor methods after find result chains", () => {
);
assert.deepEqual(
formattedChainItems.map((item) => item.label),
- ["limit", "sort", "skip", "count", "explain", "collation"],
+ ["limit", "sort", "skip", "count", "explain", "collation", "toArray", "pretty"],
);
assert.deepEqual(
formattedPrefixedItems.map((item) => item.label),
@@ -183,9 +183,51 @@ test("offers count only where find().count() actually parses", () => {
// The shell parser accepts count() only as the sole call chained onto find().
assert.ok(labels("db.characters.find({}).").includes("count"));
assert.equal(labels("db.characters.find({}).sort({ name: 1 }).").includes("count"), false);
+ assert.equal(labels("db.characters.find({}).toArray().").includes("count"), false);
+ assert.equal(labels("db.characters.find({}).pretty().").includes("count"), false);
assert.equal(labels("db.characters.aggregate([]).").includes("count"), false);
});
+test("offers only accepted cursor methods toArray and pretty after aggregate", () => {
+ // The executor rejects limit, sort, skip, explain, etc. after aggregate(), accepting only toArray() and pretty().
+ assert.deepEqual(labels("db.characters.aggregate([])."), ["toArray", "pretty"]);
+ assert.deepEqual(labels("db.characters.aggregate([], { allowDiskUse: true })."), ["toArray", "pretty"]);
+ assert.deepEqual(labels("db.characters.aggregate([]).toArray()."), ["toArray", "pretty"]);
+ assert.deepEqual(labels("db.characters.aggregate([]).pretty()."), ["toArray", "pretty"]);
+ assert.deepEqual(labels("db.characters.aggregate([]).to"), ["toArray"]);
+ assert.deepEqual(labels("db.characters.aggregate([]).pr"), ["pretty"]);
+
+ for (const rejected of ["limit", "sort", "skip", "explain", "collation", "count"]) {
+ assert.equal(labels("db.characters.aggregate([]).").includes(rejected), false, `${rejected} should not be offered after aggregate()`);
+ }
+});
+
+test("recognises toArray and pretty in find chains and keeps count restricted", () => {
+ const expectedChainMethods = ["limit", "sort", "skip", "explain", "collation", "toArray", "pretty"];
+ assert.deepEqual(labels("db.characters.find({}).toArray()."), expectedChainMethods);
+ assert.deepEqual(labels("db.characters.find({}).pretty()."), expectedChainMethods);
+ assert.deepEqual(labels("db.characters.find({}).sort({ name: 1 }).toArray()."), expectedChainMethods);
+});
+
+test("stops offering root snippets after terminal cursor methods count and explain", () => {
+ // Nothing can follow count() or explain(); these positions must yield mode "none" rather than root db.* snippets.
+ assert.equal(getMongoCompletionContext("db.users.find({}).count().", "db.users.find({}).count().".length).mode, "none");
+ assert.deepEqual(labels("db.users.find({}).count()."), []);
+ assert.deepEqual(labels("db.users.find({}).count().db"), []);
+ assert.deepEqual(labels("db.characters.find({}).count()."), []);
+
+ assert.equal(getMongoCompletionContext("db.users.find({}).explain().", "db.users.find({}).explain().".length).mode, "none");
+ assert.deepEqual(labels("db.users.find({}).explain()."), []);
+ assert.deepEqual(labels('db.users.find({}).explain("executionStats").'), []);
+ assert.deepEqual(labels("db.users.find({}).sort({ name: 1 }).explain()."), []);
+ assert.deepEqual(labels("db.users.find({}).explain().db"), []);
+ assert.deepEqual(labels("db.users.find({}).explain().lim"), []);
+
+ assert.deepEqual(labels("db.users.aggregate([]).count()."), []);
+ assert.deepEqual(labels("db.users.aggregate([]).explain()."), []);
+ assert.deepEqual(labels("db.users.aggregate([]).limit(5)."), []);
+});
+
test("suggests observed fields inside query objects", () => {
const items = buildMongoCompletionItems('db.users.find({ "pro', 'db.users.find({ "pro'.length, { fields });
const email = items.find((item) => item.label === "profile.email");
@@ -876,8 +918,8 @@ test("completes the collation document wherever it appears", () => {
assert.deepEqual(labels('db.users.find({}).collation({ strength: "'), []);
assert.deepEqual(labels('db.users.find({}).collation({ locale: "'), []);
// The chain continues after collation(), and collation() is a find-cursor method only.
- assert.deepEqual(labels('db.users.find({}).collation({ locale: "en" }).'), ["limit", "sort", "skip", "explain", "collation"]);
- assert.ok(!labels("db.users.aggregate([]).").includes("collation"));
+ assert.deepEqual(labels('db.users.find({}).collation({ locale: "en" }).'), ["limit", "sort", "skip", "explain", "collation", "toArray", "pretty"]);
+ assert.deepEqual(labels("db.users.aggregate([])."), ["toArray", "pretty"]);
});
test("completes an index's partial filter as a filter", () => {