feat(mongodb): suggest accepted values for field-to-value maps
This commit is contained in:
1 parent
ad1e5c9496
commit
d1446360cc
4 files changed
+96
-16
No files matched your search
@@ -84,7 +84,9 @@ describe("getMongoDocumentQueryCompletionContext", () => {
|
|||||||
it("completes sort keys without value or operator noise", () => {
|
it("completes sort keys without value or operator noise", () => {
|
||||||
expect(contextAt("{ created", "sortKeys")).toMatchObject({ mode: "field", prefix: "created" });
|
expect(contextAt("{ created", "sortKeys")).toMatchObject({ mode: "field", prefix: "created" });
|
||||||
expect(labelsAt("{ created", "sortKeys")).toEqual(["createdAt"]);
|
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" });
|
expect(contextAt("{ createdAt: -1, ", "sortKeys")).toMatchObject({ mode: "field" });
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|||||||
@@ -9,6 +9,7 @@ import {
|
|||||||
PUSH_MODIFIERS,
|
PUSH_MODIFIERS,
|
||||||
BULK_WRITE_OPERATION_FIELDS,
|
BULK_WRITE_OPERATION_FIELDS,
|
||||||
BULK_WRITE_OPERATIONS,
|
BULK_WRITE_OPERATIONS,
|
||||||
|
KEY_MAP_VALUES,
|
||||||
METHOD_OPTION_KEYS,
|
METHOD_OPTION_KEYS,
|
||||||
STAGE_OPTION_KEYS,
|
STAGE_OPTION_KEYS,
|
||||||
TOP_LEVEL_QUERY_OPERATORS,
|
TOP_LEVEL_QUERY_OPERATORS,
|
||||||
@@ -52,7 +53,8 @@ export type MongoCompletionMode =
|
|||||||
| "stageOption"
|
| "stageOption"
|
||||||
| "methodOption"
|
| "methodOption"
|
||||||
| "bulkWriteOperation"
|
| "bulkWriteOperation"
|
||||||
| "bulkWriteField";
|
| "bulkWriteField"
|
||||||
|
| "keyMapValue";
|
||||||
|
|
||||||
export interface MongoCompletionField {
|
export interface MongoCompletionField {
|
||||||
name: string;
|
name: string;
|
||||||
@@ -86,6 +88,8 @@ export interface MongoCompletionContext {
|
|||||||
method?: string;
|
method?: string;
|
||||||
/** bulkWrite operation (`updateOne`, `deleteMany`, …) whose body the cursor sits in. */
|
/** bulkWrite operation (`updateOne`, `deleteMany`, …) whose body the cursor sits in. */
|
||||||
bulkWriteOperation?: string;
|
bulkWriteOperation?: string;
|
||||||
|
/** Which field-to-value map the cursor sits in: `sort`, `projection` or `index`. */
|
||||||
|
keyMap?: string;
|
||||||
}
|
}
|
||||||
|
|
||||||
export interface MongoCompletionInput {
|
export interface MongoCompletionInput {
|
||||||
@@ -262,7 +266,7 @@ export function getMongoCompletionContext(text: string, cursor: number): MongoCo
|
|||||||
const database = extractActiveDatabase(text, safeCursor);
|
const database = extractActiveDatabase(text, safeCursor);
|
||||||
const { prefix, from } = readMongoPropertyPrefix(text, safeCursor);
|
const { prefix, from } = readMongoPropertyPrefix(text, safeCursor);
|
||||||
const replaceClosingQuote = closingQuoteAtCursor(prefix, 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 };
|
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);
|
const classified = classifyCursorInCall(call.method, scan);
|
||||||
return {
|
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,
|
collection: classified.collection ?? collection,
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
@@ -398,6 +402,9 @@ export function buildMongoCompletionItemsFromContext(context: MongoCompletionCon
|
|||||||
case "bulkWriteOperation":
|
case "bulkWriteOperation":
|
||||||
items = specItems(BULK_WRITE_OPERATIONS, prefix, "bulkWrite operation", 100);
|
items = specItems(BULK_WRITE_OPERATIONS, prefix, "bulkWrite operation", 100);
|
||||||
break;
|
break;
|
||||||
|
case "keyMapValue":
|
||||||
|
items = specItems(KEY_MAP_VALUES[context.keyMap ?? ""] ?? [], prefix, `${context.keyMap} value`, 100);
|
||||||
|
break;
|
||||||
case "bulkWriteField":
|
case "bulkWriteField":
|
||||||
items = specItems(BULK_WRITE_OPERATION_FIELDS[context.bulkWriteOperation ?? ""] ?? [], prefix, `${context.bulkWriteOperation} field`, 100);
|
items = specItems(BULK_WRITE_OPERATION_FIELDS[context.bulkWriteOperation ?? ""] ?? [], prefix, `${context.bulkWriteOperation} field`, 100);
|
||||||
break;
|
break;
|
||||||
@@ -461,11 +468,11 @@ export function getMongoDocumentQueryCompletionContext(text: string, cursor: num
|
|||||||
const scan = scanMongoCallArguments(text, 0, safeCursor);
|
const scan = scanMongoCallArguments(text, 0, safeCursor);
|
||||||
if (!scan) return nothing;
|
if (!scan) return nothing;
|
||||||
|
|
||||||
const mode = kind === "filter" ? classifyFilter(scan, 0) : classifyKeyMap(scan, 0);
|
const classified = kind === "filter" ? { mode: classifyFilter(scan, 0) } : classifyKeyMap(scan, 0, "sort");
|
||||||
if (mode === "none") return nothing;
|
if (classified.mode === "none") return nothing;
|
||||||
|
|
||||||
const { prefix, from } = readMongoPropertyPrefix(text, safeCursor);
|
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. */
|
/** 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;
|
collection?: string;
|
||||||
method?: string;
|
method?: string;
|
||||||
bulkWriteOperation?: string;
|
bulkWriteOperation?: string;
|
||||||
|
keyMap?: string;
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -671,9 +679,11 @@ function classifyCursorInCall(method: string, scan: MongoCallScan): MongoCursorC
|
|||||||
case "documents":
|
case "documents":
|
||||||
return { mode: classifyDocument(scan, 1) };
|
return { mode: classifyDocument(scan, 1) };
|
||||||
case "projection":
|
case "projection":
|
||||||
|
return classifyKeyMap(scan, 0, "projection");
|
||||||
case "keys":
|
case "keys":
|
||||||
|
return classifyKeyMap(scan, 0, "index");
|
||||||
case "sortKeys":
|
case "sortKeys":
|
||||||
return { mode: classifyKeyMap(scan, 0) };
|
return classifyKeyMap(scan, 0, "sort");
|
||||||
// A bare string argument naming a field, e.g. distinct("category").
|
// A bare string argument naming a field, e.g. distinct("category").
|
||||||
case "fieldName":
|
case "fieldName":
|
||||||
return { mode: scan.stack.length === 0 ? "fieldPath" : "none" };
|
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";
|
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);
|
const inner = innermost(scan);
|
||||||
if (!inner || scan.inValue) return "none";
|
if (!inner || inner.kind !== "object" || innerDepth(scan, rootIndex) !== 0) return { mode: "none" };
|
||||||
if (inner.kind !== "object" || innerDepth(scan, rootIndex) !== 0) return "none";
|
if (scan.inValue) return { mode: scan.inString ? "none" : "keyMapValue", keyMap };
|
||||||
return "field";
|
return { mode: "field" };
|
||||||
}
|
}
|
||||||
|
|
||||||
/** Option keys whose value is a field-to-value map, so the cursor completes field names there. */
|
/** 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.
|
// `{ sort: { … } }` and `{ projection: { … } }` are field maps one level in.
|
||||||
if (depth === 1 && inner.kind === "object" && FIELD_MAP_OPTION_KEYS.has(inner.key ?? "")) {
|
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" };
|
if (depth !== 0 || scan.inValue) return { mode: "none" };
|
||||||
return { mode: inner.kind === "object" ? "methodOption" : "none", method };
|
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 {
|
function classifyStageBody(stage: string, scan: MongoCallScan, bodyIndex: number): MongoCursorClass {
|
||||||
if (stage === "$match") return { mode: classifyFilter(scan, bodyIndex), stage };
|
if (stage === "$match") return { mode: classifyFilter(scan, bodyIndex), stage };
|
||||||
if (stage === "$group") return { mode: classifyGroup(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 (stage === "$unset") return { mode: innermost(scan)?.kind === "array" ? "fieldPath" : "none", stage };
|
||||||
if (OPTION_STAGES.has(stage)) return classifyStageOptions(stage, scan, bodyIndex);
|
if (OPTION_STAGES.has(stage)) return classifyStageOptions(stage, scan, bodyIndex);
|
||||||
// `$project`-shaped stages and anything unmodelled: keys are field names, values are expressions.
|
// `$project`-shaped stages and anything unmodelled: keys are field names, values are expressions.
|
||||||
|
|||||||
@@ -294,6 +294,31 @@ export const EXPRESSION_OPERATORS: MongoOperatorSpec[] = specs([
|
|||||||
["$rand", "Returns a random float between 0 and 1", "$rand: {}"],
|
["$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.
|
* The operations a `bulkWrite()` array accepts, and the fields each one allows.
|
||||||
*
|
*
|
||||||
|
|||||||
+40
-2
@@ -1,7 +1,7 @@
|
|||||||
import { strict as assert } from "node:assert";
|
import { strict as assert } from "node:assert";
|
||||||
import { test } from "vitest";
|
import { test } from "vitest";
|
||||||
import { buildMongoCompletionItems, getMongoCompletionContext, getMongoCompletionResultValidFor, inferMongoCompletionFields, shouldAutoOpenMongoCompletion } from "../../apps/desktop/src/lib/mongo/mongoCompletion.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, 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, 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";
|
import { parseMongoCommand } from "../../apps/desktop/src/lib/mongo/mongoShellCommand.ts";
|
||||||
|
|
||||||
const collections = ["users", "user_events", "order-items", "audit.logs"];
|
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", () => {
|
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
|
// `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.
|
// top-level snippets are noise there; the engine stays quiet until the argument is modelled.
|
||||||
|
|||||||
Reference in new issue
Block a user