From 0cdd634d2089e126726b07b80a424a74cac64223 Mon Sep 17 00:00:00 2001 From: Loc Nguyen <113083148+thailoc-dev@users.noreply.github.com> Date: Fri, 2 Oct 2026 08:07:33 +0700 Subject: [PATCH] feat(completion): complete mongo show dbs and createUser --- apps/desktop/src/lib/mongo/mongoCompletion.ts | 58 +++++++++++-- .../src/lib/mongo/mongoCompletionTables.ts | 7 ++ packages/app-tests/mongoCompletion.test.ts | 84 ++++++++++++++++++- 3 files changed, 141 insertions(+), 8 deletions(-) diff --git a/apps/desktop/src/lib/mongo/mongoCompletion.ts b/apps/desktop/src/lib/mongo/mongoCompletion.ts index 1b9b2c3bd5..7243736dac 100644 --- a/apps/desktop/src/lib/mongo/mongoCompletion.ts +++ b/apps/desktop/src/lib/mongo/mongoCompletion.ts @@ -60,7 +60,8 @@ export type MongoCompletionMode = | "bulkWriteField" | "keyMapValue" | "operatorField" - | "enumValue"; + | "enumValue" + | "showSubcommand"; /** Kind of aggregation or update pipeline holding the cursor. */ export type MongoPipelineKind = "aggregate" | "update" | "facet" | "join" | "view"; @@ -125,6 +126,7 @@ const COLLECTION_METHODS = [ { label: "distinct", detail: "List the distinct values of a field", apply: 'distinct("${field}")' }, { label: "insertOne", detail: "Insert one document", apply: "insertOne({})" }, { label: "insertMany", detail: "Insert multiple documents", apply: "insertMany([{}])" }, + { label: "insert", detail: "Insert documents (legacy helper)", apply: "insert({})" }, { label: "updateOne", detail: "Update one matching document", apply: "updateOne({}, { $set: {} })" }, { label: "updateMany", detail: "Update all matching documents", apply: "updateMany({}, { $set: {} })" }, { label: "replaceOne", detail: "Replace one matching document", apply: "replaceOne({}, {})" }, @@ -168,6 +170,7 @@ const COLLECTION_METHOD_BOOST: Record<(typeof COLLECTION_METHODS)[number]["label stats: 95, createIndex: 90, count: 80, + insert: 80, dataSize: 75, storageSize: 70, totalIndexSize: 65, @@ -185,6 +188,7 @@ const DATABASE_METHODS = [ { label: "runCommand", detail: "Run a database command document", apply: "runCommand({ ${} })" }, { label: "stats", detail: "Show database statistics", apply: "stats()" }, { label: "serverStatus", detail: "Show server status", apply: "serverStatus()" }, + { label: "createUser", detail: "Create a database user", apply: 'createUser({ user: "${name}", pwd: "${password}", roles: [] })' }, { label: "createCollection", detail: "Create a collection", apply: 'createCollection("${name}")' }, { label: "dropDatabase", detail: "Drop the current database", apply: "dropDatabase()" }, ] as const; @@ -217,6 +221,7 @@ const ROOT_SNIPPETS = [ { label: "db.collection.aggregate", detail: "Aggregation pipeline", apply: "db.${collection}.aggregate([\n { $match: {} }\n])" }, { label: "db.getCollection", detail: "Reference a collection by name", apply: 'db.getCollection("${}")' }, { label: "use", detail: "Switch the active database", apply: "use ${database}" }, + { label: "show dbs", detail: "List available databases", apply: "show dbs" }, { label: "db.version", detail: "Show the MongoDB server version", apply: "db.version()" }, { label: "db.stats", detail: "Show database statistics", apply: "db.stats()" }, { label: "db.serverStatus", detail: "Show server status", apply: "db.serverStatus()" }, @@ -227,6 +232,7 @@ const ROOT_SNIPPET_BOOST: Record<(typeof ROOT_SNIPPETS)[number]["label"], number "db.collection.aggregate": 340, "db.getCollection": 330, use: 320, + "show dbs": 305, "db.version": 310, "db.stats": 305, "db.serverStatus": 300, @@ -251,6 +257,7 @@ const METHOD_ARG_ROLES: Record = { findOneAndReplace: ["filter", "replacement", "options"], insertOne: ["document"], insertMany: ["documents"], + insert: ["documents"], aggregate: ["pipeline", "options"], createIndex: ["keys", "options"], distinct: ["fieldName", "filter"], @@ -260,6 +267,7 @@ const METHOD_ARG_ROLES: Record = { // Database-level helpers whose argument is a document. createCollection: ["name", "options"], runCommand: ["options"], + createUser: ["options"], }; /** `{ $oid: "..." }` for a bare value position, where the user has not typed the braces yet. */ @@ -338,6 +346,9 @@ export function getMongoCompletionContext(text: string, cursor: number): MongoCo const usePrefix = matchUseDatabasePrefix(beforeCursor); if (usePrefix) return { mode: "database", prefix: usePrefix.prefix, from: usePrefix.from }; + const showPrefix = matchShowSubcommandPrefix(beforeCursor); + if (showPrefix) return { mode: "showSubcommand", prefix: showPrefix.prefix, from: showPrefix.from }; + if (endsAtDbRootDot(beforeCursor)) { return { mode: "collection", @@ -400,10 +411,10 @@ export function getMongoCompletionContext(text: string, cursor: number): MongoCo // Top-level snippets belong at the start of a command. Inside an argument list — of a method // this engine does not model (`limit(`, `drop(`, `dropIndex("`, `runCommand({`, …) or after a // `use` — they are noise: `db.collection.find` is not something you can type there. - if (!call) return isInsideCallArguments(beforeCursor) || isAfterUseKeyword(beforeCursor) ? at("none") : at("root"); + if (!call) return isInsideCallArguments(beforeCursor) || isAfterUseKeyword(beforeCursor) || isAfterShowKeyword(beforeCursor) ? at("none") : at("root"); const scan = scanMongoCallArguments(text, call.openParenIndex + 1, safeCursor); - if (!scan) return isInsideCallArguments(beforeCursor) || isAfterUseKeyword(beforeCursor) ? at("none") : at("root"); + if (!scan) return isInsideCallArguments(beforeCursor) || isAfterUseKeyword(beforeCursor) || isAfterShowKeyword(beforeCursor) ? at("none") : at("root"); const classified = classifyCursorInCall(call.method, scan); return { @@ -435,6 +446,9 @@ export function buildMongoCompletionItemsFromContext(context: MongoCompletionCon case "database": items = databaseItems(prefix, input.databases ?? []); break; + case "showSubcommand": + items = showSubcommandItems(prefix); + break; case "collection": items = collectionItems(prefix, collections, context.siblingRoot ?? false); break; @@ -541,8 +555,8 @@ export function shouldAutoOpenMongoCompletion(text: string, cursor: number): boo const previousChar = text[cursor - 1]; if (!previousChar) return false; if (text.slice(0, cursor).endsWith("db.")) return true; - // `use ` names a database next; open the list as soon as the space is typed. - if (previousChar === " " && matchUseDatabasePrefix(text.slice(0, cursor))) return true; + // `use ` and `show ` name a database or subcommand next; open the list as soon as the space is typed. + if (previousChar === " " && (matchUseDatabasePrefix(text.slice(0, cursor)) || matchShowSubcommandPrefix(text.slice(0, cursor)))) return true; if (previousChar === "$" || previousChar === "." || previousChar === '"' || previousChar === "'") return true; if (/[{,[:]/.test(previousChar) || /[{,[:]\s+$/.test(text.slice(0, cursor))) { return getMongoCompletionContext(text, cursor).mode !== "none"; @@ -824,7 +838,7 @@ function classifyCursorInCall(method: string, scan: MongoCallScan): MongoCursorC case "document": return { mode: classifyDocument(scan, 0) }; case "documents": - return { mode: classifyDocument(scan, 1) }; + return { mode: scan.stack[0]?.kind === "array" ? classifyDocument(scan, 1) : classifyDocument(scan, 0) }; case "projection": return classifyKeyMap(scan, 0, "projection"); case "keys": @@ -1335,6 +1349,21 @@ function rootItems(prefix: string): MongoCompletionItem[] { return dedupeAndSort([...snippets, ...methods]); } +const SHOW_SUBCOMMANDS = [ + { label: "dbs", detail: "List available databases", apply: "dbs", boost: 210 }, + { label: "databases", detail: "List available databases", apply: "databases", boost: 200 }, +] as const; + +function showSubcommandItems(prefix: string): MongoCompletionItem[] { + return SHOW_SUBCOMMANDS.filter((item) => matchesFuzzyPrefix(item.label, prefix)).map((item) => ({ + label: item.label, + type: "keyword" as const, + detail: item.detail, + apply: item.apply, + boost: startsWithPrefix(item.label, prefix) ? item.boost : item.boost - 30, + })); +} + function collectionItems(prefix: string, collections: string[], siblingRoot = false): MongoCompletionItem[] { const names = collectionNameItems(prefix, collections); const methods = DATABASE_METHODS.filter((method) => (siblingRoot ? method.label !== "getSiblingDB" : true) && matchesFuzzyPrefix(method.label, prefix)).map((method) => ({ @@ -1664,6 +1693,17 @@ function matchUseDatabasePrefix(beforeCursor: string): { prefix: string; from: n return { prefix: beforeCursor.slice(beforeCursor.length - prefix.length), from: beforeCursor.length - prefix.length }; } +/** + * Cursor in the bare subcommand after `show`. + */ +function matchShowSubcommandPrefix(beforeCursor: string): { prefix: string; from: number } | null { + const currentLine = maskMongoLiterals(beforeCursor).split("\n").pop() ?? ""; + const match = /(?:^|[\s;])show\s+([^\s;"'()]*)$/i.exec(currentLine); + if (!match || isInsideCallArguments(beforeCursor)) return null; + const prefix = match[1] ?? ""; + return { prefix: beforeCursor.slice(beforeCursor.length - prefix.length), from: beforeCursor.length - prefix.length }; +} + function matchGetCollectionPrefix(beforeCursor: string): { prefix: string; from: number } | null { const match = new RegExp(String.raw`(?:^|[\s;(])${DB_ROOT}\.getCollection\(\s*(["'][^"'\\]*)$`).exec(beforeCursor); if (!match) return null; @@ -1781,6 +1821,12 @@ function isAfterUseKeyword(beforeCursor: string): boolean { return /(?:^|[\s;])use\s+[\w$-]*$/.test(maskMongoLiterals(beforeCursor)); } +/** After `show` on the current line, to keep root snippets from leaking once arguments/words trail. */ +function isAfterShowKeyword(beforeCursor: string): boolean { + const currentLine = maskMongoLiterals(beforeCursor).split("\n").pop() ?? ""; + return /(?:^|[\s;])show\s+[\w$-]*(?:\s+[\w$-]*)*$/i.test(currentLine); +} + /** Blank out string/comment CONTENT (preserving length, so offsets stay valid) before pattern matching. */ function maskMongoLiterals(text: string): string { const chars = [...text]; diff --git a/apps/desktop/src/lib/mongo/mongoCompletionTables.ts b/apps/desktop/src/lib/mongo/mongoCompletionTables.ts index 5575c970a4..c034f1b149 100644 --- a/apps/desktop/src/lib/mongo/mongoCompletionTables.ts +++ b/apps/desktop/src/lib/mongo/mongoCompletionTables.ts @@ -669,6 +669,13 @@ export const METHOD_OPTION_KEYS: Record = { ["pipeline", "Aggregation pipeline the view applies", "pipeline: [${}]"], ["changeStreamPreAndPostImages", "Record document images for change streams", "changeStreamPreAndPostImages: { enabled: true }"], ]), + createUser: specs([ + ["user", "User name", 'user: "${name}"'], + ["pwd", "User password", 'pwd: "${password}"'], + ["roles", "Roles granted to the user", "roles: []"], + ["customData", "Arbitrary information stored with the user", "customData: {}"], + ["mechanisms", "Authentication mechanisms", "mechanisms: [${}]"], + ]), // Command documents run as written, so this lists the commands worth typing by hand. runCommand: specs([ ["ping", "Check that the server responds", "ping: 1"], diff --git a/packages/app-tests/mongoCompletion.test.ts b/packages/app-tests/mongoCompletion.test.ts index 13e6dd91b7..f8445bdb88 100644 --- a/packages/app-tests/mongoCompletion.test.ts +++ b/packages/app-tests/mongoCompletion.test.ts @@ -699,6 +699,26 @@ test("stays quiet in the trailing argument of methods that take no options", () } }); +test("completes legacy insert helper arguments and stays quiet in trailing arguments", () => { + assert.ok(labels("db.users.").includes("insert")); + assert.ok(labels("db.users.ins").includes("insert")); + assert.ok(labels("ins").includes("insert")); + + // Both document and array shapes complete collection fields + assert.deepEqual(labels("db.users.insert({ na", { fields }), ["name"]); + assert.deepEqual(labels("db.users.insert([{ na", { fields }), ["name"]); + assert.ok(labels("db.users.insert({ name: ", { fields }).includes("ObjectId")); + assert.ok(labels("db.users.insert([{ name: ", { fields }).includes("ObjectId")); + + // Stays quiet in trailing options argument because insert takes no options + assert.deepEqual(labels("db.users.insert({}, { ", { fields, collections }), []); + assert.deepEqual(labels("db.users.insert([{}], { ", { fields, collections }), []); + + // Every new insert snippet shape parses + assert.ok(parseMongoCommand("db.users.insert({})")); + assert.ok(parseMongoCommand("db.users.insert([{}])")); +}); + test("every suggested option key parses on the method that offers it", () => { // The option sets mirror the driver's own structs, most of which reject unknown fields, so a // key that only exists in this table would complete into a command that fails at Run. @@ -739,7 +759,7 @@ test("every suggested option key parses on the method that offers it", () => { }; for (const [method, options] of Object.entries(METHOD_OPTION_KEYS)) { - if (method === "createCollection" || method === "runCommand") continue; // database-level: pinned from their own templates below + if (method === "createCollection" || method === "runCommand" || method === "createUser") continue; // database-level: pinned from their own templates below const args = callArgs[method]; assert.ok(args !== undefined, `${method} needs sample arguments in this test`); for (const option of options) { @@ -1189,7 +1209,7 @@ test("completes runCommand command names and their collection arguments", () => assert.ok(labels("db.").includes("runCommand")); }); -test("every suggested createCollection option and runCommand command parses", () => { +test("every suggested createCollection option, createUser option and runCommand command parses", () => { const render = (apply: string) => apply.replace(/\$\{([^{}]*)\}/g, (_, name: string) => name || "1"); for (const option of METHOD_OPTION_KEYS.createCollection ?? []) { const command = `db.createCollection("x", { ${render(option.apply)} })`; @@ -1199,6 +1219,10 @@ test("every suggested createCollection option and runCommand command parses", () const command = `db.runCommand({ ${render(spec.apply)} })`; assert.ok(parseMongoCommand(command), `${command} must parse`); } + for (const option of METHOD_OPTION_KEYS.createUser ?? []) { + const command = `db.createUser({ ${option.label === "user" ? "" : 'user: "test", '}${render(option.apply)} })`; + assert.ok(parseMongoCommand(command), `${command} must parse`); + } }); test("suggests the use and db.version commands", () => { @@ -1208,6 +1232,62 @@ test("suggests the use and db.version commands", () => { assert.equal(labels("db.getColl", { collections }).includes("getCollection"), true); }); +test("suggests show dbs and show subcommands", () => { + // Typing sh or show at root offers show dbs snippet + const shItems = buildMongoCompletionItems("sh", 2); + const showSnippet = shItems.find((item) => item.label === "show dbs"); + assert.ok(showSnippet, "typing sh offers show dbs"); + assert.equal(showSnippet?.apply, "show dbs"); + assert.ok(buildMongoCompletionItems("show", 4).some((item) => item.label === "show dbs")); + assert.ok(parseMongoCommand("show dbs"), "show dbs snippet must parse"); + + // show followed by space offers dbs and databases, and NOT db.* snippets + const showSpaceItems = labels("show "); + assert.deepEqual(showSpaceItems, ["dbs", "databases"]); + assert.equal(showSpaceItems.includes("db.collection.find"), false); + assert.equal(showSpaceItems.includes("db.version"), false); + assert.equal(showSpaceItems.includes("collections"), false, "show collections is not supported"); + + // Subcommand filtering + assert.deepEqual(labels("show d"), ["dbs", "databases"]); + assert.deepEqual(labels("show db"), ["dbs"]); + assert.deepEqual(labels("show dat"), ["databases"]); + assert.deepEqual(labels("show col"), []); + + // Context and auto-trigger + assert.deepEqual(getMongoCompletionContext("show ", 5), { mode: "showSubcommand", prefix: "", from: 5 }); + assert.deepEqual(getMongoCompletionContext("show db", 7), { mode: "showSubcommand", prefix: "db", from: 5 }); + assert.equal(shouldAutoOpenMongoCompletion("show ", 5), true); + + // Stays quiet when extra arguments follow rather than leaking root snippets + assert.deepEqual(labels("show dbs extra"), []); + + // Subsequent lines in scripts without semicolons retain root and db completions + assert.ok(labels("show dbs\nfi").includes("find")); + assert.ok(labels("show dbs\ndb.", { collections }).includes("users")); + assert.ok(labels("show dbs\ndb.", { collections }).includes("version")); + assert.ok(labels("show dbs\nsh").includes("show dbs")); +}); + +test("suggests createUser database helper and its document options", () => { + // Offered on db. alongside other database helpers + const dbHelpers = labels("db."); + assert.ok(dbHelpers.includes("createUser")); + const snippet = buildMongoCompletionItems("db.createU", "db.createU".length).find((item) => item.label === "createUser"); + assert.equal(snippet?.apply, 'createUser({ user: "${name}", pwd: "${password}", roles: [] })'); + + // Document argument options + const optionLabels = labels("db.createUser({ "); + assert.deepEqual(optionLabels, ["customData", "mechanisms", "pwd", "roles", "user"]); + assert.deepEqual(labels("db.createUser({ pw"), ["pwd"]); + + // Stays quiet inside sub-arrays/values rather than leaking root snippets + assert.deepEqual(labels("db.createUser({ roles: [ "), []); + + // Snippet parses via parseMongoCommand + assert.ok(parseMongoCommand('db.createUser({ user: "name", pwd: "password", roles: [] })')); +}); + test("ranks everyday operators above the long tail", () => { const queryOperators = labels("db.users.find({ age: { $").slice(0, 10); assert.ok(queryOperators.includes("$eq"));