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。

fix(mongodb): replace the typed new when completing constructors

Loc Nguyen4fadbb98017c
diff --git a/apps/desktop/src/lib/mongo/mongoCompletion.ts b/apps/desktop/src/lib/mongo/mongoCompletion.ts
index c8d7cb8b17..f3085a4e02 100644
--- a/apps/desktop/src/lib/mongo/mongoCompletion.ts
+++ b/apps/desktop/src/lib/mongo/mongoCompletion.ts
@@ -25,6 +25,9 @@ import {
type MongoOperatorSpec,
} from "@/lib/mongo/mongoCompletionTables";
+/** Snippets callable with `new` — every shell constructor accepts it (bare `Date(` is the only rejected spelling); literals like `null` do not. */
+const NEW_CONSTRUCTIBLE_VALUE_SNIPPETS: readonly MongoOperatorSpec[] = VALUE_SNIPPETS.filter((spec) => spec.label === "new Date" || /^[A-Z]/.test(spec.label));
+
/**
* What the cursor may usefully be completed with. Each mode maps to exactly one
* item source, so `buildMongoCompletionItemsFromContext` never has to re-derive
@@ -442,8 +445,11 @@ export function getMongoCompletionContext(text: string, cursor: number): MongoCo
const classified = classifyCursorInCall(call.method, scan);
const variables = classified.mode === "fieldRef" || classified.mode === "expression" ? collectScopeVariables(scan) : undefined;
+ const valuePrefix = classified.mode === "value" ? adjustValuePrefixForNew(text, safeCursor, from) : { prefix, from };
return {
...at(classified.mode, classified.stage, classified.method, classified.bulkWriteOperation, classified.keyMap),
+ prefix: valuePrefix.prefix,
+ from: valuePrefix.from,
...(classified.operator ? { operator: classified.operator } : {}),
...(classified.enumKey ? { enumKey: classified.enumKey } : {}),
...(classified.pipelineKind ? { pipelineKind: classified.pipelineKind } : {}),
@@ -534,6 +540,12 @@ export function buildMongoCompletionItemsFromContext(context: MongoCompletionCon
items = indexNameItems(prefix, input.indexes ?? [], context.method);
break;
case "value":
+ if (/^new\s+/i.test(prefix)) {
+ // Match against what follows `new ` so `new O` still finds `ObjectId("…")`;
+ // the replacement range already covers the typed keyword via adjustValuePrefixForNew.
+ items = specItems(NEW_CONSTRUCTIBLE_VALUE_SNIPPETS, normalizeMongoKeyPrefix(prefix).replace(/^new\s+/i, ""), "value", 100);
+ break;
+ }
// Shell constructors first; the extended JSON spellings need their own braces here.
items = [...specItems(VALUE_SNIPPETS, prefix, "value", 100), ...specItems(BRACED_EXTENDED_JSON_VALUES, prefix, "extended JSON value", 90)];
break;
@@ -625,7 +637,9 @@ export function shouldAutoOpenMongoCompletion(text: string, cursor: number): boo
if (!previousChar) return false;
if (text.slice(0, cursor).endsWith("db.")) 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 === " " && (matchUseDatabasePrefix(text.slice(0, cursor)) || matchShowSubcommandPrefix(text.slice(0, cursor)) || (/(?:^|[^\w$.])new\s+$/.test(text.slice(0, cursor)) && getMongoCompletionContext(text, cursor).mode === "value"))) {
+ return true;
+ }
if (previousChar === ".") {
return getMongoCompletionContext(text, cursor).mode !== "none";
}
@@ -672,7 +686,8 @@ export function getMongoDocumentQueryCompletionContext(text: string, cursor: num
const classified = kind === "filter" ? classifyFilter(scan, 0) : classifyKeyMap(scan, 0, "sort");
if (classified.mode === "none") return nothing;
- const { prefix, from } = readMongoPropertyPrefix(text, safeCursor);
+ const rawPrefix = readMongoPropertyPrefix(text, safeCursor);
+ const { prefix, from } = classified.mode === "value" ? adjustValuePrefixForNew(text, safeCursor, rawPrefix.from) : rawPrefix;
const variables = classified.mode === "fieldRef" || classified.mode === "expression" ? collectScopeVariables(scan) : undefined;
return {
...classified,
@@ -766,7 +781,10 @@ export function shouldAutoOpenMongoDocumentQueryCompletion(text: string, cursor:
* of the identifier and are safe to keep.
*/
export function getMongoCompletionResultValidFor(context?: MongoCompletionContext): RegExp {
- if (!context || !DOT_SCOPED_MODES.has(context.mode)) return /["']?[\w_$.-]*$/;
+ if (!context || !DOT_SCOPED_MODES.has(context.mode)) {
+ if (context?.mode === "value") return /(?:new\s+)?["']?[\w_$.-]*$/;
+ return /["']?[\w_$.-]*$/;
+ }
const segments = context.prefix.split(".").length;
return new RegExp(`["']?[\\w_$-]*${"\\.[\\w_$-]*".repeat(segments - 1)}$`);
}
@@ -1993,6 +2011,15 @@ export function readMongoPropertyPrefix(text: string, cursor: number): { prefix:
return { prefix: text.slice(from, safeCursor), from };
}
+export function adjustValuePrefixForNew(text: string, cursor: number, from: number): { prefix: string; from: number } {
+ const beforeFrom = text.slice(0, from);
+ const match = /(?:^|[^\w$.])(new\s+)$/.exec(beforeFrom);
+ if (!match || !match[1]) return { prefix: text.slice(from, cursor), from };
+ const newStart = from - match[1].length;
+ if (isInsideMongoComment(text, newStart)) return { prefix: text.slice(from, cursor), from };
+ return { prefix: text.slice(newStart, cursor), from: newStart };
+}
+
function findOpenMongoQuoteStart(text: string, cursor: number): number | null {
for (let index = 0; index < cursor; index++) {
const char = text[index];
@@ -2536,11 +2563,11 @@ function escapeSingleQuoted(value: string): string {
}
function startsWithPrefix(value: string, prefix: string): boolean {
- return value.toLowerCase().startsWith(prefix.toLowerCase());
+ return value.toLowerCase().startsWith(prefix.toLowerCase().replace(/\s+/g, " "));
}
function matchesFuzzyPrefix(value: string, prefix: string): boolean {
- const normalizedPrefix = normalizeMongoKeyPrefix(prefix).toLowerCase();
+ const normalizedPrefix = normalizeMongoKeyPrefix(prefix).toLowerCase().replace(/\s+/g, " ");
if (!normalizedPrefix) return true;
return value.toLowerCase().includes(normalizedPrefix);
}
diff --git a/packages/app-tests/mongoCompletion.test.ts b/packages/app-tests/mongoCompletion.test.ts
index 5a790433d6..5c1a706902 100644
--- a/packages/app-tests/mongoCompletion.test.ts
+++ b/packages/app-tests/mongoCompletion.test.ts
@@ -2072,6 +2072,96 @@ test("keeps the find chain completable when a comment holds an unbalanced parent
assert.deepEqual(labels('db.users.find({ note: "(x" }).li', { fields }), ["limit"]);
});
+test("replaces typed new keyword when completing new Date", () => {
+ // Bad case 1: cursor after `new D`
+ const text1 = "db.users.find({ name: new D";
+ const cursor1 = text1.length;
+ const context1 = getMongoCompletionContext(text1, cursor1);
+ const items1 = buildMongoCompletionItems(text1, cursor1, { fields });
+ const item1 = items1.find((candidate) => candidate.label === "new Date");
+ assert.ok(item1);
+ assert.equal(context1.from, text1.indexOf("new D"));
+ assert.equal(context1.prefix, "new D");
+ assert.equal(item1.apply, 'new Date("${date}")');
+ const inserted1 = text1.slice(0, context1.from) + item1.apply + text1.slice(cursor1);
+ assert.equal(inserted1, 'db.users.find({ name: new Date("${date}")');
+ // Every shell constructor accepts `new`, so matching the part after `new `
+ // keeps the other `…d…` constructors alongside `new Date`.
+ assert.deepEqual(
+ items1.map((candidate) => candidate.label),
+ ["ISODate", "ObjectId", "BinData", "new Date", "NumberDecimal", "UUID"],
+ );
+
+ // Bad case 2: cursor after `new ` (trailing space)
+ const text2 = "db.users.find({ name: new ";
+ const cursor2 = text2.length;
+ const context2 = getMongoCompletionContext(text2, cursor2);
+ const items2 = buildMongoCompletionItems(text2, cursor2, { fields });
+ const item2 = items2.find((candidate) => candidate.label === "new Date");
+ assert.ok(item2);
+ assert.equal(context2.from, text2.indexOf("new "));
+ assert.equal(context2.prefix, "new ");
+ assert.equal(item2.apply, 'new Date("${date}")');
+ const inserted2 = text2.slice(0, context2.from) + item2.apply + text2.slice(cursor2);
+ assert.equal(inserted2, 'db.users.find({ name: new Date("${date}")');
+ const labels2 = items2.map((candidate) => candidate.label);
+ assert.ok(labels2.includes("new Date"));
+ assert.ok(labels2.includes("ObjectId"));
+ assert.ok(labels2.includes("NumberLong"));
+ assert.equal(labels2.includes("null"), false, "literals are not constructible");
+ assert.equal(labels2.includes("true"), false);
+ assert.equal(labels2.includes("false"), false);
+
+ // `new O` finds the other constructible constructors (mongosh BSON classes accept `new`)
+ const text2b = "db.users.find({ name: new O";
+ const cursor2b = text2b.length;
+ const context2b = getMongoCompletionContext(text2b, cursor2b);
+ const items2b = buildMongoCompletionItems(text2b, cursor2b, { fields });
+ const item2b = items2b.find((candidate) => candidate.label === "ObjectId");
+ assert.ok(item2b);
+ assert.equal(context2b.from, text2b.indexOf("new O"));
+ assert.equal(item2b.apply, 'ObjectId("${id}")');
+ const inserted2b = text2b.slice(0, context2b.from) + item2b.apply + text2b.slice(cursor2b);
+ assert.equal(inserted2b, 'db.users.find({ name: ObjectId("${id}")');
+
+ // ValidFor regex allows typing after new in value mode
+ const pattern = getMongoCompletionResultValidFor(context1);
+ const isValid = (typed: string) => new RegExp(`^(?:${pattern.source})$`).test(typed);
+ assert.equal(isValid("new "), true);
+ assert.equal(isValid("new D"), true);
+ assert.equal(isValid("new Date"), true);
+ assert.equal(isValid("new Date("), false);
+
+ // Document query completion in filter mode
+ const docText = "{ name: new D";
+ const docCursor = docText.length;
+ const docContext = getMongoDocumentQueryCompletionContext(docText, docCursor, "filter");
+ assert.equal(docContext.from, docText.indexOf("new D"));
+ assert.equal(docContext.prefix, "new D");
+
+ // `ne` case unchanged
+ const text3 = "db.users.find({ name: ne";
+ const cursor3 = text3.length;
+ const context3 = getMongoCompletionContext(text3, cursor3);
+ const items3 = buildMongoCompletionItems(text3, cursor3, { fields });
+ const item3 = items3.find((candidate) => candidate.label === "new Date");
+ assert.ok(item3);
+ assert.equal(context3.from, text3.indexOf("ne"));
+ assert.equal(context3.prefix, "ne");
+ assert.equal(item3.apply, 'new Date("${date}")');
+ const inserted3 = text3.slice(0, context3.from) + item3.apply + text3.slice(cursor3);
+ assert.equal(inserted3, 'db.users.find({ name: new Date("${date}")');
+
+ // `{ name: "new D` (inside a string) unchanged
+ const text4 = 'db.users.find({ name: "new D';
+ const cursor4 = text4.length;
+ const context4 = getMongoCompletionContext(text4, cursor4);
+ const items4 = buildMongoCompletionItems(text4, cursor4, { fields });
+ assert.equal(context4.mode, "none");
+ assert.equal(context4.prefix, '"new D');
+ assert.deepEqual(items4, []);
+});
+
test("offers $comment as a top-level query operator", () => {
const items = labels("db.users.find({ $c", { fields });
assert.ok(items.includes("$comment"), "db.users.find({ $c should offer $comment");