UNPKG

mongodb

Version:
605 lines (533 loc) • 19.5 kB
import type { Document } from '../bson'; import { type Connection } from '../cmap/connection'; import { CursorResponse, MongoDBResponse } from '../cmap/wire_protocol/responses'; import type { Collection } from '../collection'; import { type AbstractCursorOptions } from '../cursor/abstract_cursor'; import { type OneOrMore } from '../mongo_types'; import { isObject, type MongoDBNamespace } from '../utils'; import { type CollationOptions, CommandOperation, type CommandOperationOptions, type OperationParent } from './command'; import { Aspect, defineAspects } from './operation'; const VALID_INDEX_OPTIONS = new Set([ 'background', 'unique', 'name', 'partialFilterExpression', 'sparse', 'hidden', 'expireAfterSeconds', 'storageEngine', 'collation', 'version', // text indexes 'weights', 'default_language', 'language_override', 'textIndexVersion', // 2d-sphere indexes '2dsphereIndexVersion', // 2d indexes 'bits', 'min', 'max', // geoHaystack Indexes 'bucketSize', // wildcard indexes 'wildcardProjection' ]); /** @public */ export type IndexDirection = | -1 | 1 | '2d' | '2dsphere' | 'text' | 'geoHaystack' | 'hashed' | number; function isIndexDirection(x: unknown): x is IndexDirection { return ( typeof x === 'number' || x === '2d' || x === '2dsphere' || x === 'text' || x === 'geoHaystack' ); } /** @public */ export type IndexSpecification = OneOrMore< | string | [string, IndexDirection] | { [key: string]: IndexDirection } | Map<string, IndexDirection> >; /** @public */ export interface IndexInformationOptions extends ListIndexesOptions { /** * When `true`, an array of index descriptions is returned. * When `false`, the driver returns an object that with keys corresponding to index names with values * corresponding to the entries of the indexes' key. * * For example, the given the following indexes: * ``` * [ { name: 'a_1', key: { a: 1 } }, { name: 'b_1_c_1' , key: { b: 1, c: 1 } }] * ``` * * When `full` is `true`, the above array is returned. When `full` is `false`, the following is returned: * ``` * { * 'a_1': [['a', 1]], * 'b_1_c_1': [['b', 1], ['c', 1]], * } * ``` */ full?: boolean; } /** * @public * * Loosely aligns with `IndexModel` from the spec. * */ export interface IndexDescription extends Pick< CreateIndexesOptions, | 'background' | 'unique' | 'partialFilterExpression' | 'sparse' | 'hidden' | 'expireAfterSeconds' | 'storageEngine' | 'version' | 'weights' | 'default_language' | 'language_override' | 'textIndexVersion' | '2dsphereIndexVersion' | 'bits' | 'min' | 'max' | 'bucketSize' | 'wildcardProjection' > { collation?: CollationOptions; name?: string; key: { [key: string]: IndexDirection } | Map<string, IndexDirection>; } /** @public */ export interface CreateIndexesOptions extends Omit<CommandOperationOptions, 'writeConcern'> { /** Creates the index in the background, yielding whenever possible. */ background?: boolean; /** Creates an unique index. */ unique?: boolean; /** Override the autogenerated index name (useful if the resulting name is larger than 128 bytes) */ name?: string; /** Creates a partial index based on the given filter object (MongoDB 3.2 or higher) */ partialFilterExpression?: Document; /** Creates a sparse index. */ sparse?: boolean; /** Allows you to expire data on indexes applied to a data (MongoDB 2.2 or higher) */ expireAfterSeconds?: number; /** Allows users to configure the storage engine on a per-index basis when creating an index. (MongoDB 3.0 or higher) */ storageEngine?: Document; /** Specifies how many data-bearing members of a replica set, including the primary, must complete the index builds successfully before the primary marks the indexes as ready. This option accepts the same values for the "w" field in a write concern plus "votingMembers", which indicates all voting data-bearing nodes. */ commitQuorum?: number | string; /** Specifies the index version number, either 0 or 1. */ version?: number; // text indexes weights?: Document; default_language?: string; language_override?: string; textIndexVersion?: number; // 2d-sphere indexes '2dsphereIndexVersion'?: number; // 2d indexes bits?: number; /** For geospatial indexes set the lower bound for the co-ordinates. */ min?: number; /** For geospatial indexes set the high bound for the co-ordinates. */ max?: number; // geoHaystack Indexes bucketSize?: number; // wildcard indexes wildcardProjection?: Document; /** Specifies that the index should exist on the target collection but should not be used by the query planner when executing operations. */ hidden?: boolean; /** Collation */ collation?: CollationOptions; } // Maps to `IndexOptions` in // https://github.com/mongodb/specifications/blob/6f64d0ee3ae49edbdb30eb995f3e29549e8cfa6a/source/index-management/index-management.md#common-api-components /** @public */ export interface IndexOptions extends Document { /** * Optionally specifies the length in time, in seconds, for documents to remain in * a collection. */ expireAfterSeconds?: number; /** * Optionally specify a specific name for the index outside of the default generated * name. If none is provided then the name is generated in the format "[field]_[direction]". * * Note that if an index is created for the same key pattern with different collations, * a name must be provided by the user to avoid ambiguity. * * @example For an index of name: 1, age: -1, the generated name would be "name_1_age_-1". */ name?: string; /** * Optionally tells the index to only reference documents with the specified field in * the index. */ sparse?: boolean; /** * Optionally allows users to configure the storage engine on a per-index basis when creating * an index. */ storageEngine?: Document; /** * Optionally forces the index to be unique. */ unique?: boolean; /** * Optionally specifies the index version number, either 0 or 1. */ version?: number; /** * Optionally specifies the default language for text indexes. * Is 'english' if none is provided. */ defaultLanguage?: string; /** * Optionally Specifies the field in the document to override the language. */ languageOverride?: string; /** * Optionally provides the text index version number. */ textIndexVersion?: number; /** * Optionally specifies fields in the index and their corresponding weight values. */ weights?: Document; /** * Optionally specifies the 2dsphere index version number. */ '2dsphereIndexVersion'?: number; /** * Optionally specifies the precision of the stored geo hash in the 2d index, from 1 to 32. */ bits?: number; /** * Optionally sets the maximum boundary for latitude and longitude in the 2d index. */ max?: number; /** * Optionally sets the minimum boundary for latitude and longitude in the index in a * 2d index. */ min?: number; /** * Optionally specifies the number of units within which to group the location values * in a geo haystack index. */ bucketSize?: number; /** * Optionally specifies a filter for use in a partial index. Only documents that match the * filter expression are included in the index. */ partialFilterExpression?: Document; /** * Optionally specifies a collation to use for the index. If not specified, no collation is * sent and the default collation of the collection server-side is used. */ collation?: CollationOptions; /** * Optionally specifies the wildcard projection of a wildcard index. */ wildcardProjection?: Document; /** * Optionally specifies that the index should exist on the target collection but should not be used by the query * planner when executing operations. * * This option is only supported by servers \>= 4.4. */ hidden?: boolean; } /** @public */ export interface CreateIndexOptions extends Omit<CommandOperationOptions, 'collation' | 'explain'> { /** * Specifies how many data-bearing members of a replica set, including the primary, must * complete the index builds successfully before the primary marks the indexes as ready. * * This option accepts the same values for the "w" field in a write concern plus "votingMembers", * which indicates all voting data-bearing nodes. * * This option is only supported by servers \>= 4.4. Drivers MUST manually raise an error if this option * is specified when creating an index on a pre 4.4 server. See the Q&A section for the rationale behind this. * * @remarks This option is sent only if the caller explicitly provides a value. The default is to not send a value. * * @sinceServerVersion 4.4 */ commitQuorum?: number | string; } function isSingleIndexTuple(t: unknown): t is [string, IndexDirection] { return Array.isArray(t) && t.length === 2 && isIndexDirection(t[1]); } /** * Converts an `IndexSpecification`, which can be specified in multiple formats, into a * valid `key` for the createIndexes command. */ function constructIndexDescriptionMap(indexSpec: IndexSpecification): Map<string, IndexDirection> { const key: Map<string, IndexDirection> = new Map(); const indexSpecs = !Array.isArray(indexSpec) || isSingleIndexTuple(indexSpec) ? [indexSpec] : indexSpec; // Iterate through array and handle different types for (const spec of indexSpecs) { if (typeof spec === 'string') { key.set(spec, 1); } else if (Array.isArray(spec)) { key.set(spec[0], spec[1] ?? 1); } else if (spec instanceof Map) { for (const [property, value] of spec) { key.set(property, value); } } else if (isObject(spec)) { for (const [property, value] of Object.entries(spec)) { key.set(property, value); } } } return key; } /** * Index options whose public name on {@link IndexOptions} differs from the field name the * `createIndexes` command expects. */ const INDEX_OPTION_RENAMES = new Map([ ['version', 'v'], ['defaultLanguage', 'default_language'], ['languageOverride', 'language_override'] ]); /** * Receives an index description and returns a modified index description which has mapped the * options in {@link INDEX_OPTION_RENAMES} to the field names the `createIndexes` command expects. * * When `allowUnknownIndexOptions` is `false` (the default), options that are not in the driver's * `VALID_INDEX_OPTIONS` allowlist are removed from the description. When `true`, all options are * retained and passed through to the server for validation. */ function resolveIndexDescription( description: IndexDescription, // TODO(NODE-7868): Remove allowUnknownIndexOptions with a default behavior of true in a future major version release allowUnknownIndexOptions: boolean ): Omit<ResolvedIndexDescription, 'key'> { const providedOptions = Object.entries(description).filter( ([optionName]) => // Ensure `key` is removed, even when `allowUnknownIndexOptions` is true optionName !== 'key' && (allowUnknownIndexOptions || VALID_INDEX_OPTIONS.has(optionName)) ); return Object.fromEntries( providedOptions.map(([name, value]) => [INDEX_OPTION_RENAMES.get(name) ?? name, value]) ); } /** * @public * The index information returned by the listIndexes command. https://www.mongodb.com/docs/manual/reference/command/listIndexes/#mongodb-dbcommand-dbcmd.listIndexes */ export type IndexDescriptionInfo = Omit<IndexDescription, 'key' | 'version'> & { key: { [key: string]: IndexDirection }; v?: IndexDescription['version']; } & Document; /** @public */ export type IndexDescriptionCompact = Record<string, [name: string, direction: IndexDirection][]>; /** * @internal * * Internally, the driver represents index description keys with `Map`s to preserve key ordering. * We don't require users to specify maps, so we transform user provided descriptions into * "resolved" by converting the `key` into a JS `Map`, if it isn't already a map. * * Additionally, we support the `version` option, but the `createIndexes` command uses the field `v` * to specify the index version so we map the value of `version` to `v`, if provided. */ type ResolvedIndexDescription = Omit<IndexDescription, 'key' | 'version'> & { key: Map<string, IndexDirection>; v?: IndexDescription['version']; }; /** @internal */ export class CreateIndexesOperation extends CommandOperation<string[]> { override SERVER_COMMAND_RESPONSE_TYPE = MongoDBResponse; override options: CreateIndexesOptions; collectionName: string; indexes: ReadonlyArray<ResolvedIndexDescription>; private constructor( parent: OperationParent, collectionName: string, indexes: IndexDescription[], // TODO(NODE-7868): Remove allowUnknownIndexOptions with a default behavior of true in a future major version release allowUnknownIndexOptions: boolean, commandOptions: CreateIndexesOptions | CreateIndexOptions | undefined ) { super(parent, commandOptions); this.options = { ...commandOptions }; // collation is set on each index, it should not be defined at the root this.options.collation = undefined; this.collectionName = collectionName; this.indexes = indexes.map((userIndex: IndexDescription): ResolvedIndexDescription => { // Ensure the key is a Map to preserve index key ordering const key = userIndex.key instanceof Map ? userIndex.key : new Map(Object.entries(userIndex.key)); const name = userIndex.name ?? Array.from(key).flat().join('_'); const validIndexOptions = resolveIndexDescription(userIndex, allowUnknownIndexOptions); return { ...validIndexOptions, name, key }; }); this.ns = parent.s.namespace; } /** * Index options are carried by the individual {@link IndexDescription} entries of `indexes`, * so the only options bag this factory takes is the command one. */ static fromIndexDescriptionArray( parent: OperationParent, collectionName: string, indexes: IndexDescription[], // TODO(NODE-7868): Remove allowUnknownIndexOptions with a default behavior of true in a future major version release allowUnknownIndexOptions: boolean, commandOptions: CreateIndexesOptions | undefined ): CreateIndexesOperation { return new CreateIndexesOperation( parent, collectionName, indexes, allowUnknownIndexOptions, commandOptions ); } static fromIndexSpecification( parent: OperationParent, collectionName: string, indexSpec: IndexSpecification, allowUnknownIndexOptions: boolean, indexOptions: IndexOptions | undefined, commandOptions: CreateIndexOptions | undefined ): CreateIndexesOperation; static fromIndexSpecification( parent: OperationParent, collectionName: string, indexSpec: IndexSpecification, allowUnknownIndexOptions: boolean, indexOptions: CreateIndexesOptions | IndexOptions | undefined, commandOptions: CreateIndexOptions | undefined ): CreateIndexesOperation { const key = constructIndexDescriptionMap(indexSpec); // If called with overload using `CreateIndexesOptions`, then indexOptions may contain combined index and command options // These are filtered in CreateIndexesOperation using VALID_INDEX_OPTIONS. // Otherwise, `IndexOptions` only contains index options (which is the ultimate goal anyway) const description: IndexDescription = { ...indexOptions, key }; return new CreateIndexesOperation( parent, collectionName, [description], allowUnknownIndexOptions, // TODO(NODE-7868): Remove the `?? indexOptions` fallback along with the two parameter path. // Once `indexOptions` is index options only it must not reach the command root. commandOptions ?? indexOptions ); } override get commandName() { return 'createIndexes'; } override buildCommandDocument(_connection: Connection): Document { const options = this.options; const indexes = this.indexes; const cmd: Document = { createIndexes: this.collectionName, indexes }; if (options.commitQuorum != null) { cmd.commitQuorum = options.commitQuorum; } return cmd; } override handleOk(_response: InstanceType<typeof this.SERVER_COMMAND_RESPONSE_TYPE>): string[] { const indexNames = this.indexes.map(index => index.name || ''); return indexNames; } } /** @public */ export type DropIndexesOptions = CommandOperationOptions; /** @internal */ export class DropIndexOperation extends CommandOperation<Document> { override SERVER_COMMAND_RESPONSE_TYPE = MongoDBResponse; override options: DropIndexesOptions; collection: Collection; indexName: string; constructor(collection: Collection, indexName: string, options?: DropIndexesOptions) { super(collection, options); this.options = options ?? {}; this.collection = collection; this.indexName = indexName; this.ns = collection.fullNamespace; } override get commandName() { return 'dropIndexes' as const; } override buildCommandDocument(_connection: Connection): Document { return { dropIndexes: this.collection.collectionName, index: this.indexName }; } } /** @public */ export type ListIndexesOptions = AbstractCursorOptions & { /** @internal */ omitMaxTimeMS?: boolean; /** @internal */ rawData?: boolean; }; /** @internal */ export class ListIndexesOperation extends CommandOperation<CursorResponse> { override SERVER_COMMAND_RESPONSE_TYPE = CursorResponse; /** * @remarks WriteConcern can still be present on the options because * we inherit options from the client/db/collection. The * key must be present on the options in order to delete it. * This allows typescript to delete the key but will * not allow a writeConcern to be assigned as a property on options. */ override options: ListIndexesOptions & { writeConcern?: never }; collectionNamespace: MongoDBNamespace; constructor(collection: Collection, options?: ListIndexesOptions) { super(collection, options); this.options = { ...options }; delete this.options.writeConcern; this.collectionNamespace = collection.s.namespace; } override get commandName() { return 'listIndexes' as const; } override buildCommandDocument(_connection: Connection): Document { const cursor = this.options.batchSize ? { batchSize: this.options.batchSize } : {}; const command: Document = { listIndexes: this.collectionNamespace.collection, cursor }; // we check for undefined specifically here to allow falsy values // eslint-disable-next-line no-restricted-syntax if (this.options.comment !== undefined) { command.comment = this.options.comment; } return command; } override handleOk( response: InstanceType<typeof this.SERVER_COMMAND_RESPONSE_TYPE> ): CursorResponse { return response; } } defineAspects(ListIndexesOperation, [ Aspect.READ_OPERATION, Aspect.RETRYABLE, Aspect.CURSOR_CREATING, Aspect.SUPPORTS_RAW_DATA ]); defineAspects(CreateIndexesOperation, [Aspect.WRITE_OPERATION, Aspect.SUPPORTS_RAW_DATA]); defineAspects(DropIndexOperation, [Aspect.WRITE_OPERATION, Aspect.SUPPORTS_RAW_DATA]);