fix(mongodb): limit cursor methods after aggregate and count

This commit is contained in:
Loc Nguyen authored and GitHub committed 2026-10-01 22:35:59 +08:00
1 parent b6049d80d0
commit 57ecec9cf8
2 files changed
+84 -13

No files matched your search

+37 -8
View File
@@ -194,6 +194,15 @@ const CURSOR_METHODS = [
*/ */
const CURSOR_COUNT_METHOD = { label: "count", detail: "Count the documents matched by find()", apply: "count()" } as const; 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 = [ const ROOT_SNIPPETS = [
{ label: "db.collection.find", detail: "Find documents", apply: "db.${collection}.find({})" }, { 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])" }, { 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); const cursorChain = matchCursorMethodDot(beforeCursor);
if (cursorChain) { if (cursorChain) {
if (cursorChain.terminal) return at("none");
const methodPrefix = readMethodPrefix(beforeCursor); const methodPrefix = readMethodPrefix(beforeCursor);
return { mode: "cursorMethod", prefix: methodPrefix.prefix, from: methodPrefix.from, collection, database, stage: cursorChain.countable ? "countable" : cursorChain.find ? "find" : undefined }; 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[] { 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( return dedupeAndSort(
methods methods
.filter((method) => matchesFuzzyPrefix(method.label, prefix)) .filter((method) => matchesFuzzyPrefix(method.label, prefix))
@@ -1240,7 +1254,7 @@ function cursorMethodItems(prefix: string, countable: boolean, find: boolean): M
type: "function" as const, type: "function" as const,
detail: method.detail, detail: method.detail,
apply: method.apply, 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 * `db.x.find(…).…` or `db.x.aggregate(…).…` — matches cursor method chaining positions.
* is while no other cursor method has been chained on. * 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"); const collectionCall = new RegExp(String.raw`(?:^|[\s;(])${DB_ROOT}\.${COLLECTION_REF}\.(find|aggregate)\s*\(`, "g");
let lastMatch: RegExpExecArray | null = null; let lastMatch: RegExpExecArray | null = null;
let match: RegExpExecArray | null; let match: RegExpExecArray | null;
@@ -1477,8 +1492,22 @@ function matchCursorMethodDot(beforeCursor: string): { find: boolean; countable:
if (closeParen < 0) return null; if (closeParen < 0) return null;
const chain = beforeCursor.slice(closeParen + 1); const chain = beforeCursor.slice(closeParen + 1);
if (!/^(?:\s*\.\s*(?:sort|skip|limit|collation)\s*\([^()]*\))*\s*\.\s*[\w$-]*$/.test(chain)) return null; if (!/\.\s*[\w$-]*$/.test(chain)) return null;
return { find: lastMatch[1] === "find", countable: lastMatch[1] === "find" && /^\s*\.\s*[\w$-]*$/.test(chain) };
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 { function findMatchingParen(text: string, openIndex: number): number {
+47 -5
View File
@@ -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(methodLabels.slice(0, 6), ["find", "findOne", "aggregate", "countDocuments", "estimatedDocumentCount", "distinct"]);
assert.deepEqual(getCollectionMethodLabels.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(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", () => { 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( assert.deepEqual(
allItems.map((item) => item.label), allItems.map((item) => item.label),
["limit", "sort", "skip", "count", "explain", "collation"], ["limit", "sort", "skip", "count", "explain", "collation", "toArray", "pretty"],
); );
assert.deepEqual( assert.deepEqual(
prefixedItems.map((item) => item.label), prefixedItems.map((item) => item.label),
@@ -171,7 +171,7 @@ test("suggests cursor methods after find result chains", () => {
); );
assert.deepEqual( assert.deepEqual(
formattedChainItems.map((item) => item.label), formattedChainItems.map((item) => item.label),
["limit", "sort", "skip", "count", "explain", "collation"], ["limit", "sort", "skip", "count", "explain", "collation", "toArray", "pretty"],
); );
assert.deepEqual( assert.deepEqual(
formattedPrefixedItems.map((item) => item.label), 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(). // The shell parser accepts count() only as the sole call chained onto find().
assert.ok(labels("db.characters.find({}).").includes("count")); 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({}).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); 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", () => { test("suggests observed fields inside query objects", () => {
const items = buildMongoCompletionItems('db.users.find({ "pro', 'db.users.find({ "pro'.length, { fields }); const items = buildMongoCompletionItems('db.users.find({ "pro', 'db.users.find({ "pro'.length, { fields });
const email = items.find((item) => item.label === "profile.email"); 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({ strength: "'), []);
assert.deepEqual(labels('db.users.find({}).collation({ locale: "'), []); assert.deepEqual(labels('db.users.find({}).collation({ locale: "'), []);
// The chain continues after collation(), and collation() is a find-cursor method only. // 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.deepEqual(labels('db.users.find({}).collation({ locale: "en" }).'), ["limit", "sort", "skip", "explain", "collation", "toArray", "pretty"]);
assert.ok(!labels("db.users.aggregate([]).").includes("collation")); assert.deepEqual(labels("db.users.aggregate([])."), ["toArray", "pretty"]);
}); });
test("completes an index's partial filter as a filter", () => { test("completes an index's partial filter as a filter", () => {