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 bulkWrite operations in completions

Loc Nguyen6ee12ab0a5c6
diff --git a/apps/desktop/src/lib/mongo/mongoCompletion.ts b/apps/desktop/src/lib/mongo/mongoCompletion.ts
index 110d11156d..f61e588083 100644
--- a/apps/desktop/src/lib/mongo/mongoCompletion.ts
+++ b/apps/desktop/src/lib/mongo/mongoCompletion.ts
@@ -7,6 +7,8 @@ import {
FIELD_QUERY_OPERATORS,
PIPELINE_STAGES,
PUSH_MODIFIERS,
+ BULK_WRITE_OPERATION_FIELDS,
+ BULK_WRITE_OPERATIONS,
METHOD_OPTION_KEYS,
STAGE_OPTION_KEYS,
TOP_LEVEL_QUERY_OPERATORS,
@@ -48,7 +50,9 @@ export type MongoCompletionMode =
| "accumulator"
| "stage"
| "stageOption"
- | "methodOption";
+ | "methodOption"
+ | "bulkWriteOperation"
+ | "bulkWriteField";
export interface MongoCompletionField {
name: string;
@@ -78,6 +82,8 @@ export interface MongoCompletionContext {
stage?: string;
/** Collection method whose options object the cursor sits in. */
method?: string;
+ /** bulkWrite operation (`updateOne`, `deleteMany`, …) whose body the cursor sits in. */
+ bulkWriteOperation?: string;
}
export interface MongoCompletionInput {
@@ -253,7 +259,7 @@ export function getMongoCompletionContext(text: string, cursor: number): MongoCo
const collection = extractActiveCollection(text, safeCursor);
const { prefix, from } = readMongoPropertyPrefix(text, safeCursor);
const replaceClosingQuote = closingQuoteAtCursor(prefix, text, safeCursor);
- const at = (mode: MongoCompletionMode, stage?: string, method?: string): MongoCompletionContext => ({ mode, prefix, from, replaceClosingQuote, collection, stage, method });
+ const at = (mode: MongoCompletionMode, stage?: string, method?: string, bulkWriteOperation?: string): MongoCompletionContext => ({ mode, prefix, from, replaceClosingQuote, collection, stage, method, bulkWriteOperation });
if (isInsideMongoComment(text, safeCursor)) return { mode: "none", prefix: "", from: safeCursor };
@@ -298,7 +304,10 @@ export function getMongoCompletionContext(text: string, cursor: number): MongoCo
if (!scan) return at("root");
const classified = classifyCursorInCall(call.method, scan);
- return { ...at(classified.mode, classified.stage, classified.method), collection: classified.collection ?? collection };
+ return {
+ ...at(classified.mode, classified.stage, classified.method, classified.bulkWriteOperation),
+ collection: classified.collection ?? collection,
+ };
}
export function buildMongoCompletionItems(text: string, cursor: number, input: MongoCompletionInput = {}): MongoCompletionItem[] {
@@ -378,6 +387,12 @@ export function buildMongoCompletionItemsFromContext(context: MongoCompletionCon
case "methodOption":
items = specItems(METHOD_OPTION_KEYS[context.method ?? ""] ?? [], prefix, `${context.method}() option`, 100);
break;
+ case "bulkWriteOperation":
+ items = specItems(BULK_WRITE_OPERATIONS, prefix, "bulkWrite operation", 100);
+ break;
+ case "bulkWriteField":
+ items = specItems(BULK_WRITE_OPERATION_FIELDS[context.bulkWriteOperation ?? ""] ?? [], prefix, `${context.bulkWriteOperation} field`, 100);
+ break;
default:
items = [];
}
@@ -555,6 +570,7 @@ interface MongoCursorClass {
stage?: string;
collection?: string;
method?: string;
+ bulkWriteOperation?: string;
}
/**
@@ -655,9 +671,8 @@ function classifyCursorInCall(method: string, scan: MongoCallScan): MongoCursorC
return { mode: scan.stack.length === 0 ? "fieldPath" : "none" };
case "pipeline":
return classifyPipeline(scan);
- // bulkWrite operations are `{ <op>: { filter, update, … } }` entries; completing inside them is a follow-up.
case "operations":
- return { mode: "none" };
+ return classifyBulkWriteOperations(scan);
case "options":
return classifyMethodOptions(method, scan);
default:
@@ -745,6 +760,49 @@ function classifyMethodOptions(method: string, scan: MongoCallScan): MongoCursor
return { mode: inner.kind === "object" ? "methodOption" : "none", method };
}
+/**
+ * `bulkWrite([{ <operation>: { <field>: … } }])`, which nests one level deeper than the other
+ * arguments: the array holds operation wrappers, each wrapper holds exactly one operation whose
+ * body carries the fields, and those fields are ordinary filters, updates and documents.
+ */
+function classifyBulkWriteOperations(scan: MongoCallScan): MongoCursorClass {
+ const arrayIndex = scan.stack.findIndex((container) => container.kind === "array");
+ if (arrayIndex !== 0) return { mode: "none" };
+
+ const wrapper = scan.stack[arrayIndex + 1];
+ if (!wrapper || wrapper.kind !== "object") return { mode: "none" };
+
+ // `[{ … }]` — naming the operation.
+ if (scan.stack.length - 1 === arrayIndex + 1) {
+ return { mode: scan.inValue ? "none" : "bulkWriteOperation" };
+ }
+
+ const operation = scan.stack[arrayIndex + 2]?.key ?? "";
+ const fields = BULK_WRITE_OPERATION_FIELDS[operation];
+ if (!fields) return { mode: "none" };
+
+ // `[{ updateOne: { … } }]` — naming a field of the operation.
+ if (scan.stack.length - 1 === arrayIndex + 2) {
+ return { mode: scan.inValue ? "value" : "bulkWriteField", bulkWriteOperation: operation };
+ }
+
+ // Inside a field's value, where the shapes are the ordinary ones.
+ const fieldIndex = arrayIndex + 3;
+ switch (scan.stack[fieldIndex]?.key ?? "") {
+ case "filter":
+ return { mode: classifyFilter(scan, fieldIndex), bulkWriteOperation: operation };
+ case "arrayFilters":
+ return { mode: classifyFilter(scan, fieldIndex + 1), bulkWriteOperation: operation };
+ case "update":
+ return { mode: classifyUpdate(scan, fieldIndex), bulkWriteOperation: operation };
+ case "document":
+ case "replacement":
+ return { mode: classifyDocument(scan, fieldIndex), bulkWriteOperation: operation };
+ default:
+ return { mode: "none" };
+ }
+}
+
function classifyPipeline(scan: MongoCallScan): MongoCursorClass {
const pipelineIndex = findPipelineArrayIndex(scan.stack);
if (pipelineIndex < 0) return { mode: "none" };
diff --git a/apps/desktop/src/lib/mongo/mongoCompletionTables.ts b/apps/desktop/src/lib/mongo/mongoCompletionTables.ts
index c6f03610ac..5a7138901d 100644
--- a/apps/desktop/src/lib/mongo/mongoCompletionTables.ts
+++ b/apps/desktop/src/lib/mongo/mongoCompletionTables.ts
@@ -294,6 +294,33 @@ export const EXPRESSION_OPERATORS: MongoOperatorSpec[] = specs([
["$rand", "Returns a random float between 0 and 1", "$rand: {}"],
]);
+/**
+ * The operations a `bulkWrite()` array accepts, and the fields each one allows.
+ *
+ * Both lists are exactly what the shell parser accepts: it rejects an unknown operation key and
+ * an unknown field inside one, so anything extra here would complete into a command that fails.
+ */
+export const BULK_WRITE_OPERATIONS: MongoOperatorSpec[] = specs([
+ ["insertOne", "Insert one document", "insertOne: { document: { ${} } }"],
+ ["updateOne", "Update the first matching document", "updateOne: { filter: { ${} }, update: { $set: { ${} } } }"],
+ ["updateMany", "Update every matching document", "updateMany: { filter: { ${} }, update: { $set: { ${} } } }"],
+ ["replaceOne", "Replace the first matching document", "replaceOne: { filter: { ${} }, replacement: { ${} } }"],
+ ["deleteOne", "Delete the first matching document", "deleteOne: { filter: { ${} } }"],
+ ["deleteMany", "Delete every matching document", "deleteMany: { filter: { ${} } }"],
+]);
+
+const BULK_WRITE_FILTER: Spec = ["filter", "Documents the operation applies to", "filter: { ${} }"];
+const BULK_WRITE_UPSERT: Spec = ["upsert", "Insert the document when the filter matches nothing", "upsert: true"];
+
+export const BULK_WRITE_OPERATION_FIELDS: Record<string, MongoOperatorSpec[]> = {
+ insertOne: specs([["document", "Document to insert", "document: { ${} }"]]),
+ updateOne: specs([BULK_WRITE_FILTER, ["update", "Update operators or an aggregation pipeline", "update: { $set: { ${} } }"], BULK_WRITE_UPSERT, ["arrayFilters", "Conditions for the $[<identifier>] positional operator", 'arrayFilters: [{ "${elem}.${field}": ${} }]']]),
+ updateMany: specs([BULK_WRITE_FILTER, ["update", "Update operators or an aggregation pipeline", "update: { $set: { ${} } }"], BULK_WRITE_UPSERT, ["arrayFilters", "Conditions for the $[<identifier>] positional operator", 'arrayFilters: [{ "${elem}.${field}": ${} }]']]),
+ replaceOne: specs([BULK_WRITE_FILTER, ["replacement", "Whole document that replaces the match", "replacement: { ${} }"], BULK_WRITE_UPSERT]),
+ deleteOne: specs([BULK_WRITE_FILTER]),
+ deleteMany: specs([BULK_WRITE_FILTER]),
+};
+
/**
* Option keys accepted by a collection method's trailing options argument.
*
diff --git a/packages/app-tests/mongoCompletion.test.ts b/packages/app-tests/mongoCompletion.test.ts
index 4ff9cd3b9e..c3c37a2e3e 100644
--- a/packages/app-tests/mongoCompletion.test.ts
+++ b/packages/app-tests/mongoCompletion.test.ts
@@ -1,7 +1,7 @@
import { strict as assert } from "node:assert";
import { test } from "vitest";
import { buildMongoCompletionItems, getMongoCompletionContext, getMongoCompletionResultValidFor, inferMongoCompletionFields, shouldAutoOpenMongoCompletion } from "../../apps/desktop/src/lib/mongo/mongoCompletion.ts";
-import { ACCUMULATORS, EXPRESSION_OPERATORS, EXTENDED_JSON_VALUES, METHOD_OPTION_KEYS, PIPELINE_STAGES, PUSH_MODIFIERS, QUERY_OPERATORS, STAGE_OPTION_KEYS, UPDATE_OPERATORS, VALUE_SNIPPETS } from "../../apps/desktop/src/lib/mongo/mongoCompletionTables.ts";
+import { ACCUMULATORS, BULK_WRITE_OPERATION_FIELDS, BULK_WRITE_OPERATIONS, EXPRESSION_OPERATORS, EXTENDED_JSON_VALUES, METHOD_OPTION_KEYS, PIPELINE_STAGES, PUSH_MODIFIERS, QUERY_OPERATORS, STAGE_OPTION_KEYS, UPDATE_OPERATORS, VALUE_SNIPPETS } from "../../apps/desktop/src/lib/mongo/mongoCompletionTables.ts";
import { parseMongoCommand } from "../../apps/desktop/src/lib/mongo/mongoShellCommand.ts";
const collections = ["users", "user_events", "order-items", "audit.logs"];
@@ -493,8 +493,8 @@ test("stays quiet inside string values, comments and unmodelled arguments", () =
assert.deepEqual(labels('db.users.find({ name: "Ad', { fields }), []);
assert.deepEqual(labels("// db.users.fi", { fields }), []);
assert.deepEqual(labels('db.users.find({ _id: ObjectId("6a04', { fields }), []);
- // bulkWrite operation entries are still unmodelled; its options argument is not.
- assert.deepEqual(labels("db.users.bulkWrite([{ insertOne: { do", { fields }), []);
+ // An operation name bulkWrite() does not accept has no fields to offer.
+ assert.deepEqual(labels("db.users.bulkWrite([{ mapReduceOne: { ", { fields }), []);
});
test("suggests only helpers the shell parser accepts", () => {
@@ -589,6 +589,61 @@ test("every suggested option key parses on the method that offers it", () => {
}
});
+test("completes bulkWrite operations, their fields, and the shapes inside them", () => {
+ assert.deepEqual(labels("db.users.bulkWrite([{ "), ["deleteMany", "deleteOne", "insertOne", "replaceOne", "updateMany", "updateOne"]);
+ assert.deepEqual(labels("db.users.bulkWrite([{ upd"), ["updateMany", "updateOne"]);
+
+ assert.deepEqual(labels("db.users.bulkWrite([{ insertOne: { "), ["document"]);
+ assert.deepEqual(labels("db.users.bulkWrite([{ deleteMany: { "), ["filter"]);
+ assert.deepEqual(labels("db.users.bulkWrite([{ replaceOne: { "), ["filter", "replacement", "upsert"]);
+ assert.deepEqual(labels("db.users.bulkWrite([{ updateOne: { "), ["arrayFilters", "filter", "update", "upsert"]);
+
+ // Inside a field the shapes are the ordinary ones.
+ assert.ok(labels("db.users.bulkWrite([{ updateOne: { filter: { ", { fields }).includes("$or"));
+ assert.deepEqual(labels("db.users.bulkWrite([{ updateOne: { filter: { na", { fields }), ["name"]);
+ assert.ok(labels("db.users.bulkWrite([{ updateOne: { filter: { age: { $g", { fields }).includes("$gte"));
+ assert.ok(labels("db.users.bulkWrite([{ updateOne: { update: { $s", { fields }).includes("$set"));
+ assert.deepEqual(labels("db.users.bulkWrite([{ updateOne: { update: { $set: { na", { fields }), ["name"]);
+ assert.deepEqual(labels("db.users.bulkWrite([{ insertOne: { document: { na", { fields }), ["name"]);
+ assert.deepEqual(labels("db.users.bulkWrite([{ replaceOne: { replacement: { na", { fields }), ["name"]);
+ assert.deepEqual(labels("db.users.bulkWrite([{ updateOne: { arrayFilters: [{ na", { fields }), ["name"]);
+
+ // An operation the parser does not accept has nothing to offer.
+ assert.deepEqual(labels("db.users.bulkWrite([{ notAnOperation: { ", { fields }), []);
+});
+
+test("every suggested bulkWrite operation and field parses", () => {
+ // The parser rejects an unknown operation key and an unknown field inside one, so a suggestion
+ // that only exists in the table would complete into a command that fails at Run.
+ const fieldValues: Record<string, string> = {
+ document: "{ a: 1 }",
+ filter: "{ a: 1 }",
+ update: "{ $set: { b: 2 } }",
+ replacement: "{ b: 2 }",
+ upsert: "true",
+ arrayFilters: '[{ "e.f": 1 }]',
+ };
+
+ assert.deepEqual(
+ BULK_WRITE_OPERATIONS.map((operation) => operation.label).sort(),
+ Object.keys(BULK_WRITE_OPERATION_FIELDS).sort(),
+ "every offered operation needs a field list, and vice versa",
+ );
+
+ for (const [operation, fieldSpecs] of Object.entries(BULK_WRITE_OPERATION_FIELDS)) {
+ // Every field of an operation at once, so each one is exercised against the parser.
+ const body = fieldSpecs
+ .map((field) => {
+ const value = fieldValues[field.label];
+ assert.ok(value !== undefined, `${field.label} needs a sample value in this test`);
+ return `${field.label}: ${value}`;
+ })
+ .join(", ");
+ const command = `db.users.bulkWrite([{ ${operation}: { ${body} } }])`;
+ assert.ok(parseMongoCommand(command), `${command} must parse`);
+ }
+});
+
test("completes both arguments of distinct", () => {
const method = buildMongoCompletionItems("db.users.dist", "db.users.dist".length).find((item) => item.label === "distinct");
assert.equal(method?.apply, 'users.distinct("${field}")');