feat(mongodb): complete operator sub-documents and enum values
This commit is contained in:
1 parent
aff43d7ba9
commit
39e94454a0
3 files changed
+501
-53
No files matched your search
@@ -3,6 +3,7 @@ import {
|
|||||||
ACCUMULATORS,
|
ACCUMULATORS,
|
||||||
COMMON_OPERATORS,
|
COMMON_OPERATORS,
|
||||||
EXPRESSION_OPERATORS,
|
EXPRESSION_OPERATORS,
|
||||||
|
ENUM_VALUES,
|
||||||
EXTENDED_JSON_VALUES,
|
EXTENDED_JSON_VALUES,
|
||||||
FIELD_QUERY_OPERATORS,
|
FIELD_QUERY_OPERATORS,
|
||||||
PIPELINE_STAGES,
|
PIPELINE_STAGES,
|
||||||
@@ -11,10 +12,10 @@ import {
|
|||||||
BULK_WRITE_OPERATIONS,
|
BULK_WRITE_OPERATIONS,
|
||||||
KEY_MAP_VALUES,
|
KEY_MAP_VALUES,
|
||||||
METHOD_OPTION_KEYS,
|
METHOD_OPTION_KEYS,
|
||||||
|
OPERATOR_SUB_KEYS,
|
||||||
STAGE_OPTION_KEYS,
|
STAGE_OPTION_KEYS,
|
||||||
TOP_LEVEL_QUERY_OPERATORS,
|
TOP_LEVEL_QUERY_OPERATORS,
|
||||||
UPDATE_OPERATORS,
|
UPDATE_OPERATORS,
|
||||||
UPDATE_OPERATOR_LABELS,
|
|
||||||
VALUE_SNIPPETS,
|
VALUE_SNIPPETS,
|
||||||
mongoOperatorItemType,
|
mongoOperatorItemType,
|
||||||
type MongoOperatorSpec,
|
type MongoOperatorSpec,
|
||||||
@@ -55,7 +56,9 @@ export type MongoCompletionMode =
|
|||||||
| "methodOption"
|
| "methodOption"
|
||||||
| "bulkWriteOperation"
|
| "bulkWriteOperation"
|
||||||
| "bulkWriteField"
|
| "bulkWriteField"
|
||||||
| "keyMapValue";
|
| "keyMapValue"
|
||||||
|
| "operatorField"
|
||||||
|
| "enumValue";
|
||||||
|
|
||||||
export interface MongoCompletionField {
|
export interface MongoCompletionField {
|
||||||
name: string;
|
name: string;
|
||||||
@@ -91,6 +94,10 @@ export interface MongoCompletionContext {
|
|||||||
bulkWriteOperation?: string;
|
bulkWriteOperation?: string;
|
||||||
/** Which field-to-value map the cursor sits in: `sort`, `projection` or `index`. */
|
/** Which field-to-value map the cursor sits in: `sort`, `projection` or `index`. */
|
||||||
keyMap?: string;
|
keyMap?: string;
|
||||||
|
/** Operator whose own sub-document the cursor sits in (`$text`, `$near`, `$jsonSchema`, `collation`). */
|
||||||
|
operator?: string;
|
||||||
|
/** Which fixed value set the cursor's value position accepts (`$type`, `explain`, `caseFirst`). */
|
||||||
|
enumKey?: string;
|
||||||
}
|
}
|
||||||
|
|
||||||
export interface MongoCompletionInput {
|
export interface MongoCompletionInput {
|
||||||
@@ -177,6 +184,7 @@ const CURSOR_METHODS = [
|
|||||||
{ label: "limit", detail: "Limit cursor results", apply: "limit(100)" },
|
{ label: "limit", detail: "Limit cursor results", apply: "limit(100)" },
|
||||||
{ label: "skip", detail: "Skip cursor results", apply: "skip(0)" },
|
{ label: "skip", detail: "Skip cursor results", apply: "skip(0)" },
|
||||||
{ label: "explain", detail: "Show the query plan instead of the results", apply: 'explain("executionStats")' },
|
{ label: "explain", detail: "Show the query plan instead of the results", apply: 'explain("executionStats")' },
|
||||||
|
{ label: "collation", detail: "Locale-aware rules for matching and sorting", apply: 'collation({ locale: "${en}" })' },
|
||||||
] as const;
|
] as const;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -206,7 +214,7 @@ const ROOT_SNIPPET_BOOST: Record<(typeof ROOT_SNIPPETS)[number]["label"], number
|
|||||||
};
|
};
|
||||||
|
|
||||||
/** Role of each positional argument, by collection helper. Drives cursor classification. */
|
/** 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";
|
type MongoArgRole = "filter" | "update" | "replacement" | "document" | "documents" | "operations" | "pipeline" | "projection" | "keys" | "sortKeys" | "fieldName" | "options" | "collation" | "verbosity";
|
||||||
|
|
||||||
const METHOD_ARG_ROLES: Record<string, readonly MongoArgRole[]> = {
|
const METHOD_ARG_ROLES: Record<string, readonly MongoArgRole[]> = {
|
||||||
find: ["filter", "projection"],
|
find: ["filter", "projection"],
|
||||||
@@ -228,6 +236,8 @@ const METHOD_ARG_ROLES: Record<string, readonly MongoArgRole[]> = {
|
|||||||
createIndex: ["keys", "options"],
|
createIndex: ["keys", "options"],
|
||||||
distinct: ["fieldName", "filter"],
|
distinct: ["fieldName", "filter"],
|
||||||
sort: ["sortKeys"],
|
sort: ["sortKeys"],
|
||||||
|
collation: ["collation"],
|
||||||
|
explain: ["verbosity"],
|
||||||
};
|
};
|
||||||
|
|
||||||
/** `{ $oid: "..." }` for a bare value position, where the user has not typed the braces yet. */
|
/** `{ $oid: "..." }` for a bare value position, where the user has not typed the braces yet. */
|
||||||
@@ -318,7 +328,7 @@ export function getMongoCompletionContext(text: string, cursor: number): MongoCo
|
|||||||
const cursorChain = matchCursorMethodDot(beforeCursor);
|
const cursorChain = matchCursorMethodDot(beforeCursor);
|
||||||
if (cursorChain) {
|
if (cursorChain) {
|
||||||
const methodPrefix = readMethodPrefix(beforeCursor);
|
const methodPrefix = readMethodPrefix(beforeCursor);
|
||||||
return { mode: "cursorMethod", prefix: methodPrefix.prefix, from: methodPrefix.from, collection, database, stage: cursorChain.countable ? "countable" : undefined };
|
return { mode: "cursorMethod", prefix: methodPrefix.prefix, from: methodPrefix.from, collection, database, stage: cursorChain.countable ? "countable" : cursorChain.find ? "find" : undefined };
|
||||||
}
|
}
|
||||||
|
|
||||||
const call = findInnermostMongoCall(beforeCursor);
|
const call = findInnermostMongoCall(beforeCursor);
|
||||||
@@ -333,6 +343,8 @@ 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, classified.keyMap),
|
...at(classified.mode, classified.stage, classified.method, classified.bulkWriteOperation, classified.keyMap),
|
||||||
|
...(classified.operator ? { operator: classified.operator } : {}),
|
||||||
|
...(classified.enumKey ? { enumKey: classified.enumKey } : {}),
|
||||||
collection: classified.collection ?? collection,
|
collection: classified.collection ?? collection,
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
@@ -370,7 +382,7 @@ export function buildMongoCompletionItemsFromContext(context: MongoCompletionCon
|
|||||||
items = methodItems(prefix);
|
items = methodItems(prefix);
|
||||||
break;
|
break;
|
||||||
case "cursorMethod":
|
case "cursorMethod":
|
||||||
items = cursorMethodItems(prefix, context.stage === "countable");
|
items = cursorMethodItems(prefix, context.stage === "countable", context.stage === "countable" || context.stage === "find");
|
||||||
break;
|
break;
|
||||||
case "field":
|
case "field":
|
||||||
items = fieldItems(prefix, fields);
|
items = fieldItems(prefix, fields);
|
||||||
@@ -426,6 +438,12 @@ export function buildMongoCompletionItemsFromContext(context: MongoCompletionCon
|
|||||||
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;
|
||||||
|
case "operatorField":
|
||||||
|
items = specItems(OPERATOR_SUB_KEYS[context.operator ?? ""] ?? [], prefix, `${context.operator} key`, 100);
|
||||||
|
break;
|
||||||
|
case "enumValue":
|
||||||
|
items = enumValueItems(prefix, ENUM_VALUES[context.enumKey ?? ""] ?? [], context.enumKey ?? "");
|
||||||
|
break;
|
||||||
default:
|
default:
|
||||||
items = [];
|
items = [];
|
||||||
}
|
}
|
||||||
@@ -493,7 +511,7 @@ 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 classified = kind === "filter" ? { mode: classifyFilter(scan, 0) } : classifyKeyMap(scan, 0, "sort");
|
const classified = kind === "filter" ? classifyFilter(scan, 0) : classifyKeyMap(scan, 0, "sort");
|
||||||
if (classified.mode === "none") return nothing;
|
if (classified.mode === "none") return nothing;
|
||||||
|
|
||||||
const { prefix, from } = readMongoPropertyPrefix(text, safeCursor);
|
const { prefix, from } = readMongoPropertyPrefix(text, safeCursor);
|
||||||
@@ -623,6 +641,8 @@ interface MongoCursorClass {
|
|||||||
method?: string;
|
method?: string;
|
||||||
bulkWriteOperation?: string;
|
bulkWriteOperation?: string;
|
||||||
keyMap?: string;
|
keyMap?: string;
|
||||||
|
operator?: string;
|
||||||
|
enumKey?: string;
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -706,9 +726,9 @@ function classifyCursorInCall(method: string, scan: MongoCallScan): MongoCursorC
|
|||||||
|
|
||||||
switch (role) {
|
switch (role) {
|
||||||
case "filter":
|
case "filter":
|
||||||
return { mode: classifyFilter(scan, 0) };
|
return classifyFilter(scan, 0);
|
||||||
case "update":
|
case "update":
|
||||||
return { mode: classifyUpdate(scan, 0) };
|
return classifyUpdate(scan, 0);
|
||||||
case "replacement":
|
case "replacement":
|
||||||
case "document":
|
case "document":
|
||||||
return { mode: classifyDocument(scan, 0) };
|
return { mode: classifyDocument(scan, 0) };
|
||||||
@@ -729,6 +749,12 @@ function classifyCursorInCall(method: string, scan: MongoCallScan): MongoCursorC
|
|||||||
return classifyBulkWriteOperations(scan);
|
return classifyBulkWriteOperations(scan);
|
||||||
case "options":
|
case "options":
|
||||||
return classifyMethodOptions(method, scan);
|
return classifyMethodOptions(method, scan);
|
||||||
|
// `find(…).collation({ … })`, the same document as the `collation` option.
|
||||||
|
case "collation":
|
||||||
|
return classifyCollation(scan, 0);
|
||||||
|
// `find(…).explain("executionStats")`.
|
||||||
|
case "verbosity":
|
||||||
|
return scan.stack.length === 0 ? { mode: "enumValue", enumKey: "explain" } : { mode: "none" };
|
||||||
default:
|
default:
|
||||||
return { mode: "none" };
|
return { mode: "none" };
|
||||||
}
|
}
|
||||||
@@ -743,14 +769,38 @@ function innermost(scan: MongoCallScan): MongoContainer | undefined {
|
|||||||
return scan.stack[scan.stack.length - 1];
|
return scan.stack[scan.stack.length - 1];
|
||||||
}
|
}
|
||||||
|
|
||||||
function classifyFilter(scan: MongoCallScan, rootIndex: number): MongoCompletionMode {
|
/** Query operators whose value is a document with its own keys rather than a field's constraint object. */
|
||||||
|
const SUB_DOCUMENT_QUERY_OPERATORS = new Set(["$text", "$geoWithin", "$geoIntersects", "$near", "$nearSphere", "$geometry"]);
|
||||||
|
|
||||||
|
/** Value positions in a filter that take a fixed set of strings, by the key and the operator that holds it. */
|
||||||
|
function filterValueEnum(operator: string | null, key: string | null): string | undefined {
|
||||||
|
if (key === "$type") return "$type";
|
||||||
|
if (key === "$options") return "$options";
|
||||||
|
if (key === "type" && operator === "$geometry") return "geometryType";
|
||||||
|
return undefined;
|
||||||
|
}
|
||||||
|
|
||||||
|
function classifyFilter(scan: MongoCallScan, rootIndex: number): MongoCursorClass {
|
||||||
const inner = innermost(scan);
|
const inner = innermost(scan);
|
||||||
if (!inner || innerDepth(scan, rootIndex) < 0) return "none";
|
if (!inner || innerDepth(scan, rootIndex) < 0) return { mode: "none" };
|
||||||
// Elements of `$in: [...]` are values, so `{ _id: { $in: [ObjectId(...)] } }` completes like any value.
|
|
||||||
if (inner.kind === "array") return VALUE_ARRAY_OPERATORS.has(inner.key ?? "") && !scan.inString ? "value" : "none";
|
// Under `$jsonSchema` the vocabulary is JSON Schema, however deep the cursor sits.
|
||||||
if (inner.kind !== "object") return "none";
|
const schemaIndex = findContainerIndex(scan, rootIndex, "$jsonSchema");
|
||||||
if (scan.inValue) return scan.inString ? "none" : "value";
|
if (schemaIndex >= 0) return classifyJsonSchema(scan, schemaIndex);
|
||||||
if (innerDepth(scan, rootIndex) === 0) return "filterField";
|
|
||||||
|
if (inner.kind === "array") {
|
||||||
|
// `$type: ["string", "null"]` lists BSON types.
|
||||||
|
if (inner.key === "$type") return { mode: "enumValue", enumKey: "$type" };
|
||||||
|
// Elements of `$in: [...]` are values, so `{ _id: { $in: [ObjectId(...)] } }` completes like any value.
|
||||||
|
return { mode: VALUE_ARRAY_OPERATORS.has(inner.key ?? "") && !scan.inString ? "value" : "none" };
|
||||||
|
}
|
||||||
|
if (inner.kind !== "object") return { mode: "none" };
|
||||||
|
if (scan.inValue) {
|
||||||
|
const enumKey = filterValueEnum(inner.key, scan.valueKey);
|
||||||
|
if (enumKey) return { mode: "enumValue", enumKey };
|
||||||
|
return { mode: scan.inString ? "none" : "value" };
|
||||||
|
}
|
||||||
|
if (innerDepth(scan, rootIndex) === 0) return { mode: "filterField" };
|
||||||
|
|
||||||
// Inside a nested object: whose value is it?
|
// Inside a nested object: whose value is it?
|
||||||
switch (inner.key) {
|
switch (inner.key) {
|
||||||
@@ -758,30 +808,78 @@ function classifyFilter(scan: MongoCallScan, rootIndex: number): MongoCompletion
|
|||||||
// An object inside an array: a sub-filter under `$and` / `$or` / `$nor`,
|
// An object inside an array: a sub-filter under `$and` / `$or` / `$nor`,
|
||||||
// or an extended JSON wrapper such as `{ $oid: ... }` under `$in`.
|
// or an extended JSON wrapper such as `{ $oid: ... }` under `$in`.
|
||||||
const parent = scan.stack[scan.stack.length - 2];
|
const parent = scan.stack[scan.stack.length - 2];
|
||||||
return parent?.kind === "array" && VALUE_ARRAY_OPERATORS.has(parent.key ?? "") ? "valueWrapper" : "filterField";
|
return { mode: parent?.kind === "array" && VALUE_ARRAY_OPERATORS.has(parent.key ?? "") ? "valueWrapper" : "filterField" };
|
||||||
}
|
}
|
||||||
case "$elemMatch":
|
case "$elemMatch":
|
||||||
return "filterField";
|
return { mode: "filterField" };
|
||||||
case "$expr":
|
case "$expr":
|
||||||
return "expression";
|
return { mode: "expression" };
|
||||||
case "$jsonSchema":
|
|
||||||
return "none";
|
|
||||||
default:
|
default:
|
||||||
return "queryOperator"; // a field's constraint object, or `$not`
|
// `$text: { … }` and the geo operators hold their own keys; anything else is a
|
||||||
|
// field's constraint object, or `$not`, where the field operators belong.
|
||||||
|
return SUB_DOCUMENT_QUERY_OPERATORS.has(inner.key) ? { mode: "operatorField", operator: inner.key } : { mode: "queryOperator" };
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
function classifyUpdate(scan: MongoCallScan, rootIndex: number): MongoCompletionMode {
|
/** Index of the innermost object container at or above `rootIndex` that is the value of `key`, or -1. */
|
||||||
const inner = innermost(scan);
|
function findContainerIndex(scan: MongoCallScan, rootIndex: number, key: string): number {
|
||||||
if (!inner || innerDepth(scan, rootIndex) < 0) return "none";
|
for (let i = scan.stack.length - 1; i > rootIndex; i--) {
|
||||||
if (scan.inValue) return scan.inString ? "none" : "value";
|
const container = scan.stack[i];
|
||||||
if (inner.kind !== "object") return "none";
|
if (container?.kind === "object" && container.key === key) return i;
|
||||||
if (innerDepth(scan, rootIndex) === 0) return "updateOperator";
|
}
|
||||||
|
return -1;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Keywords whose value is itself a schema. */
|
||||||
|
const SCHEMA_NESTING_KEYWORDS = new Set(["items", "additionalItems", "additionalProperties", "not"]);
|
||||||
|
/** Keywords whose value is a list of schemas. */
|
||||||
|
const SCHEMA_LIST_KEYWORDS = new Set(["allOf", "anyOf", "oneOf"]);
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Inside `$jsonSchema: { … }`: the schema object and every schema nested in it
|
||||||
|
* (`properties.<field>`, `items`, an `allOf` branch) take the JSON Schema keywords,
|
||||||
|
* `properties` itself names fields, and `bsonType` / `type` take the BSON aliases.
|
||||||
|
*/
|
||||||
|
function classifyJsonSchema(scan: MongoCallScan, schemaIndex: number): MongoCursorClass {
|
||||||
|
const inner = innermost(scan);
|
||||||
|
if (!inner) return { mode: "none" };
|
||||||
const parent = scan.stack[scan.stack.length - 2];
|
const parent = scan.stack[scan.stack.length - 2];
|
||||||
if (parent?.key === "$push" || parent?.key === "$addToSet") return "pushModifier";
|
const keywords: MongoCursorClass = { mode: "operatorField", operator: "$jsonSchema" };
|
||||||
if (inner.key && UPDATE_OPERATOR_LABELS.has(inner.key)) return "field";
|
|
||||||
return "field";
|
if (inner.kind === "array") {
|
||||||
|
if (inner.key === "bsonType" || inner.key === "type") return { mode: "enumValue", enumKey: "bsonType" };
|
||||||
|
if (inner.key === "required" && scan.inString) return { mode: "fieldPath" };
|
||||||
|
return { mode: "none" };
|
||||||
|
}
|
||||||
|
if (inner.kind !== "object") return { mode: "none" };
|
||||||
|
if (scan.inValue) {
|
||||||
|
if (scan.valueKey === "bsonType" || scan.valueKey === "type") return { mode: "enumValue", enumKey: "bsonType" };
|
||||||
|
return { mode: "none" };
|
||||||
|
}
|
||||||
|
|
||||||
|
if (scan.stack.length - 1 === schemaIndex) return keywords;
|
||||||
|
if (inner.key === "properties") return { mode: "field" };
|
||||||
|
if (inner.key === null) return parent?.kind === "array" && SCHEMA_LIST_KEYWORDS.has(parent.key ?? "") ? keywords : { mode: "none" };
|
||||||
|
if (SCHEMA_NESTING_KEYWORDS.has(inner.key)) return keywords;
|
||||||
|
if (parent?.key === "properties" || parent?.key === "patternProperties") return keywords;
|
||||||
|
return { mode: "none" };
|
||||||
|
}
|
||||||
|
|
||||||
|
function classifyUpdate(scan: MongoCallScan, rootIndex: number): MongoCursorClass {
|
||||||
|
const inner = innermost(scan);
|
||||||
|
if (!inner || innerDepth(scan, rootIndex) < 0) return { mode: "none" };
|
||||||
|
const parent = scan.stack[scan.stack.length - 2];
|
||||||
|
if (scan.inValue) {
|
||||||
|
// `$currentDate: { at: { $type: "timestamp" } }`.
|
||||||
|
if (scan.valueKey === "$type" && parent?.key === "$currentDate") return { mode: "enumValue", enumKey: "currentDateType" };
|
||||||
|
return { mode: scan.inString ? "none" : "value" };
|
||||||
|
}
|
||||||
|
if (inner.kind !== "object") return { mode: "none" };
|
||||||
|
if (innerDepth(scan, rootIndex) === 0) return { mode: "updateOperator" };
|
||||||
|
|
||||||
|
if (parent?.key === "$push" || parent?.key === "$addToSet") return { mode: "pushModifier" };
|
||||||
|
if (parent?.key === "$currentDate") return { mode: "operatorField", operator: "$currentDate" };
|
||||||
|
return { mode: "field" };
|
||||||
}
|
}
|
||||||
|
|
||||||
function classifyDocument(scan: MongoCallScan, rootIndex: number): MongoCompletionMode {
|
function classifyDocument(scan: MongoCallScan, rootIndex: number): MongoCompletionMode {
|
||||||
@@ -805,18 +903,46 @@ function classifyKeyMap(scan: MongoCallScan, rootIndex: number, keyMap: string):
|
|||||||
/** 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. */
|
||||||
const FIELD_MAP_OPTION_KEYS = new Set(["sort", "projection"]);
|
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" };
|
||||||
|
|
||||||
function classifyMethodOptions(method: string, scan: MongoCallScan): MongoCursorClass {
|
function classifyMethodOptions(method: string, scan: MongoCallScan): MongoCursorClass {
|
||||||
const inner = innermost(scan);
|
const inner = innermost(scan);
|
||||||
const depth = innerDepth(scan, 0);
|
const depth = innerDepth(scan, 0);
|
||||||
if (!inner || depth < 0) return { mode: "none" };
|
if (!inner || depth < 0) return { mode: "none" };
|
||||||
|
|
||||||
// `{ sort: { … } }` and `{ projection: { … } }` are field maps one level in.
|
if (depth === 0) {
|
||||||
if (depth === 1 && inner.kind === "object" && FIELD_MAP_OPTION_KEYS.has(inner.key ?? "")) {
|
if (scan.inValue) {
|
||||||
if (!scan.inValue) return { mode: "field", method };
|
const enumKey = OPTION_VALUE_ENUMS[scan.valueKey ?? ""];
|
||||||
return { mode: scan.inString ? "none" : "keyMapValue", method, keyMap: inner.key ?? "" };
|
return enumKey ? { mode: "enumValue", enumKey, method } : { mode: "none" };
|
||||||
|
}
|
||||||
|
return { mode: inner.kind === "object" ? "methodOption" : "none", method };
|
||||||
}
|
}
|
||||||
if (depth !== 0 || scan.inValue) return { mode: "none" };
|
|
||||||
return { mode: inner.kind === "object" ? "methodOption" : "none", method };
|
// Which option's value holds the cursor, however deep.
|
||||||
|
const option = scan.stack[1]?.key ?? "";
|
||||||
|
// `{ sort: { … } }` and `{ projection: { … } }` are field maps one level in.
|
||||||
|
if (depth === 1 && inner.kind === "object" && FIELD_MAP_OPTION_KEYS.has(option)) {
|
||||||
|
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 };
|
||||||
|
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 {
|
||||||
|
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 ?? ""];
|
||||||
|
return enumKey ? { mode: "enumValue", enumKey } : { mode: "none" };
|
||||||
|
}
|
||||||
|
return { mode: "operatorField", operator: "collation" };
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -849,11 +975,11 @@ function classifyBulkWriteOperations(scan: MongoCallScan): MongoCursorClass {
|
|||||||
const fieldIndex = arrayIndex + 3;
|
const fieldIndex = arrayIndex + 3;
|
||||||
switch (scan.stack[fieldIndex]?.key ?? "") {
|
switch (scan.stack[fieldIndex]?.key ?? "") {
|
||||||
case "filter":
|
case "filter":
|
||||||
return { mode: classifyFilter(scan, fieldIndex), bulkWriteOperation: operation };
|
return { ...classifyFilter(scan, fieldIndex), bulkWriteOperation: operation };
|
||||||
case "arrayFilters":
|
case "arrayFilters":
|
||||||
return { mode: classifyFilter(scan, fieldIndex + 1), bulkWriteOperation: operation };
|
return { ...classifyFilter(scan, fieldIndex + 1), bulkWriteOperation: operation };
|
||||||
case "update":
|
case "update":
|
||||||
return { mode: classifyUpdate(scan, fieldIndex), bulkWriteOperation: operation };
|
return { ...classifyUpdate(scan, fieldIndex), bulkWriteOperation: operation };
|
||||||
case "document":
|
case "document":
|
||||||
case "replacement":
|
case "replacement":
|
||||||
return { mode: classifyDocument(scan, fieldIndex), bulkWriteOperation: operation };
|
return { mode: classifyDocument(scan, fieldIndex), bulkWriteOperation: operation };
|
||||||
@@ -904,7 +1030,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 { ...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 { ...classifyKeyMap(scan, bodyIndex, "sort"), 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 };
|
||||||
@@ -1065,8 +1191,9 @@ function methodItems(prefix: string): MongoCompletionItem[] {
|
|||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
function cursorMethodItems(prefix: string, countable: boolean): MongoCompletionItem[] {
|
/** `collation()` is a find-cursor method only, so it is withheld after `aggregate(…)`. */
|
||||||
const methods = countable ? [...CURSOR_METHODS, CURSOR_COUNT_METHOD] : [...CURSOR_METHODS];
|
function cursorMethodItems(prefix: string, countable: boolean, find: boolean): MongoCompletionItem[] {
|
||||||
|
const methods = [...CURSOR_METHODS.filter((method) => find || method.label !== "collation"), ...(countable ? [CURSOR_COUNT_METHOD] : [])];
|
||||||
return dedupeAndSort(
|
return dedupeAndSort(
|
||||||
methods
|
methods
|
||||||
.filter((method) => matchesFuzzyPrefix(method.label, prefix))
|
.filter((method) => matchesFuzzyPrefix(method.label, prefix))
|
||||||
@@ -1075,7 +1202,7 @@ function cursorMethodItems(prefix: string, countable: boolean): MongoCompletionI
|
|||||||
type: "function" as const,
|
type: "function" as const,
|
||||||
detail: method.detail,
|
detail: method.detail,
|
||||||
apply: method.apply,
|
apply: method.apply,
|
||||||
boost: method.label === "limit" ? 150 : method.label === "sort" ? 140 : method.label === "skip" ? 130 : 120,
|
boost: method.label === "limit" ? 150 : method.label === "sort" ? 140 : method.label === "skip" ? 130 : method.label === "collation" ? 115 : 120,
|
||||||
})),
|
})),
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
@@ -1128,6 +1255,27 @@ function fieldRefItems(prefix: string, fields: MongoCompletionField[], baseBoost
|
|||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Values from a fixed set, in or out of quotes: `$type: "` and `$type: ` both offer
|
||||||
|
* `string`. Inside a quote the item supplies only the bare value and consumes the
|
||||||
|
* closing quote; outside it, the authored literal, quotes included.
|
||||||
|
*/
|
||||||
|
function enumValueItems(prefix: string, values: readonly MongoOperatorSpec[], category: string): MongoCompletionItem[] {
|
||||||
|
const quoted = prefix.startsWith('"') || prefix.startsWith("'");
|
||||||
|
const normalizedPrefix = normalizeMongoKeyPrefix(prefix);
|
||||||
|
return values
|
||||||
|
.filter((value) => matchesFuzzyPrefix(value.label, normalizedPrefix))
|
||||||
|
.filter((value) => !quoted || value.apply.startsWith('"'))
|
||||||
|
.map((value) => ({
|
||||||
|
label: value.label,
|
||||||
|
type: "keyword" as const,
|
||||||
|
detail: value.detail,
|
||||||
|
info: `${category} value`,
|
||||||
|
apply: quoted ? quoteMongoString(value.label, prefix) : value.apply,
|
||||||
|
boost: startsWithPrefix(value.label, normalizedPrefix) ? 120 : 90,
|
||||||
|
}));
|
||||||
|
}
|
||||||
|
|
||||||
function specItems(specs: readonly MongoOperatorSpec[], prefix: string, category: string, baseBoost: number): MongoCompletionItem[] {
|
function specItems(specs: readonly MongoOperatorSpec[], prefix: string, category: string, baseBoost: number): MongoCompletionItem[] {
|
||||||
const normalizedPrefix = normalizeMongoKeyPrefix(prefix);
|
const normalizedPrefix = normalizeMongoKeyPrefix(prefix);
|
||||||
return dedupeAndSort(
|
return dedupeAndSort(
|
||||||
@@ -1279,7 +1427,7 @@ function isAfterCollectionDot(beforeCursor: string): boolean {
|
|||||||
* `db.x.find(…).…` — and whether `count()` is still legal there, which it only
|
* `db.x.find(…).…` — and whether `count()` is still legal there, which it only
|
||||||
* is while no other cursor method has been chained on.
|
* is while no other cursor method has been chained on.
|
||||||
*/
|
*/
|
||||||
function matchCursorMethodDot(beforeCursor: string): { countable: boolean } | null {
|
function matchCursorMethodDot(beforeCursor: string): { find: boolean; countable: boolean } | null {
|
||||||
const collectionCall = new RegExp(String.raw`(?:^|[\s;(])${DB_ROOT}\.${COLLECTION_REF}\.(find|aggregate)\s*\(`, "g");
|
const collectionCall = new RegExp(String.raw`(?:^|[\s;(])${DB_ROOT}\.${COLLECTION_REF}\.(find|aggregate)\s*\(`, "g");
|
||||||
let lastMatch: RegExpExecArray | null = null;
|
let lastMatch: RegExpExecArray | null = null;
|
||||||
let match: RegExpExecArray | null;
|
let match: RegExpExecArray | null;
|
||||||
@@ -1291,8 +1439,8 @@ function matchCursorMethodDot(beforeCursor: string): { countable: boolean } | nu
|
|||||||
if (closeParen < 0) return null;
|
if (closeParen < 0) return null;
|
||||||
|
|
||||||
const chain = beforeCursor.slice(closeParen + 1);
|
const chain = beforeCursor.slice(closeParen + 1);
|
||||||
if (!/^(?:\s*\.\s*(?:sort|skip|limit)\s*\([^()]*\))*\s*\.\s*[\w$-]*$/.test(chain)) return null;
|
if (!/^(?:\s*\.\s*(?:sort|skip|limit|collation)\s*\([^()]*\))*\s*\.\s*[\w$-]*$/.test(chain)) return null;
|
||||||
return { countable: lastMatch[1] === "find" && /^\s*\.\s*[\w$-]*$/.test(chain) };
|
return { find: lastMatch[1] === "find", countable: lastMatch[1] === "find" && /^\s*\.\s*[\w$-]*$/.test(chain) };
|
||||||
}
|
}
|
||||||
|
|
||||||
function findMatchingParen(text: string, openIndex: number): number {
|
function findMatchingParen(text: string, openIndex: number): number {
|
||||||
|
|||||||
@@ -325,6 +325,167 @@ export const KEY_MAP_VALUES: Record<string, MongoOperatorSpec[]> = {
|
|||||||
* Both lists are exactly what the shell parser accepts: it rejects an unknown operation key and
|
* 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.
|
* an unknown field inside one, so anything extra here would complete into a command that fails.
|
||||||
*/
|
*/
|
||||||
|
const GEO_NEAR_KEYS: Spec[] = [
|
||||||
|
["$geometry", "GeoJSON point to measure distance from", '$geometry: { type: "Point", coordinates: [${}, ${}] }'],
|
||||||
|
["$maxDistance", "Farthest match, in meters", "$maxDistance: ${}"],
|
||||||
|
["$minDistance", "Nearest match, in meters", "$minDistance: ${}"],
|
||||||
|
];
|
||||||
|
|
||||||
|
const JSON_SCHEMA_KEYWORDS: Spec[] = [
|
||||||
|
["bsonType", "BSON type the value must have", 'bsonType: "${string}"'],
|
||||||
|
["type", "JSON Schema type the value must have", 'type: "${string}"'],
|
||||||
|
["enum", "Values the field may take", "enum: [${}]"],
|
||||||
|
["required", "Fields that must be present", 'required: ["${field}"]'],
|
||||||
|
["properties", "Schema for each named field", "properties: { ${field}: {} }"],
|
||||||
|
["additionalProperties", "Allow, forbid or constrain fields not listed in properties", "additionalProperties: false"],
|
||||||
|
["patternProperties", "Schema for fields whose name matches a pattern", 'patternProperties: { "${pattern}": {} }'],
|
||||||
|
["minProperties", "Minimum number of fields", "minProperties: ${}"],
|
||||||
|
["maxProperties", "Maximum number of fields", "maxProperties: ${}"],
|
||||||
|
["items", "Schema for array elements", "items: {}"],
|
||||||
|
["additionalItems", "Allow or constrain elements beyond the listed item schemas", "additionalItems: false"],
|
||||||
|
["minItems", "Minimum array length", "minItems: ${}"],
|
||||||
|
["maxItems", "Maximum array length", "maxItems: ${}"],
|
||||||
|
["uniqueItems", "Reject duplicate array elements", "uniqueItems: true"],
|
||||||
|
["minimum", "Smallest allowed number", "minimum: ${}"],
|
||||||
|
["maximum", "Largest allowed number", "maximum: ${}"],
|
||||||
|
["exclusiveMinimum", "Treat minimum as exclusive", "exclusiveMinimum: true"],
|
||||||
|
["exclusiveMaximum", "Treat maximum as exclusive", "exclusiveMaximum: true"],
|
||||||
|
["multipleOf", "Number must be a multiple of this", "multipleOf: ${}"],
|
||||||
|
["minLength", "Minimum string length", "minLength: ${}"],
|
||||||
|
["maxLength", "Maximum string length", "maxLength: ${}"],
|
||||||
|
["pattern", "Regular expression the string must match", 'pattern: "${}"'],
|
||||||
|
["allOf", "Must match every listed schema", "allOf: [{}]"],
|
||||||
|
["anyOf", "Must match at least one listed schema", "anyOf: [{}]"],
|
||||||
|
["oneOf", "Must match exactly one listed schema", "oneOf: [{}]"],
|
||||||
|
["not", "Must not match this schema", "not: {}"],
|
||||||
|
["dependencies", "Fields or schemas required when a field is present", 'dependencies: { ${field}: ["${other}"] }'],
|
||||||
|
["title", "Schema title", 'title: "${}"'],
|
||||||
|
["description", "Schema description", 'description: "${}"'],
|
||||||
|
];
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Keys of an operator's own sub-document, where the field operators `{ field: { $… } }`
|
||||||
|
* takes would be wrong: `$text: { $search }`, `$near: { $geometry }`. `$jsonSchema`
|
||||||
|
* and every schema nested in it take the JSON Schema keywords; `collation` covers
|
||||||
|
* the cursor method and the option key alike; `$currentDate` is the per-field
|
||||||
|
* object of the update operator.
|
||||||
|
*/
|
||||||
|
export const OPERATOR_SUB_KEYS: Record<string, MongoOperatorSpec[]> = {
|
||||||
|
$text: specs([
|
||||||
|
["$search", "Words or phrases to search for", '$search: "${text}"'],
|
||||||
|
["$language", "Language for stemming and stop words", '$language: "${en}"'],
|
||||||
|
["$caseSensitive", "Match case exactly", "$caseSensitive: true"],
|
||||||
|
["$diacriticSensitive", "Match diacritics exactly", "$diacriticSensitive: true"],
|
||||||
|
]),
|
||||||
|
$geoWithin: specs([
|
||||||
|
["$geometry", "GeoJSON polygon or multipolygon to fall within", '$geometry: { type: "Polygon", coordinates: [${}] }'],
|
||||||
|
["$box", "Rectangle from its bottom-left and top-right corners", "$box: [[${}, ${}], [${}, ${}]]"],
|
||||||
|
["$polygon", "Polygon from a list of points", "$polygon: [[${}, ${}]]"],
|
||||||
|
["$center", "Circle from a center point and a radius", "$center: [[${}, ${}], ${}]"],
|
||||||
|
["$centerSphere", "Spherical circle from a center point and a radius in radians", "$centerSphere: [[${}, ${}], ${}]"],
|
||||||
|
]),
|
||||||
|
$geoIntersects: specs([["$geometry", "GeoJSON geometry to intersect", '$geometry: { type: "${Polygon}", coordinates: [${}] }']]),
|
||||||
|
$near: specs(GEO_NEAR_KEYS),
|
||||||
|
$nearSphere: specs(GEO_NEAR_KEYS),
|
||||||
|
$geometry: specs([
|
||||||
|
["type", "GeoJSON geometry type", 'type: "${Point}"'],
|
||||||
|
["coordinates", "Coordinates, longitude first", "coordinates: [${}, ${}]"],
|
||||||
|
]),
|
||||||
|
$jsonSchema: specs(JSON_SCHEMA_KEYWORDS),
|
||||||
|
$currentDate: specs([["$type", "Store a Date or a Timestamp", '$type: "${date}"']]),
|
||||||
|
collation: specs([
|
||||||
|
["locale", 'ICU locale, such as "en" or "zh"', 'locale: "${en}"'],
|
||||||
|
["strength", "Comparison level, 1 (base letters) to 5 (identical)", "strength: 2"],
|
||||||
|
["caseLevel", "Compare case as its own level", "caseLevel: false"],
|
||||||
|
["caseFirst", "Order uppercase before or after lowercase", 'caseFirst: "${off}"'],
|
||||||
|
["numericOrdering", "Compare digit sequences as numbers", "numericOrdering: true"],
|
||||||
|
["alternate", "Whether spaces and punctuation are base characters", 'alternate: "${non-ignorable}"'],
|
||||||
|
["maxVariable", 'Which characters "shifted" ignores', 'maxVariable: "${punct}"'],
|
||||||
|
["backwards", "Compare secondary differences from the end", "backwards: false"],
|
||||||
|
["normalization", "Normalize text to Unicode NFD first", "normalization: false"],
|
||||||
|
]),
|
||||||
|
};
|
||||||
|
|
||||||
|
const BSON_TYPE_ALIASES: Spec[] = [
|
||||||
|
["string", "UTF-8 string", '"string"'],
|
||||||
|
["objectId", "ObjectId", '"objectId"'],
|
||||||
|
["date", "Date", '"date"'],
|
||||||
|
["bool", "Boolean", '"bool"'],
|
||||||
|
["int", "32-bit integer", '"int"'],
|
||||||
|
["long", "64-bit integer", '"long"'],
|
||||||
|
["double", "64-bit floating point", '"double"'],
|
||||||
|
["decimal", "128-bit decimal", '"decimal"'],
|
||||||
|
["number", "Any numeric type", '"number"'],
|
||||||
|
["object", "Embedded document", '"object"'],
|
||||||
|
["array", "Array", '"array"'],
|
||||||
|
["null", "Null", '"null"'],
|
||||||
|
["binData", "Binary data", '"binData"'],
|
||||||
|
["regex", "Regular expression", '"regex"'],
|
||||||
|
["timestamp", "Timestamp", '"timestamp"'],
|
||||||
|
["javascript", "JavaScript code", '"javascript"'],
|
||||||
|
["minKey", "MinKey", '"minKey"'],
|
||||||
|
["maxKey", "MaxKey", '"maxKey"'],
|
||||||
|
];
|
||||||
|
|
||||||
|
/**
|
||||||
|
* The fixed set a value position accepts, by the name the classifier gives that
|
||||||
|
* position. String values carry their quotes in `apply`, so an unquoted cursor
|
||||||
|
* gets a well-formed literal; numbers do not.
|
||||||
|
*/
|
||||||
|
export const ENUM_VALUES: Record<string, MongoOperatorSpec[]> = {
|
||||||
|
$type: specs(BSON_TYPE_ALIASES),
|
||||||
|
bsonType: specs(BSON_TYPE_ALIASES),
|
||||||
|
$options: specs([
|
||||||
|
["i", "Case-insensitive", '"i"'],
|
||||||
|
["m", "^ and $ match at line breaks", '"m"'],
|
||||||
|
["x", "Ignore whitespace and # comments in the pattern", '"x"'],
|
||||||
|
["s", "Dot matches newlines", '"s"'],
|
||||||
|
["u", "Unicode character classes", '"u"'],
|
||||||
|
]),
|
||||||
|
geometryType: specs([
|
||||||
|
["Point", "Single position", '"Point"'],
|
||||||
|
["LineString", "Sequence of positions", '"LineString"'],
|
||||||
|
["Polygon", "Closed ring of positions", '"Polygon"'],
|
||||||
|
["MultiPoint", "Several points", '"MultiPoint"'],
|
||||||
|
["MultiLineString", "Several line strings", '"MultiLineString"'],
|
||||||
|
["MultiPolygon", "Several polygons", '"MultiPolygon"'],
|
||||||
|
["GeometryCollection", "Mixed geometries", '"GeometryCollection"'],
|
||||||
|
]),
|
||||||
|
returnDocument: specs([
|
||||||
|
["after", "Return the document as modified", '"after"'],
|
||||||
|
["before", "Return the document as it was", '"before"'],
|
||||||
|
]),
|
||||||
|
explain: specs([
|
||||||
|
["queryPlanner", "The chosen plan, without running it", '"queryPlanner"'],
|
||||||
|
["executionStats", "The chosen plan and its execution statistics", '"executionStats"'],
|
||||||
|
["allPlansExecution", "Every candidate plan and its statistics", '"allPlansExecution"'],
|
||||||
|
]),
|
||||||
|
currentDateType: specs([
|
||||||
|
["date", "Store a Date", '"date"'],
|
||||||
|
["timestamp", "Store a Timestamp", '"timestamp"'],
|
||||||
|
]),
|
||||||
|
caseFirst: specs([
|
||||||
|
["off", "Lowercase and uppercase in code point order", '"off"'],
|
||||||
|
["upper", "Uppercase first", '"upper"'],
|
||||||
|
["lower", "Lowercase first", '"lower"'],
|
||||||
|
]),
|
||||||
|
alternate: specs([
|
||||||
|
["non-ignorable", "Spaces and punctuation count as base characters", '"non-ignorable"'],
|
||||||
|
["shifted", "Spaces and punctuation are ignored up to maxVariable", '"shifted"'],
|
||||||
|
]),
|
||||||
|
maxVariable: specs([
|
||||||
|
["punct", "Shift both spaces and punctuation", '"punct"'],
|
||||||
|
["space", "Shift spaces only", '"space"'],
|
||||||
|
]),
|
||||||
|
strength: specs([
|
||||||
|
["1", "Base letters only", "1"],
|
||||||
|
["2", "Base letters and accents", "2"],
|
||||||
|
["3", "Base letters, accents and case", "3"],
|
||||||
|
["4", "Also punctuation, with alternate: shifted", "4"],
|
||||||
|
["5", "Identical, including code points", "5"],
|
||||||
|
]),
|
||||||
|
};
|
||||||
|
|
||||||
export const BULK_WRITE_OPERATIONS: MongoOperatorSpec[] = specs([
|
export const BULK_WRITE_OPERATIONS: MongoOperatorSpec[] = specs([
|
||||||
["insertOne", "Insert one document", "insertOne: { document: { ${} } }"],
|
["insertOne", "Insert one document", "insertOne: { document: { ${} } }"],
|
||||||
["updateOne", "Update the first matching document", "updateOne: { filter: { ${} }, update: { $set: { ${} } } }"],
|
["updateOne", "Update the first matching document", "updateOne: { filter: { ${} }, update: { $set: { ${} } } }"],
|
||||||
|
|||||||
+146
-7
@@ -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, buildMongoCompletionItemsFromContext, getMongoCompletionContext, getMongoCompletionResultValidFor, getMongoDocumentQueryCompletionContext, 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, 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 { ACCUMULATORS, BULK_WRITE_OPERATION_FIELDS, BULK_WRITE_OPERATIONS, ENUM_VALUES, EXPRESSION_OPERATORS, EXTENDED_JSON_VALUES, KEY_MAP_VALUES, METHOD_OPTION_KEYS, OPERATOR_SUB_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"];
|
||||||
@@ -138,7 +138,7 @@ test("prioritizes common read helpers and keeps destructive helpers last", () =>
|
|||||||
assert.deepEqual(methodLabels.slice(0, 6), ["find", "findOne", "aggregate", "countDocuments", "estimatedDocumentCount", "distinct"]);
|
assert.deepEqual(methodLabels.slice(0, 6), ["find", "findOne", "aggregate", "countDocuments", "estimatedDocumentCount", "distinct"]);
|
||||||
assert.deepEqual(getCollectionMethodLabels.slice(0, 6), ["find", "findOne", "aggregate", "countDocuments", "estimatedDocumentCount", "distinct"]);
|
assert.deepEqual(getCollectionMethodLabels.slice(0, 6), ["find", "findOne", "aggregate", "countDocuments", "estimatedDocumentCount", "distinct"]);
|
||||||
assert.deepEqual(methodLabels.slice(-3), ["dropIndex", "dropIndexes", "drop"]);
|
assert.deepEqual(methodLabels.slice(-3), ["dropIndex", "dropIndexes", "drop"]);
|
||||||
assert.deepEqual(labels("db.users.find({})."), ["limit", "sort", "skip", "count", "explain"]);
|
assert.deepEqual(labels("db.users.find({})."), ["limit", "sort", "skip", "count", "explain", "collation"]);
|
||||||
});
|
});
|
||||||
|
|
||||||
test("keeps dotted collection names ahead of methods until the collection is resolved", () => {
|
test("keeps dotted collection names ahead of methods until the collection is resolved", () => {
|
||||||
@@ -163,7 +163,7 @@ test("suggests cursor methods after find result chains", () => {
|
|||||||
|
|
||||||
assert.deepEqual(
|
assert.deepEqual(
|
||||||
allItems.map((item) => item.label),
|
allItems.map((item) => item.label),
|
||||||
["limit", "sort", "skip", "count", "explain"],
|
["limit", "sort", "skip", "count", "explain", "collation"],
|
||||||
);
|
);
|
||||||
assert.deepEqual(
|
assert.deepEqual(
|
||||||
prefixedItems.map((item) => item.label),
|
prefixedItems.map((item) => item.label),
|
||||||
@@ -171,7 +171,7 @@ test("suggests cursor methods after find result chains", () => {
|
|||||||
);
|
);
|
||||||
assert.deepEqual(
|
assert.deepEqual(
|
||||||
formattedChainItems.map((item) => item.label),
|
formattedChainItems.map((item) => item.label),
|
||||||
["limit", "sort", "skip", "count", "explain"],
|
["limit", "sort", "skip", "count", "explain", "collation"],
|
||||||
);
|
);
|
||||||
assert.deepEqual(
|
assert.deepEqual(
|
||||||
formattedPrefixedItems.map((item) => item.label),
|
formattedPrefixedItems.map((item) => item.label),
|
||||||
@@ -633,8 +633,6 @@ test("offers nothing rather than top-level snippets inside an unmodelled argumen
|
|||||||
for (const text of [
|
for (const text of [
|
||||||
"db.users.find({}).limit(",
|
"db.users.find({}).limit(",
|
||||||
"db.users.find({}).skip(",
|
"db.users.find({}).skip(",
|
||||||
"db.users.find({}).explain(",
|
|
||||||
"db.users.find({}).collation({ ",
|
|
||||||
"db.users.drop(",
|
"db.users.drop(",
|
||||||
"db.users.renameCollection(",
|
"db.users.renameCollection(",
|
||||||
'db.users.dropIndex("',
|
'db.users.dropIndex("',
|
||||||
@@ -792,6 +790,147 @@ test("completes database names after use and inside getSiblingDB", () => {
|
|||||||
assert.deepEqual(labels("// use ", { databases }), []);
|
assert.deepEqual(labels("// use ", { databases }), []);
|
||||||
});
|
});
|
||||||
|
|
||||||
|
test("completes the keys of an operator's own sub-document", () => {
|
||||||
|
// `{ field: { $… } }` takes the field operators, but `$text` and the geo operators hold
|
||||||
|
// documents with their own keys, where `$gt` and friends are nonsense.
|
||||||
|
assert.deepEqual(labels("db.users.find({ $text: { ", { fields }), ["$caseSensitive", "$diacriticSensitive", "$language", "$search"]);
|
||||||
|
assert.deepEqual(labels('db.users.find({ $text: { $search: "a", $lang', { fields }), ["$language"]);
|
||||||
|
assert.deepEqual(labels("db.users.find({ loc: { $geoWithin: { ", { fields }), ["$box", "$center", "$centerSphere", "$geometry", "$polygon"]);
|
||||||
|
assert.deepEqual(labels("db.users.find({ loc: { $geoIntersects: { ", { fields }), ["$geometry"]);
|
||||||
|
assert.deepEqual(labels("db.users.find({ loc: { $near: { ", { fields }), ["$geometry", "$maxDistance", "$minDistance"]);
|
||||||
|
assert.deepEqual(labels("db.users.find({ loc: { $nearSphere: { ", { fields }), ["$geometry", "$maxDistance", "$minDistance"]);
|
||||||
|
assert.deepEqual(labels("db.users.find({ loc: { $near: { $geometry: { ", { fields }), ["coordinates", "type"]);
|
||||||
|
// The same filter positions inside a stage, a bulk operation and the document browser's filter bar.
|
||||||
|
assert.deepEqual(labels("db.users.aggregate([{ $match: { $text: { ", { fields }), ["$caseSensitive", "$diacriticSensitive", "$language", "$search"]);
|
||||||
|
assert.deepEqual(labels("db.users.bulkWrite([{ deleteMany: { filter: { $text: { ", { fields }), ["$caseSensitive", "$diacriticSensitive", "$language", "$search"]);
|
||||||
|
const bar = getMongoDocumentQueryCompletionContext("{ $text: { ", "{ $text: { ".length, "filter");
|
||||||
|
assert.deepEqual(buildMongoCompletionItemsFromContext(bar).map((item) => item.label), ["$caseSensitive", "$diacriticSensitive", "$language", "$search"]);
|
||||||
|
// A field that happens to be called `text` is still a field, and `$not` still wraps field operators.
|
||||||
|
assert.ok(labels("db.users.find({ text: { $", { fields }).includes("$gt"));
|
||||||
|
assert.ok(labels("db.users.find({ name: { $not: { $", { fields }).includes("$regex"));
|
||||||
|
// Inside a value string the engine stays quiet, as everywhere else.
|
||||||
|
assert.deepEqual(labels('db.users.find({ $text: { $search: "', { fields }), []);
|
||||||
|
|
||||||
|
// `$currentDate` names fields, and each field's object takes `$type`.
|
||||||
|
assert.deepEqual(labels("db.users.updateOne({}, { $currentDate: { ", { fields }).slice(0, 2), ["_id", "createdAt"]);
|
||||||
|
assert.deepEqual(labels("db.users.updateOne({}, { $currentDate: { at: { ", { fields }), ["$type"]);
|
||||||
|
});
|
||||||
|
|
||||||
|
test("completes JSON Schema keywords inside $jsonSchema", () => {
|
||||||
|
const keywords = labels("db.users.find({ $jsonSchema: { ", { fields });
|
||||||
|
for (const keyword of ["bsonType", "required", "properties", "items", "allOf", "not", "pattern", "minimum"]) assert.ok(keywords.includes(keyword), keyword);
|
||||||
|
assert.ok(!keywords.includes("$gt"), "field operators do not belong in a schema");
|
||||||
|
// `properties` names fields; each named field's object is a schema again, however deep.
|
||||||
|
assert.deepEqual(labels("db.users.find({ $jsonSchema: { properties: { ", { fields }), ["_id", "createdAt", "name", "profile.email"]);
|
||||||
|
assert.deepEqual(labels("db.users.find({ $jsonSchema: { properties: { name: { ", { fields }), keywords);
|
||||||
|
assert.deepEqual(labels("db.users.find({ $jsonSchema: { properties: { tags: { items: { ", { fields }), keywords);
|
||||||
|
assert.deepEqual(labels("db.users.find({ $jsonSchema: { not: { ", { fields }), keywords);
|
||||||
|
assert.deepEqual(labels("db.users.find({ $jsonSchema: { anyOf: [{ ", { fields }), keywords);
|
||||||
|
assert.deepEqual(labels('db.users.find({ $jsonSchema: { patternProperties: { "^a": { ', { fields }), keywords);
|
||||||
|
// `required` lists field paths; `bsonType` / `type` take the BSON aliases, alone or in a list.
|
||||||
|
assert.deepEqual(labels('db.users.find({ $jsonSchema: { required: ["', { fields }), ["_id", "createdAt", "name", "profile.email"]);
|
||||||
|
assert.ok(labels('db.users.find({ $jsonSchema: { properties: { name: { bsonType: "', { fields }).includes("objectId"));
|
||||||
|
assert.ok(labels('db.users.find({ $jsonSchema: { properties: { name: { type: "', { fields }).includes("string"));
|
||||||
|
assert.ok(labels('db.users.find({ $jsonSchema: { bsonType: ["', { fields }).includes("null"));
|
||||||
|
// Other values, and lists of values, are the user's own.
|
||||||
|
assert.deepEqual(labels('db.users.find({ $jsonSchema: { properties: { name: { description: "', { fields }), []);
|
||||||
|
assert.deepEqual(labels("db.users.find({ $jsonSchema: { properties: { name: { enum: [", { fields }), []);
|
||||||
|
// The `validator` of an index's partial filter is an ordinary filter, so the schema works there too.
|
||||||
|
assert.deepEqual(labels("db.users.createIndex({ a: 1 }, { partialFilterExpression: { $jsonSchema: { properties: { name: { ", { fields }), keywords);
|
||||||
|
});
|
||||||
|
|
||||||
|
test("completes enumerated string values in and out of quotes", () => {
|
||||||
|
const types = labels('db.users.find({ name: { $type: "', { fields });
|
||||||
|
for (const alias of ["string", "objectId", "date", "int", "long", "double", "decimal", "number", "array", "null"]) assert.ok(types.includes(alias), alias);
|
||||||
|
assert.deepEqual(labels('db.users.find({ name: { $type: "obj', { fields }), ["objectId", "object"]);
|
||||||
|
assert.deepEqual(labels('db.users.find({ name: { $type: ["', { fields }), types);
|
||||||
|
// Outside a quote the value arrives quoted; inside, bare, consuming the closing quote already typed.
|
||||||
|
assert.equal(buildMongoCompletionItems("db.users.find({ name: { $type: ", 31, { fields })[0]?.apply, '"string"');
|
||||||
|
assert.equal(buildMongoCompletionItems('db.users.find({ name: { $type: "', 32, { fields })[0]?.apply, '"string"');
|
||||||
|
assert.equal(buildMongoCompletionItems("db.users.find({ name: { $type: 'str", 35, { fields })[0]?.apply, "'string'");
|
||||||
|
assert.equal(getMongoCompletionContext('db.users.find({ name: { $type: "str" } })', 35).replaceClosingQuote, '"');
|
||||||
|
assert.deepEqual(labels('db.users.find({ name: { $regex: "a", $options: "', { fields }), ["i", "m", "x", "s", "u"]);
|
||||||
|
assert.deepEqual(labels('db.users.find({ loc: { $near: { $geometry: { type: "', { fields }), ["Point", "LineString", "Polygon", "MultiPoint", "MultiLineString", "MultiPolygon", "GeometryCollection"]);
|
||||||
|
assert.deepEqual(labels('db.users.findOneAndUpdate({}, { $set: {} }, { returnDocument: "'), ["after", "before"]);
|
||||||
|
assert.deepEqual(labels("db.users.findOneAndUpdate({}, { $set: {} }, { returnDocument: "), ["after", "before"]);
|
||||||
|
assert.deepEqual(labels('db.users.updateOne({}, { $currentDate: { at: { $type: "'), ["date", "timestamp"]);
|
||||||
|
// `explain()` takes a verbosity, the one argument the find chain accepts a value for.
|
||||||
|
assert.deepEqual(labels('db.users.find({}).explain("'), ["queryPlanner", "executionStats", "allPlansExecution"]);
|
||||||
|
assert.deepEqual(labels("db.users.find({}).explain("), ["queryPlanner", "executionStats", "allPlansExecution"]);
|
||||||
|
assert.deepEqual(labels("db.users.find({}).explain(1, "), []);
|
||||||
|
// The document browser's filter bar shares the value sets.
|
||||||
|
const bar = getMongoDocumentQueryCompletionContext('{ name: { $type: "', '{ name: { $type: "'.length, "filter");
|
||||||
|
assert.deepEqual(buildMongoCompletionItemsFromContext(bar).map((item) => item.label), types);
|
||||||
|
});
|
||||||
|
|
||||||
|
test("completes the collation document wherever it appears", () => {
|
||||||
|
const keys = ["alternate", "backwards", "caseFirst", "caseLevel", "locale", "maxVariable", "normalization", "numericOrdering", "strength"];
|
||||||
|
assert.deepEqual(labels("db.users.find({}).collation({ "), keys);
|
||||||
|
assert.deepEqual(labels("db.users.aggregate([], { collation: { "), keys);
|
||||||
|
assert.deepEqual(labels("db.users.createIndex({ a: 1 }, { collation: { "), keys);
|
||||||
|
assert.deepEqual(labels('db.users.find({}).collation({ caseFirst: "'), ["off", "upper", "lower"]);
|
||||||
|
assert.deepEqual(labels('db.users.find({}).collation({ alternate: "'), ["non-ignorable", "shifted"]);
|
||||||
|
assert.deepEqual(labels('db.users.find({}).collation({ maxVariable: "'), ["punct", "space"]);
|
||||||
|
assert.deepEqual(labels("db.users.find({}).collation({ strength: "), ["1", "2", "3", "4", "5"]);
|
||||||
|
// Numbers are not offered inside a quote.
|
||||||
|
assert.deepEqual(labels('db.users.find({}).collation({ strength: "'), []);
|
||||||
|
assert.deepEqual(labels('db.users.find({}).collation({ locale: "'), []);
|
||||||
|
// The chain continues after collation(), and collation() is a find-cursor method only.
|
||||||
|
assert.deepEqual(labels('db.users.find({}).collation({ locale: "en" }).'), ["limit", "sort", "skip", "explain", "collation"]);
|
||||||
|
assert.ok(!labels("db.users.aggregate([]).").includes("collation"));
|
||||||
|
});
|
||||||
|
|
||||||
|
test("completes an index's partial filter as a filter", () => {
|
||||||
|
assert.deepEqual(labels("db.users.createIndex({ a: 1 }, { partialFilterExpression: { ", { fields }).slice(0, 3), ["_id", "createdAt", "name"]);
|
||||||
|
assert.ok(labels("db.users.createIndex({ a: 1 }, { partialFilterExpression: { name: { $", { fields }).includes("$exists"));
|
||||||
|
assert.ok(labels("db.users.createIndex({ a: 1 }, { partialFilterExpression: { name: { $exists: ", { fields }).includes("true"));
|
||||||
|
});
|
||||||
|
|
||||||
|
test("every suggested sub-document key and enumerated value parses in the position that offers it", () => {
|
||||||
|
const render = (apply: string) => apply.replace(/\$\{([^{}]*)\}/g, (_, name: string) => name || "1");
|
||||||
|
const keyCommands: Record<string, (body: string) => string> = {
|
||||||
|
$text: (body) => `db.users.find({ $text: { ${body} } })`,
|
||||||
|
$geoWithin: (body) => `db.users.find({ loc: { $geoWithin: { ${body} } } })`,
|
||||||
|
$geoIntersects: (body) => `db.users.find({ loc: { $geoIntersects: { ${body} } } })`,
|
||||||
|
$near: (body) => `db.users.find({ loc: { $near: { ${body} } } })`,
|
||||||
|
$nearSphere: (body) => `db.users.find({ loc: { $nearSphere: { ${body} } } })`,
|
||||||
|
$geometry: (body) => `db.users.find({ loc: { $near: { $geometry: { ${body} } } } })`,
|
||||||
|
$jsonSchema: (body) => `db.users.find({ $jsonSchema: { ${body} } })`,
|
||||||
|
$currentDate: (body) => `db.users.updateOne({}, { $currentDate: { at: { ${body} } } })`,
|
||||||
|
collation: (body) => `db.users.find({}).collation({ ${body} })`,
|
||||||
|
};
|
||||||
|
for (const [operator, keys] of Object.entries(OPERATOR_SUB_KEYS)) {
|
||||||
|
const build = keyCommands[operator];
|
||||||
|
assert.ok(build, `${operator} needs a sample command in this test`);
|
||||||
|
for (const key of keys) {
|
||||||
|
const command = build(render(key.apply));
|
||||||
|
assert.ok(parseMongoCommand(command), `${command} must parse`);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const valueCommands: Record<string, (value: string) => string> = {
|
||||||
|
$type: (value) => `db.users.find({ a: { $type: ${value} } })`,
|
||||||
|
bsonType: (value) => `db.users.find({ $jsonSchema: { bsonType: ${value} } })`,
|
||||||
|
$options: (value) => `db.users.find({ a: { $regex: "x", $options: ${value} } })`,
|
||||||
|
geometryType: (value) => `db.users.find({ loc: { $geoIntersects: { $geometry: { type: ${value}, coordinates: [] } } } })`,
|
||||||
|
returnDocument: (value) => `db.users.findOneAndUpdate({}, { $set: { a: 1 } }, { returnDocument: ${value} })`,
|
||||||
|
explain: (value) => `db.users.find({}).explain(${value})`,
|
||||||
|
currentDateType: (value) => `db.users.updateOne({}, { $currentDate: { at: { $type: ${value} } } })`,
|
||||||
|
caseFirst: (value) => `db.users.find({}).collation({ locale: "en", caseFirst: ${value} })`,
|
||||||
|
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} })`,
|
||||||
|
};
|
||||||
|
for (const [enumKey, values] of Object.entries(ENUM_VALUES)) {
|
||||||
|
const build = valueCommands[enumKey];
|
||||||
|
assert.ok(build, `${enumKey} needs a sample command in this test`);
|
||||||
|
for (const value of values) {
|
||||||
|
const command = build(value.apply);
|
||||||
|
assert.ok(parseMongoCommand(command), `${command} must parse`);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
test("suggests the use and db.version commands", () => {
|
test("suggests the use and db.version commands", () => {
|
||||||
assert.equal(buildMongoCompletionItems("us", 2).find((item) => item.label === "use")?.apply, "use ${database}");
|
assert.equal(buildMongoCompletionItems("us", 2).find((item) => item.label === "use")?.apply, "use ${database}");
|
||||||
// Database helpers stay reachable after `db.`, alongside the collection names.
|
// Database helpers stay reachable after `db.`, alongside the collection names.
|
||||||
@@ -812,7 +951,7 @@ test("ranks everyday operators above the long tail", () => {
|
|||||||
});
|
});
|
||||||
|
|
||||||
test("snippet templates use placeholder syntax CodeMirror actually honours", () => {
|
test("snippet templates use placeholder syntax CodeMirror actually honours", () => {
|
||||||
const templates = [...QUERY_OPERATORS, ...UPDATE_OPERATORS, ...PUSH_MODIFIERS, ...PIPELINE_STAGES, ...ACCUMULATORS, ...EXPRESSION_OPERATORS, ...VALUE_SNIPPETS, ...EXTENDED_JSON_VALUES, ...Object.values(STAGE_OPTION_KEYS).flat()];
|
const templates = [...QUERY_OPERATORS, ...UPDATE_OPERATORS, ...PUSH_MODIFIERS, ...PIPELINE_STAGES, ...ACCUMULATORS, ...EXPRESSION_OPERATORS, ...VALUE_SNIPPETS, ...EXTENDED_JSON_VALUES, ...Object.values(STAGE_OPTION_KEYS).flat(), ...Object.values(OPERATOR_SUB_KEYS).flat(), ...Object.values(ENUM_VALUES).flat()];
|
||||||
assert.ok(templates.length > 200);
|
assert.ok(templates.length > 200);
|
||||||
|
|
||||||
for (const { label, apply } of templates) {
|
for (const { label, apply } of templates) {
|
||||||
|
|||||||
Reference in new issue
Block a user