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): suggest accepted values for field-to-value maps

Loc Nguyend1446360cc38
diff --git a/apps/desktop/src/lib/mongo/__tests__/mongoDocumentQueryCompletion.spec.ts b/apps/desktop/src/lib/mongo/__tests__/mongoDocumentQueryCompletion.spec.ts
index 270f6c4174..6f6f34786a 100644
--- a/apps/desktop/src/lib/mongo/__tests__/mongoDocumentQueryCompletion.spec.ts
+++ b/apps/desktop/src/lib/mongo/__tests__/mongoDocumentQueryCompletion.spec.ts
@@ -84,7 +84,9 @@ describe("getMongoDocumentQueryCompletionContext", () => {
it("completes sort keys without value or operator noise", () => {
expect(contextAt("{ created", "sortKeys")).toMatchObject({ mode: "field", prefix: "created" });
expect(labelsAt("{ created", "sortKeys")).toEqual(["createdAt"]);
- expect(contextAt("{ createdAt: ", "sortKeys")).toMatchObject({ mode: "none" });
+ // A sort value is one of two directions; the filter bar's values and operators would be noise.
+ expect(contextAt("{ createdAt: ", "sortKeys")).toMatchObject({ mode: "keyMapValue", keyMap: "sort" });
+ expect(labelsAt("{ createdAt: ", "sortKeys")).toEqual(["-1", "1"]);
expect(contextAt("{ createdAt: -1, ", "sortKeys")).toMatchObject({ mode: "field" });
});
});
diff --git a/apps/desktop/src/lib/mongo/mongoCompletion.ts b/apps/desktop/src/lib/mongo/mongoCompletion.ts
index b663657f3c..1ad56d6c5a 100644
--- a/apps/desktop/src/lib/mongo/mongoCompletion.ts
+++ b/apps/desktop/src/lib/mongo/mongoCompletion.ts
@@ -9,6 +9,7 @@ import {
PUSH_MODIFIERS,
BULK_WRITE_OPERATION_FIELDS,
BULK_WRITE_OPERATIONS,
+ KEY_MAP_VALUES,
METHOD_OPTION_KEYS,
STAGE_OPTION_KEYS,
TOP_LEVEL_QUERY_OPERATORS,
@@ -52,7 +53,8 @@ export type MongoCompletionMode =
| "stageOption"
| "methodOption"
| "bulkWriteOperation"
- | "bulkWriteField";
+ | "bulkWriteField"
+ | "keyMapValue";
export interface MongoCompletionField {
name: string;
@@ -86,6 +88,8 @@ export interface MongoCompletionContext {
method?: string;
/** bulkWrite operation (`updateOne`, `deleteMany`, …) whose body the cursor sits in. */
bulkWriteOperation?: string;
+ /** Which field-to-value map the cursor sits in: `sort`, `projection` or `index`. */
+ keyMap?: string;
}
export interface MongoCompletionInput {
@@ -262,7 +266,7 @@ export function getMongoCompletionContext(text: string, cursor: number): MongoCo
const database = extractActiveDatabase(text, safeCursor);
const { prefix, from } = readMongoPropertyPrefix(text, safeCursor);
const replaceClosingQuote = closingQuoteAtCursor(prefix, text, safeCursor);
- const at = (mode: MongoCompletionMode, stage?: string, method?: string, bulkWriteOperation?: string): MongoCompletionContext => ({ mode, prefix, from, replaceClosingQuote, collection, database, stage, method, bulkWriteOperation });
+ const at = (mode: MongoCompletionMode, stage?: string, method?: string, bulkWriteOperation?: string, keyMap?: string): MongoCompletionContext => ({ mode, prefix, from, replaceClosingQuote, collection, database, stage, method, bulkWriteOperation, keyMap });
if (isInsideMongoComment(text, safeCursor)) return { mode: "none", prefix: "", from: safeCursor };
@@ -313,7 +317,7 @@ export function getMongoCompletionContext(text: string, cursor: number): MongoCo
const classified = classifyCursorInCall(call.method, scan);
return {
- ...at(classified.mode, classified.stage, classified.method, classified.bulkWriteOperation),
+ ...at(classified.mode, classified.stage, classified.method, classified.bulkWriteOperation, classified.keyMap),
collection: classified.collection ?? collection,
};
}
@@ -398,6 +402,9 @@ export function buildMongoCompletionItemsFromContext(context: MongoCompletionCon
case "bulkWriteOperation":
items = specItems(BULK_WRITE_OPERATIONS, prefix, "bulkWrite operation", 100);
break;
+ case "keyMapValue":
+ items = specItems(KEY_MAP_VALUES[context.keyMap ?? ""] ?? [], prefix, `${context.keyMap} value`, 100);
+ break;
case "bulkWriteField":
items = specItems(BULK_WRITE_OPERATION_FIELDS[context.bulkWriteOperation ?? ""] ?? [], prefix, `${context.bulkWriteOperation} field`, 100);
break;
@@ -461,11 +468,11 @@ export function getMongoDocumentQueryCompletionContext(text: string, cursor: num
const scan = scanMongoCallArguments(text, 0, safeCursor);
if (!scan) return nothing;
- const mode = kind === "filter" ? classifyFilter(scan, 0) : classifyKeyMap(scan, 0);
- if (mode === "none") return nothing;
+ const classified = kind === "filter" ? { mode: classifyFilter(scan, 0) } : classifyKeyMap(scan, 0, "sort");
+ if (classified.mode === "none") return nothing;
const { prefix, from } = readMongoPropertyPrefix(text, safeCursor);
- return { mode, prefix, from, replaceClosingQuote: closingQuoteAtCursor(prefix, text, safeCursor) };
+ return { ...classified, prefix, from, replaceClosingQuote: closingQuoteAtCursor(prefix, text, safeCursor) };
}
/** Text to splice into a plain input for a chosen completion, and where to leave the selection. */
@@ -579,6 +586,7 @@ interface MongoCursorClass {
collection?: string;
method?: string;
bulkWriteOperation?: string;
+ keyMap?: string;
}
/**
@@ -671,9 +679,11 @@ function classifyCursorInCall(method: string, scan: MongoCallScan): MongoCursorC
case "documents":
return { mode: classifyDocument(scan, 1) };
case "projection":
+ return classifyKeyMap(scan, 0, "projection");
case "keys":
+ return classifyKeyMap(scan, 0, "index");
case "sortKeys":
- return { mode: classifyKeyMap(scan, 0) };
+ return classifyKeyMap(scan, 0, "sort");
// A bare string argument naming a field, e.g. distinct("category").
case "fieldName":
return { mode: scan.stack.length === 0 ? "fieldPath" : "none" };
@@ -745,11 +755,15 @@ function classifyDocument(scan: MongoCallScan, rootIndex: number): MongoCompleti
return inner.kind === "object" ? "field" : "none";
}
-function classifyKeyMap(scan: MongoCallScan, rootIndex: number): MongoCompletionMode {
+/**
+ * A field-to-value map: `sort({ field: -1 })`, `createIndex({ field: "text" })`, a projection.
+ * Keys are field names; values are the small fixed set `keyMap` names.
+ */
+function classifyKeyMap(scan: MongoCallScan, rootIndex: number, keyMap: string): MongoCursorClass {
const inner = innermost(scan);
- if (!inner || scan.inValue) return "none";
- if (inner.kind !== "object" || innerDepth(scan, rootIndex) !== 0) return "none";
- return "field";
+ if (!inner || inner.kind !== "object" || innerDepth(scan, rootIndex) !== 0) return { mode: "none" };
+ if (scan.inValue) return { mode: scan.inString ? "none" : "keyMapValue", keyMap };
+ return { mode: "field" };
}
/** Option keys whose value is a field-to-value map, so the cursor completes field names there. */
@@ -762,7 +776,8 @@ function classifyMethodOptions(method: string, scan: MongoCallScan): MongoCursor
// `{ sort: { … } }` and `{ projection: { … } }` are field maps one level in.
if (depth === 1 && inner.kind === "object" && FIELD_MAP_OPTION_KEYS.has(inner.key ?? "")) {
- return { mode: scan.inValue ? "none" : "field", method };
+ if (!scan.inValue) return { mode: "field", method };
+ return { mode: scan.inString ? "none" : "keyMapValue", method, keyMap: inner.key ?? "" };
}
if (depth !== 0 || scan.inValue) return { mode: "none" };
return { mode: inner.kind === "object" ? "methodOption" : "none", method };
@@ -855,7 +870,7 @@ function stageStringValueMode(stage: string): MongoCompletionMode {
function classifyStageBody(stage: string, scan: MongoCallScan, bodyIndex: number): MongoCursorClass {
if (stage === "$match") return { mode: classifyFilter(scan, bodyIndex), stage };
if (stage === "$group") return { mode: classifyGroup(scan, bodyIndex), stage };
- if (stage === "$sort") return { mode: classifyKeyMap(scan, bodyIndex), stage };
+ if (stage === "$sort") return { ...classifyKeyMap(scan, bodyIndex, "sort"), stage };
if (stage === "$unset") return { mode: innermost(scan)?.kind === "array" ? "fieldPath" : "none", stage };
if (OPTION_STAGES.has(stage)) return classifyStageOptions(stage, scan, bodyIndex);
// `$project`-shaped stages and anything unmodelled: keys are field names, values are expressions.
diff --git a/apps/desktop/src/lib/mongo/mongoCompletionTables.ts b/apps/desktop/src/lib/mongo/mongoCompletionTables.ts
index 5a7138901d..0c48b60293 100644
--- a/apps/desktop/src/lib/mongo/mongoCompletionTables.ts
+++ b/apps/desktop/src/lib/mongo/mongoCompletionTables.ts
@@ -294,6 +294,31 @@ export const EXPRESSION_OPERATORS: MongoOperatorSpec[] = specs([
["$rand", "Returns a random float between 0 and 1", "$rand: {}"],
]);
+/**
+ * Values a field-to-value map accepts, by the kind of map it is.
+ *
+ * `1`/`-1` and the index types are what the server understands in these positions; the driver
+ * passes the document straight through, so the server has the final say on anything exotic.
+ */
+export const KEY_MAP_VALUES: Record<string, MongoOperatorSpec[]> = {
+ sort: specs([
+ ["1", "Ascending", "1"],
+ ["-1", "Descending", "-1"],
+ ]),
+ projection: specs([
+ ["1", "Include the field", "1"],
+ ["0", "Exclude the field", "0"],
+ ]),
+ index: specs([
+ ["1", "Ascending index", "1"],
+ ["-1", "Descending index", "-1"],
+ ['"text"', "Text index for $text search", '"text"'],
+ ['"hashed"', "Hashed index for hashed sharding", '"hashed"'],
+ ['"2dsphere"', "Geospatial index for GeoJSON data", '"2dsphere"'],
+ ['"2d"', "Geospatial index for legacy coordinate pairs", '"2d"'],
+ ]),
+};
+
/**
* The operations a `bulkWrite()` array accepts, and the fields each one allows.
*
diff --git a/packages/app-tests/mongoCompletion.test.ts b/packages/app-tests/mongoCompletion.test.ts
index cdf9d3aa7f..c9508fa616 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, 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 { buildMongoCompletionItems, buildMongoCompletionItemsFromContext, getMongoCompletionContext, getMongoCompletionResultValidFor, getMongoDocumentQueryCompletionContext, inferMongoCompletionFields, shouldAutoOpenMongoCompletion } from "../../apps/desktop/src/lib/mongo/mongoCompletion.ts";
+import { ACCUMULATORS, BULK_WRITE_OPERATION_FIELDS, BULK_WRITE_OPERATIONS, EXPRESSION_OPERATORS, EXTENDED_JSON_VALUES, KEY_MAP_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"];
@@ -589,6 +589,44 @@ test("every suggested option key parses on the method that offers it", () => {
}
});
+test("suggests the values a field-to-value map accepts", () => {
+ assert.deepEqual(labels("db.users.find({}).sort({ name: ", { fields }), ["-1", "1"]);
+ assert.deepEqual(labels("db.users.aggregate([{ $sort: { name: ", { fields }), ["-1", "1"]);
+ assert.deepEqual(labels("db.users.find({}, { name: ", { fields }), ["0", "1"]);
+ assert.deepEqual(labels("db.users.findOne({}, { name: ", { fields }), ["0", "1"]);
+ assert.deepEqual(labels("db.users.createIndex({ name: ", { fields }), ["-1", '"2d"', '"2dsphere"', '"hashed"', '"text"', "1"]);
+
+ // The sort and projection options of the find-and-modify helpers are the same maps.
+ assert.deepEqual(labels("db.users.findOneAndUpdate({}, {$set:{a:1}}, { sort: { name: ", { fields }), ["-1", "1"]);
+ assert.deepEqual(labels("db.users.findOneAndDelete({}, { projection: { name: ", { fields }), ["0", "1"]);
+
+ // Keys are still field names, and a second key in the same map still gets values.
+ assert.deepEqual(labels("db.users.find({}).sort({ na", { fields }), ["name"]);
+ assert.deepEqual(labels("db.users.find({}).sort({ name: 1, createdAt: ", { fields }), ["-1", "1"]);
+
+ // Inside a quote the engine stays quiet, as it does for every other value position.
+ assert.deepEqual(labels('db.users.createIndex({ name: "', { fields }), []);
+
+ // The document browser's sort bar is the same map without a surrounding command.
+ const sortBar = getMongoDocumentQueryCompletionContext("{ name: ", "{ name: ".length, "sortKeys");
+ assert.deepEqual(buildMongoCompletionItemsFromContext(sortBar, { fields }).map((item) => item.label), ["-1", "1"]);
+});
+
+test("every suggested map value parses in the position that offers it", () => {
+ const commands: Record<string, (value: string) => string> = {
+ sort: (value) => `db.users.find({}).sort({ name: ${value} })`,
+ projection: (value) => `db.users.find({}, { name: ${value} })`,
+ index: (value) => `db.users.createIndex({ name: ${value} })`,
+ };
+ for (const [keyMap, values] of Object.entries(KEY_MAP_VALUES)) {
+ const build = commands[keyMap];
+ assert.ok(build, `${keyMap} needs a sample command in this test`);
+ for (const value of values) {
+ assert.ok(parseMongoCommand(build(value.label)), build(value.label));
+ }
+ }
+});
+
test("offers nothing rather than top-level snippets inside an unmodelled argument", () => {
// `db.collection.find` is not something that can be typed inside these parentheses, so the
// top-level snippets are noise there; the engine stays quiet until the argument is modelled.