feat(completion): suggest mongo operator-fitting values

This commit is contained in:
Loc Nguyen authored and GitHub committed 2026-10-02 09:09:09 +08:00
1 parent 0cdd634d20
commit 472f70b218
3 files changed
+146 -5

No files matched your search

+17 -3
View File
@@ -332,6 +332,11 @@ const STAGE_OPTION_VALUE_MODES: Record<string, Record<string, MongoCompletionMod
$fill: { partitionBy: "fieldRef" }, $fill: { partitionBy: "fieldRef" },
}; };
/** Enum value key inside a stage's option object, by stage and option key. */
const STAGE_OPTION_VALUE_ENUMS: Record<string, Record<string, string>> = {
$merge: { whenMatched: "whenMatched", whenNotMatched: "whenNotMatched" },
};
export function getMongoCompletionContext(text: string, cursor: number): MongoCompletionContext { export function getMongoCompletionContext(text: string, cursor: number): MongoCompletionContext {
const safeCursor = Math.max(0, Math.min(cursor, text.length)); const safeCursor = Math.max(0, Math.min(cursor, text.length));
const beforeCursor = text.slice(0, safeCursor); const beforeCursor = text.slice(0, safeCursor);
@@ -877,11 +882,17 @@ function innermost(scan: MongoCallScan): MongoContainer | undefined {
/** Query operators whose value is a document with its own keys rather than a field's constraint object. */ /** Query operators whose value is a document with its own keys rather than a field's constraint object. */
const SUB_DOCUMENT_QUERY_OPERATORS = new Set(["$text", "$geoWithin", "$geoIntersects", "$near", "$nearSphere", "$geometry"]); const SUB_DOCUMENT_QUERY_OPERATORS = new Set(["$text", "$geoWithin", "$geoIntersects", "$near", "$nearSphere", "$geometry"]);
/** Value positions in a filter that take a fixed set of strings, by the key and the operator that holds it. */ /** Value positions in a filter that take a fixed set of values, by the key and the operator that holds it. */
function filterValueEnum(operator: string | null, key: string | null): string | undefined { function filterValueEnum(operator: string | null, key: string | null): string | undefined {
if (key === "$type") return "$type"; if (key === "$type") return "$type";
if (key === "$options") return "$options"; if (key === "$options") return "$options";
if (key === "type" && operator === "$geometry") return "geometryType"; if (key === "type" && operator === "$geometry") return "geometryType";
if (key === "$exists") return "boolean";
if (operator === "$text") {
if (key === "$caseSensitive" || key === "$diacriticSensitive") return "boolean";
if (key === "$language") return "$language";
}
if (key === "$regex") return "$regex";
return undefined; return undefined;
} }
@@ -901,6 +912,7 @@ function classifyFilter(scan: MongoCallScan, rootIndex: number): MongoCursorClas
} }
if (inner.kind !== "object") return { mode: "none" }; if (inner.kind !== "object") return { mode: "none" };
if (scan.inValue) { if (scan.inValue) {
if (scan.valueKey === "$size" || scan.valueKey === "$mod") return { mode: "none" };
const enumKey = filterValueEnum(inner.key, scan.valueKey); const enumKey = filterValueEnum(inner.key, scan.valueKey);
if (enumKey) return { mode: "enumValue", enumKey }; if (enumKey) return { mode: "enumValue", enumKey };
return { mode: scan.inString ? "none" : "value" }; return { mode: scan.inString ? "none" : "value" };
@@ -1027,7 +1039,7 @@ const FILTER_OPTION_KEYS = new Set(["partialFilterExpression", "validator"]);
/** Option keys whose value is a document with its own fixed keys, and the value sets inside it. */ /** Option keys whose value is a document with its own fixed keys, and the value sets inside it. */
const SUB_DOCUMENT_OPTION_KEYS: Record<string, Record<string, string>> = { const SUB_DOCUMENT_OPTION_KEYS: Record<string, Record<string, string>> = {
collation: { caseFirst: "caseFirst", alternate: "alternate", maxVariable: "maxVariable", strength: "strength" }, collation: { locale: "locale", caseFirst: "caseFirst", alternate: "alternate", maxVariable: "maxVariable", strength: "strength" },
timeseries: { granularity: "granularity" }, timeseries: { granularity: "granularity" },
clusteredIndex: {}, clusteredIndex: {},
}; };
@@ -1251,6 +1263,8 @@ function classifyStageOptions(stage: string, scan: MongoCallScan, bodyIndex: num
if (depth === 0) { if (depth === 0) {
if (scan.inValue) { if (scan.inValue) {
const enumKey = STAGE_OPTION_VALUE_ENUMS[stage]?.[scan.valueKey ?? ""];
if (enumKey) return { mode: "enumValue", enumKey, stage };
const mode = STAGE_OPTION_VALUE_MODES[stage]?.[scan.valueKey ?? ""] ?? "none"; const mode = STAGE_OPTION_VALUE_MODES[stage]?.[scan.valueKey ?? ""] ?? "none";
const isJoinedField = (stage === "$lookup" && scan.valueKey === "foreignField") || (stage === "$graphLookup" && (scan.valueKey === "connectToField" || scan.valueKey === "connectFromField")); const isJoinedField = (stage === "$lookup" && scan.valueKey === "foreignField") || (stage === "$graphLookup" && (scan.valueKey === "connectToField" || scan.valueKey === "connectFromField"));
const collection = isJoinedField ? stageBody?.stringValues?.["from"] : undefined; const collection = isJoinedField ? stageBody?.stringValues?.["from"] : undefined;
@@ -1533,7 +1547,7 @@ function enumValueItems(prefix: string, values: readonly MongoOperatorSpec[], ca
.filter((value) => !quoted || value.apply.startsWith('"')) .filter((value) => !quoted || value.apply.startsWith('"'))
.map((value) => ({ .map((value) => ({
label: value.label, label: value.label,
type: "keyword" as const, type: mongoOperatorItemType(value.apply),
detail: value.detail, detail: value.detail,
info: `${category} value`, info: `${category} value`,
apply: quoted ? quoteMongoString(value.label, prefix) : value.apply, apply: quoted ? quoteMongoString(value.label, prefix) : value.apply,
@@ -569,6 +569,69 @@ export const ENUM_VALUES: Record<string, MongoOperatorSpec[]> = {
["linear", "Linear interpolation between surrounding values", '"linear"'], ["linear", "Linear interpolation between surrounding values", '"linear"'],
["locf", "Last observation carried forward", '"locf"'], ["locf", "Last observation carried forward", '"locf"'],
]), ]),
boolean: specs([
["true", "Boolean true", "true"],
["false", "Boolean false", "false"],
]),
$regex: specs([["/pattern/", "Regular expression literal", "/${pattern}/"]]),
$language: specs([
["none", "No language-specific rules", '"none"'],
["da", "Danish", '"da"'],
["de", "German", '"de"'],
["en", "English", '"en"'],
["es", "Spanish", '"es"'],
["fi", "Finnish", '"fi"'],
["fr", "French", '"fr"'],
["hu", "Hungarian", '"hu"'],
["it", "Italian", '"it"'],
["nb", "Norwegian", '"nb"'],
["nl", "Dutch", '"nl"'],
["pt", "Portuguese", '"pt"'],
["ro", "Romanian", '"ro"'],
["ru", "Russian", '"ru"'],
["sv", "Swedish", '"sv"'],
["tr", "Turkish", '"tr"'],
["danish", "Danish", '"danish"'],
["dutch", "Dutch", '"dutch"'],
["english", "English", '"english"'],
["finnish", "Finnish", '"finnish"'],
["french", "French", '"french"'],
["german", "German", '"german"'],
["hungarian", "Hungarian", '"hungarian"'],
["italian", "Italian", '"italian"'],
["norwegian", "Norwegian", '"norwegian"'],
["portuguese", "Portuguese", '"portuguese"'],
["romanian", "Romanian", '"romanian"'],
["russian", "Russian", '"russian"'],
["spanish", "Spanish", '"spanish"'],
["swedish", "Swedish", '"swedish"'],
["turkish", "Turkish", '"turkish"'],
]),
locale: specs([
["simple", "Simple binary comparison", '"simple"'],
["en", "English", '"en"'],
["fr", "French", '"fr"'],
["de", "German", '"de"'],
["es", "Spanish", '"es"'],
["pt", "Portuguese", '"pt"'],
["it", "Italian", '"it"'],
["ru", "Russian", '"ru"'],
["zh", "Chinese", '"zh"'],
["ja", "Japanese", '"ja"'],
["ko", "Korean", '"ko"'],
["ar", "Arabic", '"ar"'],
]),
whenMatched: specs([
["replace", "Replace the existing document", '"replace"'],
["keepExisting", "Keep the existing document", '"keepExisting"'],
["merge", "Merge the matching documents", '"merge"'],
["fail", "Fail the aggregation operation", '"fail"'],
]),
whenNotMatched: specs([
["insert", "Insert the document", '"insert"'],
["discard", "Discard the document", '"discard"'],
["fail", "Fail the aggregation operation", '"fail"'],
]),
}; };
export const BULK_WRITE_OPERATIONS: MongoOperatorSpec[] = specs([ export const BULK_WRITE_OPERATIONS: MongoOperatorSpec[] = specs([
+66 -2
View File
@@ -1082,6 +1082,63 @@ test("completes enumerated string values in and out of quotes", () => {
); );
}); });
test("suggests values that fit query operators and remaining fixed value sets", () => {
// $exists takes only a boolean: true / false outside quotes, none inside quotes
assert.deepEqual(labels("db.users.find({ name: { $exists: ", { fields }), ["true", "false"]);
assert.deepEqual(labels('db.users.find({ name: { $exists: "', { fields }), []);
// $size takes a non-negative integer: none
assert.deepEqual(labels("db.users.find({ name: { $size: ", { fields }), []);
assert.deepEqual(labels('db.users.find({ name: { $size: "', { fields }), []);
// $mod takes numbers: none outside and inside brackets
assert.deepEqual(labels("db.users.find({ name: { $mod: ", { fields }), []);
assert.deepEqual(labels("db.users.find({ name: { $mod: [", { fields }), []);
assert.deepEqual(labels('db.users.find({ name: { $mod: "', { fields }), []);
// $regex offers a /pattern/ regex literal snippet outside quotes, none inside quotes
assert.deepEqual(labels("db.users.find({ name: { $regex: ", { fields }), ["/pattern/"]);
const regexItem = buildMongoCompletionItems("db.users.find({ name: { $regex: ", "db.users.find({ name: { $regex: ".length, { fields })[0];
assert.equal(regexItem?.label, "/pattern/");
assert.equal(regexItem?.type, "snippet");
assert.equal(regexItem?.apply, "/${pattern}/");
assert.deepEqual(labels('db.users.find({ name: { $regex: "', { fields }), []);
// $options stays as is
assert.deepEqual(labels('db.users.find({ name: { $regex: "a", $options: "', { fields }), ["i", "m", "x", "s", "u"]);
assert.deepEqual(labels("db.users.find({ name: { $regex: 'a', $options: ", { fields }), ["i", "m", "x", "s", "u"]);
// $text boolean options -> true/false; $language -> common codes/names + none
assert.deepEqual(labels("db.users.find({ $text: { $caseSensitive: "), ["true", "false"]);
assert.deepEqual(labels('db.users.find({ $text: { $caseSensitive: "'), []);
assert.deepEqual(labels("db.users.find({ $text: { $diacriticSensitive: "), ["true", "false"]);
assert.deepEqual(labels('db.users.find({ $text: { $diacriticSensitive: "'), []);
const textLanguages = labels('db.users.find({ $text: { $language: "');
for (const code of ["none", "en", "fr", "de", "es", "it", "pt", "ru", "english", "spanish"]) {
assert.ok(textLanguages.includes(code), `expected $language to include ${code}`);
}
assert.ok(labels("db.users.find({ $text: { $language: ").includes("en"));
// $elemMatch remains unchanged (completing filter fields inside its object)
assert.deepEqual(labels("db.users.find({ items: { $elemMatch: { ", { fields }).slice(0, 3), ["_id", "createdAt", "name"]);
// $gt / $eq / $in still offer the full value list (ObjectId, ISODate, etc.)
const gtValues = labels("db.users.find({ age: { $gt: ", { fields });
for (const expected of ["ObjectId", "ISODate", "new Date", "NumberLong", "NumberInt", "NumberDecimal", "UUID", "BinData", "Timestamp", "MinKey", "MaxKey", "null", "true", "false"]) {
assert.ok(gtValues.includes(expected), `expected $gt to include ${expected}`);
}
const inValues = labels("db.users.find({ age: { $in: [", { fields });
for (const expected of ["ObjectId", "ISODate", "NumberInt"]) {
assert.ok(inValues.includes(expected), `expected $in to include ${expected}`);
}
// $merge whenMatched and whenNotMatched options
assert.deepEqual(labels('db.users.aggregate([{ $merge: { whenMatched: "'), ["replace", "keepExisting", "merge", "fail"]);
assert.deepEqual(labels("db.users.aggregate([{ $merge: { whenMatched: "), ["replace", "keepExisting", "merge", "fail"]);
assert.deepEqual(labels('db.users.aggregate([{ $merge: { whenNotMatched: "'), ["insert", "discard", "fail"]);
assert.deepEqual(labels("db.users.aggregate([{ $merge: { whenNotMatched: "), ["insert", "discard", "fail"]);
});
test("completes the collation document wherever it appears", () => { test("completes the collation document wherever it appears", () => {
const keys = ["alternate", "backwards", "caseFirst", "caseLevel", "locale", "maxVariable", "normalization", "numericOrdering", "strength"]; const keys = ["alternate", "backwards", "caseFirst", "caseLevel", "locale", "maxVariable", "normalization", "numericOrdering", "strength"];
assert.deepEqual(labels("db.users.find({}).collation({ "), keys); assert.deepEqual(labels("db.users.find({}).collation({ "), keys);
@@ -1093,7 +1150,8 @@ test("completes the collation document wherever it appears", () => {
assert.deepEqual(labels("db.users.find({}).collation({ strength: "), ["1", "2", "3", "4", "5"]); assert.deepEqual(labels("db.users.find({}).collation({ strength: "), ["1", "2", "3", "4", "5"]);
// Numbers are not offered inside a quote. // Numbers are not offered inside a quote.
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: "'), ["simple", "en", "fr", "de", "es", "pt", "it", "ru", "zh", "ja", "ko", "ar"]);
assert.deepEqual(labels("db.users.find({}).collation({ locale: "), ["simple", "en", "fr", "de", "es", "pt", "it", "ru", "zh", "ja", "ko", "ar"]);
// 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", "toArray", "pretty"]); assert.deepEqual(labels('db.users.find({}).collation({ locale: "en" }).'), ["limit", "sort", "skip", "explain", "collation", "toArray", "pretty"]);
assert.deepEqual(labels("db.users.aggregate([])."), ["toArray", "pretty"]); assert.deepEqual(labels("db.users.aggregate([])."), ["toArray", "pretty"]);
@@ -1149,12 +1207,18 @@ test("every suggested sub-document key and enumerated value parses in the positi
unit: (value) => `db.users.aggregate([{ $densify: { field: "t", range: { step: 1, unit: ${value} } } }])`, unit: (value) => `db.users.aggregate([{ $densify: { field: "t", range: { step: 1, unit: ${value} } } }])`,
bounds: (value) => `db.users.aggregate([{ $densify: { field: "t", range: { step: 1, bounds: ${value} } } }])`, bounds: (value) => `db.users.aggregate([{ $densify: { field: "t", range: { step: 1, bounds: ${value} } } }])`,
fillMethod: (value) => `db.users.aggregate([{ $fill: { output: { score: { method: ${value} } } } }])`, fillMethod: (value) => `db.users.aggregate([{ $fill: { output: { score: { method: ${value} } } } }])`,
boolean: (value) => `db.users.find({ a: { $exists: ${value} } })`,
$regex: (value) => `db.users.find({ a: { $regex: ${value} } })`,
$language: (value) => `db.users.find({ $text: { $search: "x", $language: ${value} } })`,
locale: (value) => `db.users.find({}).collation({ locale: ${value} })`,
whenMatched: (value) => `db.users.aggregate([{ $merge: { into: "out", whenMatched: ${value} } }])`,
whenNotMatched: (value) => `db.users.aggregate([{ $merge: { into: "out", whenNotMatched: ${value} } }])`,
}; };
for (const [enumKey, values] of Object.entries(ENUM_VALUES)) { for (const [enumKey, values] of Object.entries(ENUM_VALUES)) {
const build = valueCommands[enumKey]; const build = valueCommands[enumKey];
assert.ok(build, `${enumKey} needs a sample command in this test`); assert.ok(build, `${enumKey} needs a sample command in this test`);
for (const value of values) { for (const value of values) {
const command = build(value.apply); const command = build(render(value.apply));
assert.ok(parseMongoCommand(command), `${command} must parse`); assert.ok(parseMongoCommand(command), `${command} must parse`);
} }
} }