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。

feat(mongodb): complete runCommand and createCollection options

Loc Nguyenc8aed1b6e550
diff --git a/apps/desktop/src/lib/mongo/mongoCompletion.ts b/apps/desktop/src/lib/mongo/mongoCompletion.ts
index a129bb8ded..b735541639 100644
--- a/apps/desktop/src/lib/mongo/mongoCompletion.ts
+++ b/apps/desktop/src/lib/mongo/mongoCompletion.ts
@@ -173,6 +173,7 @@ const DATABASE_METHODS = [
{ label: "getCollection", detail: "Reference a collection by name", apply: 'getCollection("${}")' },
{ label: "version", detail: "Show the MongoDB server version", apply: "version()" },
{ label: "getSiblingDB", detail: "Run the next command against another database", apply: 'getSiblingDB("${database}")' },
+ { 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: "createCollection", detail: "Create a collection", apply: 'createCollection("${name}")' },
@@ -214,7 +215,7 @@ const ROOT_SNIPPET_BOOST: Record<(typeof ROOT_SNIPPETS)[number]["label"], number
};
/** Role of each positional argument, by collection helper. Drives cursor classification. */
-type MongoArgRole = "filter" | "update" | "replacement" | "document" | "documents" | "operations" | "pipeline" | "projection" | "keys" | "sortKeys" | "fieldName" | "options" | "collation" | "verbosity";
+type MongoArgRole = "filter" | "update" | "replacement" | "document" | "documents" | "operations" | "pipeline" | "projection" | "keys" | "sortKeys" | "fieldName" | "options" | "collation" | "verbosity" | "name";
const METHOD_ARG_ROLES: Record<string, readonly MongoArgRole[]> = {
find: ["filter", "projection"],
@@ -238,6 +239,9 @@ const METHOD_ARG_ROLES: Record<string, readonly MongoArgRole[]> = {
sort: ["sortKeys"],
collation: ["collation"],
explain: ["verbosity"],
+ // Database-level helpers whose argument is a document.
+ createCollection: ["name", "options"],
+ runCommand: ["options"],
};
/** `{ $oid: "..." }` for a bare value position, where the user has not typed the braces yet. */
@@ -254,6 +258,9 @@ const DOT_SCOPED_MODES = new Set<MongoCompletionMode>(["root", "collection", "co
/** Stages whose body is a fixed set of option keys rather than a field map. */
const OPTION_STAGES = new Set(Object.keys(STAGE_OPTION_KEYS));
+/** The stages an update pipeline accepts: those that rewrite the document without reshaping the result set. */
+const UPDATE_PIPELINE_STAGES = PIPELINE_STAGES.filter((stage) => ["$set", "$addFields", "$unset", "$project", "$replaceRoot", "$replaceWith"].includes(stage.label));
+
/** Stages taking a bare `"$field"` string, completed as a field reference. */
const FIELD_REF_STAGES = new Set(["$unwind", "$sortByCount", "$replaceWith"]);
@@ -421,13 +428,13 @@ export function buildMongoCompletionItemsFromContext(context: MongoCompletionCon
items = specItems(ACCUMULATORS, prefix, "accumulator", 100);
break;
case "stage":
- items = specItems(PIPELINE_STAGES, prefix, "aggregation stage", 100);
+ items = context.stage === "update" ? specItems(UPDATE_PIPELINE_STAGES, prefix, "update stage", 100) : specItems(PIPELINE_STAGES, prefix, "aggregation stage", 100);
break;
case "stageOption":
items = specItems(STAGE_OPTION_KEYS[context.stage ?? ""] ?? [], prefix, `${context.stage} option`, 100);
break;
case "methodOption":
- items = specItems(METHOD_OPTION_KEYS[context.method ?? ""] ?? [], prefix, `${context.method}() option`, 100);
+ items = specItems(METHOD_OPTION_KEYS[context.method ?? ""] ?? [], prefix, context.method === "runCommand" ? "command" : `${context.method}() option`, 100);
break;
case "bulkWriteOperation":
items = specItems(BULK_WRITE_OPERATIONS, prefix, "bulkWrite operation", 100);
@@ -728,7 +735,7 @@ function classifyCursorInCall(method: string, scan: MongoCallScan): MongoCursorC
case "filter":
return classifyFilter(scan, 0);
case "update":
- return classifyUpdate(scan, 0);
+ return classifyUpdateArgument(scan, 0);
case "replacement":
case "document":
return { mode: classifyDocument(scan, 0) };
@@ -865,6 +872,11 @@ function classifyJsonSchema(scan: MongoCallScan, schemaIndex: number): MongoCurs
return { mode: "none" };
}
+/** An update argument is a document of update operators, or a pipeline of the stages an update accepts. */
+function classifyUpdateArgument(scan: MongoCallScan, rootIndex: number): MongoCursorClass {
+ return scan.stack[rootIndex]?.kind === "array" ? classifyPipeline(scan, rootIndex, "update") : classifyUpdate(scan, rootIndex);
+}
+
function classifyUpdate(scan: MongoCallScan, rootIndex: number): MongoCursorClass {
const inner = innermost(scan);
if (!inner || innerDepth(scan, rootIndex) < 0) return { mode: "none" };
@@ -904,7 +916,23 @@ function classifyKeyMap(scan: MongoCallScan, rootIndex: number, keyMap: string):
const FIELD_MAP_OPTION_KEYS = new Set(["sort", "projection"]);
/** Option keys whose value is a fixed set of strings. */
-const OPTION_VALUE_ENUMS: Record<string, string> = { returnDocument: "returnDocument" };
+const OPTION_VALUE_ENUMS: Record<string, string> = { returnDocument: "returnDocument", validationLevel: "validationLevel", validationAction: "validationAction" };
+
+/** Option keys, by method, whose string value names a collection. */
+const OPTION_COLLECTION_KEYS: Record<string, ReadonlySet<string>> = {
+ createCollection: new Set(["viewOn"]),
+ runCommand: new Set(["collStats", "listIndexes", "find", "count", "distinct", "aggregate", "insert", "update", "delete", "findAndModify", "create", "drop", "collMod", "convertToCapped", "createIndexes", "dropIndexes", "validate"]),
+};
+
+/** Option keys whose value is a filter document. */
+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. */
+const SUB_DOCUMENT_OPTION_KEYS: Record<string, Record<string, string>> = {
+ collation: { caseFirst: "caseFirst", alternate: "alternate", maxVariable: "maxVariable", strength: "strength" },
+ timeseries: { granularity: "granularity" },
+ clusteredIndex: {},
+};
function classifyMethodOptions(method: string, scan: MongoCallScan): MongoCursorClass {
const inner = innermost(scan);
@@ -914,7 +942,9 @@ function classifyMethodOptions(method: string, scan: MongoCallScan): MongoCursor
if (depth === 0) {
if (scan.inValue) {
const enumKey = OPTION_VALUE_ENUMS[scan.valueKey ?? ""];
- return enumKey ? { mode: "enumValue", enumKey, method } : { mode: "none" };
+ if (enumKey) return { mode: "enumValue", enumKey, method };
+ if (OPTION_COLLECTION_KEYS[method]?.has(scan.valueKey ?? "")) return { mode: "collectionRef", method };
+ return { mode: "none" };
}
return { mode: inner.kind === "object" ? "methodOption" : "none", method };
}
@@ -926,23 +956,27 @@ function classifyMethodOptions(method: string, scan: MongoCallScan): MongoCursor
if (!scan.inValue) return { mode: "field", method };
return { mode: scan.inString ? "none" : "keyMapValue", method, keyMap: option };
}
- if (option === "partialFilterExpression") return { ...classifyFilter(scan, 1), method };
- if (option === "collation") return { ...classifyCollation(scan, 1), method };
+ if (FILTER_OPTION_KEYS.has(option)) return { ...classifyFilter(scan, 1), method };
+ if (option === "pipeline" && scan.stack[1]?.kind === "array") return { ...classifyPipeline(scan, 1), method };
+ const valueEnums = SUB_DOCUMENT_OPTION_KEYS[option];
+ if (valueEnums) return { ...classifySubDocument(scan, 1, option, valueEnums), method };
return { mode: "none" };
}
-/** Collation option values with a fixed set. */
-const COLLATION_VALUE_ENUMS: Record<string, string> = { caseFirst: "caseFirst", alternate: "alternate", maxVariable: "maxVariable", strength: "strength" };
-
/** The collation document, as the `collation` option or the `collation()` cursor method. */
function classifyCollation(scan: MongoCallScan, rootIndex: number): MongoCursorClass {
+ return classifySubDocument(scan, rootIndex, "collation", SUB_DOCUMENT_OPTION_KEYS.collation ?? {});
+}
+
+/** A one-level document with a fixed key set (`OPERATOR_SUB_KEYS[operator]`) and, for some keys, a fixed value set. */
+function classifySubDocument(scan: MongoCallScan, rootIndex: number, operator: string, valueEnums: Record<string, string>): MongoCursorClass {
const inner = innermost(scan);
if (!inner || inner.kind !== "object" || innerDepth(scan, rootIndex) !== 0) return { mode: "none" };
if (scan.inValue) {
- const enumKey = COLLATION_VALUE_ENUMS[scan.valueKey ?? ""];
+ const enumKey = valueEnums[scan.valueKey ?? ""];
return enumKey ? { mode: "enumValue", enumKey } : { mode: "none" };
}
- return { mode: "operatorField", operator: "collation" };
+ return { mode: "operatorField", operator };
}
/**
@@ -979,7 +1013,7 @@ function classifyBulkWriteOperations(scan: MongoCallScan): MongoCursorClass {
case "arrayFilters":
return { ...classifyFilter(scan, fieldIndex + 1), bulkWriteOperation: operation };
case "update":
- return { ...classifyUpdate(scan, fieldIndex), bulkWriteOperation: operation };
+ return { ...classifyUpdateArgument(scan, fieldIndex), bulkWriteOperation: operation };
case "document":
case "replacement":
return { mode: classifyDocument(scan, fieldIndex), bulkWriteOperation: operation };
@@ -988,8 +1022,12 @@ function classifyBulkWriteOperations(scan: MongoCallScan): MongoCursorClass {
}
}
-function classifyPipeline(scan: MongoCallScan): MongoCursorClass {
- const pipelineIndex = findPipelineArrayIndex(scan.stack);
+/**
+ * `kind` is `update` for the pipeline form of an update, which accepts only the
+ * stages that rewrite a document; the marker rides in `stage` so the item builder
+ * can narrow the list.
+ */
+function classifyPipeline(scan: MongoCallScan, pipelineIndex = findPipelineArrayIndex(scan.stack), kind: "aggregate" | "update" = "aggregate"): MongoCursorClass {
if (pipelineIndex < 0) return { mode: "none" };
const stageHolder = scan.stack[pipelineIndex + 1];
@@ -998,7 +1036,7 @@ function classifyPipeline(scan: MongoCallScan): MongoCursorClass {
// `[{ … }]` — the cursor is in the stage object itself.
if (scan.stack.length - 1 === pipelineIndex + 1) {
- if (!scan.inValue) return { mode: "stage" };
+ if (!scan.inValue) return { mode: "stage", stage: kind === "update" ? "update" : undefined };
const stage = scan.valueKey ?? "";
return { mode: stageStringValueMode(stage), stage };
}
diff --git a/apps/desktop/src/lib/mongo/mongoCompletionTables.ts b/apps/desktop/src/lib/mongo/mongoCompletionTables.ts
index bccc335867..7aa2f12d46 100644
--- a/apps/desktop/src/lib/mongo/mongoCompletionTables.ts
+++ b/apps/desktop/src/lib/mongo/mongoCompletionTables.ts
@@ -393,6 +393,18 @@ export const OPERATOR_SUB_KEYS: Record<string, MongoOperatorSpec[]> = {
]),
$jsonSchema: specs(JSON_SCHEMA_KEYWORDS),
$currentDate: specs([["$type", "Store a Date or a Timestamp", '$type: "${date}"']]),
+ timeseries: specs([
+ ["timeField", "Field holding each measurement's time", 'timeField: "${timestamp}"'],
+ ["metaField", "Field holding the series metadata", 'metaField: "${meta}"'],
+ ["granularity", "Expected spacing between measurements", 'granularity: "${seconds}"'],
+ ["bucketMaxSpanSeconds", "Maximum time span of one bucket", "bucketMaxSpanSeconds: ${}"],
+ ["bucketRoundingSeconds", "Rounding of bucket boundaries", "bucketRoundingSeconds: ${}"],
+ ]),
+ clusteredIndex: specs([
+ ["key", "Clustered key, which must be _id", "key: { _id: 1 }"],
+ ["unique", "Required, and must be true", "unique: true"],
+ ["name", "Index name", 'name: "${name}"'],
+ ]),
collation: specs([
["locale", 'ICU locale, such as "en" or "zh"', 'locale: "${en}"'],
["strength", "Comparison level, 1 (base letters) to 5 (identical)", "strength: 2"],
@@ -477,6 +489,20 @@ export const ENUM_VALUES: Record<string, MongoOperatorSpec[]> = {
["punct", "Shift both spaces and punctuation", '"punct"'],
["space", "Shift spaces only", '"space"'],
]),
+ validationLevel: specs([
+ ["strict", "Validate every insert and update", '"strict"'],
+ ["moderate", "Validate inserts, and updates to documents that already validate", '"moderate"'],
+ ["off", "Do not validate", '"off"'],
+ ]),
+ validationAction: specs([
+ ["error", "Reject documents that fail validation", '"error"'],
+ ["warn", "Accept them and log a warning", '"warn"'],
+ ]),
+ granularity: specs([
+ ["seconds", "Measurements seconds apart", '"seconds"'],
+ ["minutes", "Measurements minutes apart", '"minutes"'],
+ ["hours", "Measurements hours apart", '"hours"'],
+ ]),
strength: specs([
["1", "Base letters only", "1"],
["2", "Base letters and accents", "2"],
@@ -569,6 +595,54 @@ export const METHOD_OPTION_KEYS: Record<string, MongoOperatorSpec[]> = {
["let", "Variables available to the pipeline as $$name", "let: { ${name}: ${} }"],
["explain", "Return the query plan instead of the results", "explain: true"],
]),
+ createCollection: specs([
+ ["validator", "Rules every document must satisfy", 'validator: { $jsonSchema: { bsonType: "object", required: ["${field}"], properties: {} } }'],
+ ["validationLevel", "How strictly to validate existing documents", 'validationLevel: "${strict}"'],
+ ["validationAction", "Reject or only warn on invalid documents", 'validationAction: "${error}"'],
+ ["capped", "Fixed-size collection that overwrites its oldest documents", "capped: true"],
+ ["size", "Maximum size of a capped collection, in bytes", "size: ${}"],
+ ["max", "Maximum number of documents in a capped collection", "max: ${}"],
+ ["timeseries", "Store measurements as a time series", 'timeseries: { timeField: "${timestamp}", metaField: "${meta}", granularity: "${seconds}" }'],
+ ["expireAfterSeconds", "Delete time-series documents after this age", "expireAfterSeconds: ${}"],
+ ["clusteredIndex", "Cluster the documents by _id", "clusteredIndex: { key: { _id: 1 }, unique: true }"],
+ ["collation", "Default locale-aware comparison rules", 'collation: { locale: "${en}" }'],
+ ["viewOn", "Make this a view over another collection", 'viewOn: "${collection}"'],
+ ["pipeline", "Aggregation pipeline the view applies", "pipeline: [${}]"],
+ ["changeStreamPreAndPostImages", "Record document images for change streams", "changeStreamPreAndPostImages: { enabled: true }"],
+ ]),
+ // Command documents run as written, so this lists the commands worth typing by hand.
+ runCommand: specs([
+ ["ping", "Check that the server responds", "ping: 1"],
+ ["hello", "Server role and replica set state", "hello: 1"],
+ ["buildInfo", "Server version and build details", "buildInfo: 1"],
+ ["serverStatus", "Server metrics", "serverStatus: 1"],
+ ["hostInfo", "Host system details", "hostInfo: 1"],
+ ["connectionStatus", "Authenticated user and roles", "connectionStatus: 1"],
+ ["dbStats", "Database storage statistics", "dbStats: 1"],
+ ["collStats", "Collection storage statistics", 'collStats: "${collection}"'],
+ ["listCollections", "Collections in this database", "listCollections: 1"],
+ ["listIndexes", "Indexes of a collection", 'listIndexes: "${collection}"'],
+ ["find", "Query a collection", 'find: "${collection}", filter: {}'],
+ ["count", "Count matching documents", 'count: "${collection}", query: {}'],
+ ["distinct", "Distinct values of a field", 'distinct: "${collection}", key: "${field}"'],
+ ["aggregate", "Run an aggregation pipeline", 'aggregate: "${collection}", pipeline: [], cursor: {}'],
+ ["explain", "Query plan for a command", 'explain: { find: "${collection}", filter: {} }'],
+ ["insert", "Insert documents", 'insert: "${collection}", documents: [{}]'],
+ ["update", "Update documents", 'update: "${collection}", updates: [{ q: {}, u: { $set: {} } }]'],
+ ["delete", "Delete documents", 'delete: "${collection}", deletes: [{ q: {}, limit: 1 }]'],
+ ["findAndModify", "Atomically modify and return one document", 'findAndModify: "${collection}", query: {}, update: { $set: {} }'],
+ ["create", "Create a collection", 'create: "${collection}"'],
+ ["drop", "Drop a collection", 'drop: "${collection}"'],
+ ["collMod", "Change a collection's options", 'collMod: "${collection}", validator: {}'],
+ ["convertToCapped", "Convert a collection to a capped one", 'convertToCapped: "${collection}", size: ${}'],
+ ["createIndexes", "Create indexes", 'createIndexes: "${collection}", indexes: [{ key: { ${field}: 1 }, name: "${name}" }]'],
+ ["dropIndexes", "Drop an index", 'dropIndexes: "${collection}", index: "${name}"'],
+ ["validate", "Check a collection's data and indexes", 'validate: "${collection}"'],
+ ["currentOp", "Operations in progress", "currentOp: 1"],
+ ["usersInfo", "Users of this database", "usersInfo: 1"],
+ ["profile", "Read the profiling level", "profile: -1"],
+ ["getLog", "Recent server log lines", 'getLog: "global"'],
+ ]),
};
/** Option keys accepted by the stages whose shape is a fixed set of names. */
diff --git a/packages/app-tests/mongoCompletion.test.ts b/packages/app-tests/mongoCompletion.test.ts
index a6104550c2..20c364bd62 100644
--- a/packages/app-tests/mongoCompletion.test.ts
+++ b/packages/app-tests/mongoCompletion.test.ts
@@ -578,6 +578,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
const args = callArgs[method];
assert.ok(args !== undefined, `${method} needs sample arguments in this test`);
for (const option of options) {
@@ -637,8 +638,7 @@ test("offers nothing rather than top-level snippets inside an unmodelled argumen
"db.users.renameCollection(",
'db.users.dropIndex("',
"db.users.estimatedDocumentCount(",
- "db.runCommand({ ",
- 'db.createCollection("x", { ',
+ 'db.createCollection("',
]) {
assert.deepEqual(labels(text, { fields, collections }), [], text);
}
@@ -898,6 +898,8 @@ test("every suggested sub-document key and enumerated value parses in the positi
$jsonSchema: (body) => `db.users.find({ $jsonSchema: { ${body} } })`,
$currentDate: (body) => `db.users.updateOne({}, { $currentDate: { at: { ${body} } } })`,
collation: (body) => `db.users.find({}).collation({ ${body} })`,
+ timeseries: (body) => `db.createCollection("x", { timeseries: { ${body} } })`,
+ clusteredIndex: (body) => `db.createCollection("x", { clusteredIndex: { ${body} } })`,
};
for (const [operator, keys] of Object.entries(OPERATOR_SUB_KEYS)) {
const build = keyCommands[operator];
@@ -920,6 +922,9 @@ test("every suggested sub-document key and enumerated value parses in the positi
alternate: (value) => `db.users.find({}).collation({ locale: "en", alternate: ${value} })`,
maxVariable: (value) => `db.users.find({}).collation({ locale: "en", maxVariable: ${value} })`,
strength: (value) => `db.users.find({}).collation({ locale: "en", strength: ${value} })`,
+ validationLevel: (value) => `db.createCollection("x", { validationLevel: ${value} })`,
+ validationAction: (value) => `db.createCollection("x", { validationAction: ${value} })`,
+ granularity: (value) => `db.createCollection("x", { timeseries: { timeField: "t", granularity: ${value} } })`,
};
for (const [enumKey, values] of Object.entries(ENUM_VALUES)) {
const build = valueCommands[enumKey];
@@ -931,6 +936,67 @@ test("every suggested sub-document key and enumerated value parses in the positi
}
});
+test("completes the pipeline form of an update", () => {
+ const stages = labels("db.users.updateOne({}, [{ $", { fields });
+ assert.deepEqual([...stages].sort(), ["$addFields", "$project", "$replaceRoot", "$replaceWith", "$set", "$unset"]);
+ assert.deepEqual(labels("db.users.updateMany({}, [{ $set: { a: 1 } }, { $", { fields }), stages);
+ assert.deepEqual(labels("db.users.findOneAndUpdate({}, [{ $", { fields }), stages);
+ assert.deepEqual(labels("db.users.bulkWrite([{ updateOne: { filter: {}, update: [{ $", { fields }), stages);
+ // Inside a stage the shapes are the aggregation ones.
+ assert.deepEqual(labels("db.users.updateOne({}, [{ $set: { ", { fields }), ["_id", "createdAt", "name", "profile.email"]);
+ assert.ok(labels("db.users.updateOne({}, [{ $set: { total: { $", { fields }).includes("$add"));
+ assert.deepEqual(labels('db.users.updateOne({}, [{ $unset: "', { fields }), ["_id", "createdAt", "name", "profile.email"]);
+ assert.ok(labels('db.users.updateOne({}, [{ $replaceWith: "$', { fields }).includes("$name"));
+ // The document form is untouched, the array itself waits for a stage object, and the options still follow.
+ assert.ok(labels("db.users.updateOne({}, { $", { fields }).includes("$inc"));
+ assert.deepEqual(labels("db.users.updateOne({}, [", { fields }), []);
+ assert.deepEqual(labels("db.users.updateOne({}, [{ $set: {} }], { ", { fields }), ["arrayFilters", "upsert"]);
+});
+
+test("completes createCollection options and the documents inside them", () => {
+ const keys = labels('db.createCollection("events", { ');
+ for (const key of ["validator", "validationLevel", "capped", "size", "timeseries", "clusteredIndex", "collation", "viewOn", "pipeline"]) assert.ok(keys.includes(key), key);
+ // The validator is a filter, so the schema completes inside it.
+ assert.ok(labels('db.createCollection("events", { validator: { ', { fields }).includes("$jsonSchema"));
+ assert.ok(labels('db.createCollection("events", { validator: { $jsonSchema: { ').includes("required"));
+ assert.ok(labels('db.createCollection("events", { validator: { $jsonSchema: { properties: { name: { bsonType: "').includes("string"));
+ assert.deepEqual(labels('db.createCollection("events", { validationLevel: "'), ["strict", "moderate", "off"]);
+ assert.deepEqual(labels('db.createCollection("events", { validationAction: "'), ["error", "warn"]);
+ assert.deepEqual(labels('db.createCollection("events", { timeseries: { '), ["bucketMaxSpanSeconds", "bucketRoundingSeconds", "granularity", "metaField", "timeField"]);
+ assert.deepEqual(labels('db.createCollection("events", { timeseries: { granularity: "'), ["seconds", "minutes", "hours"]);
+ assert.deepEqual(labels('db.createCollection("events", { clusteredIndex: { '), ["key", "name", "unique"]);
+ assert.ok(labels('db.createCollection("events", { collation: { ').includes("locale"));
+ assert.deepEqual(labels('db.createCollection("v", { viewOn: "', { collections }), collections);
+ assert.ok(labels('db.createCollection("v", { viewOn: "users", pipeline: [{ $').includes("$match"));
+ assert.ok(labels('db.createCollection("v", { pipeline: [{ $match: { ', { fields }).includes("name"));
+ // The name argument is the user's own.
+ assert.deepEqual(labels('db.createCollection("'), []);
+});
+
+test("completes runCommand command names and their collection arguments", () => {
+ const commands = labels("db.runCommand({ ");
+ for (const command of ["ping", "hello", "serverStatus", "dbStats", "collStats", "find", "aggregate", "listCollections", "createIndexes"]) assert.ok(commands.includes(command), command);
+ assert.deepEqual(labels("db.runCommand({ collSt"), ["collStats"]);
+ assert.deepEqual(labels('db.runCommand({ collStats: "', { collections }), collections);
+ assert.deepEqual(labels('db.runCommand({ find: "us', { collections }), ["users", "user_events"]);
+ assert.deepEqual(labels('db.runCommand({ ping: "', { collections }), []);
+ // A second key still completes commands, and `db.` offers the helper.
+ assert.ok(labels('db.runCommand({ find: "users", ').includes("find"));
+ assert.ok(labels("db.").includes("runCommand"));
+});
+
+test("every suggested createCollection 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)} })`;
+ assert.ok(parseMongoCommand(command), `${command} must parse`);
+ }
+ for (const spec of METHOD_OPTION_KEYS.runCommand ?? []) {
+ const command = `db.runCommand({ ${render(spec.apply)} })`;
+ assert.ok(parseMongoCommand(command), `${command} must parse`);
+ }
+});
+
test("suggests the use and db.version commands", () => {
assert.equal(buildMongoCompletionItems("us", 2).find((item) => item.label === "use")?.apply, "use ${database}");
// Database helpers stay reachable after `db.`, alongside the collection names.