indexes.ts 15.2 KB
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543
import type { Document } from '../bson';
import type { Collection } from '../collection';
import { AbstractCursor } from '../cursor/abstract_cursor';
import type { Db } from '../db';
import { MongoCompatibilityError, MONGODB_ERROR_CODES, MongoServerError } from '../error';
import type { OneOrMore } from '../mongo_types';
import { ReadPreference } from '../read_preference';
import type { Server } from '../sdam/server';
import type { ClientSession } from '../sessions';
import {
  Callback,
  getTopology,
  maxWireVersion,
  MongoDBNamespace,
  parseIndexOptions
} from '../utils';
import {
  CollationOptions,
  CommandOperation,
  CommandOperationOptions,
  OperationParent
} from './command';
import { indexInformation, IndexInformationOptions } from './common_functions';
import { executeOperation, ExecutionResult } from './execute_operation';
import { AbstractOperation, 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' | number;

/** @public */
export type IndexSpecification = OneOrMore<
  | string
  | [string, IndexDirection]
  | { [key: string]: IndexDirection }
  | [string, IndexDirection][]
  | { [key: string]: IndexDirection }[]
>;

/** @public */
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: Document;
}

/** @public */
export interface CreateIndexesOptions extends CommandOperationOptions {
  /** 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;
  /** (MongoDB 4.4. or higher) 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. (MongoDB 4.4 or higher) */
  hidden?: boolean;
}

function makeIndexSpec(indexSpec: IndexSpecification, options: any): IndexDescription {
  const indexParameters = parseIndexOptions(indexSpec);

  // Generate the index name
  const name = typeof options.name === 'string' ? options.name : indexParameters.name;

  // Set up the index
  const finalIndexSpec: Document = { name, key: indexParameters.fieldHash };

  // merge valid index options into the index spec
  for (const optionName in options) {
    if (VALID_INDEX_OPTIONS.has(optionName)) {
      finalIndexSpec[optionName] = options[optionName];
    }
  }

  return finalIndexSpec as IndexDescription;
}

/** @internal */
export class IndexesOperation extends AbstractOperation<Document[]> {
  override options: IndexInformationOptions;
  collection: Collection;

  constructor(collection: Collection, options: IndexInformationOptions) {
    super(options);
    this.options = options;
    this.collection = collection;
  }

  override execute(
    server: Server,
    session: ClientSession | undefined,
    callback: Callback<Document[]>
  ): void {
    const coll = this.collection;
    const options = this.options;

    indexInformation(
      coll.s.db,
      coll.collectionName,
      { full: true, ...options, readPreference: this.readPreference, session },
      callback
    );
  }
}

/** @internal */
export class CreateIndexesOperation<
  T extends string | string[] = string[]
> extends CommandOperation<T> {
  override options: CreateIndexesOptions;
  collectionName: string;
  indexes: IndexDescription[];

  constructor(
    parent: OperationParent,
    collectionName: string,
    indexes: IndexDescription[],
    options?: CreateIndexesOptions
  ) {
    super(parent, options);

    this.options = options ?? {};
    this.collectionName = collectionName;

    this.indexes = indexes;
  }

  override execute(
    server: Server,
    session: ClientSession | undefined,
    callback: Callback<T>
  ): void {
    const options = this.options;
    const indexes = this.indexes;

    const serverWireVersion = maxWireVersion(server);

    // Ensure we generate the correct name if the parameter is not set
    for (let i = 0; i < indexes.length; i++) {
      // Did the user pass in a collation, check if our write server supports it
      if (indexes[i].collation && serverWireVersion < 5) {
        callback(
          new MongoCompatibilityError(
            `Server ${server.name}, which reports wire version ${serverWireVersion}, ` +
              'does not support collation'
          )
        );
        return;
      }

      if (indexes[i].name == null) {
        const keys = [];

        for (const name in indexes[i].key) {
          keys.push(`${name}_${indexes[i].key[name]}`);
        }

        // Set the name
        indexes[i].name = keys.join('_');
      }
    }

    const cmd: Document = { createIndexes: this.collectionName, indexes };

    if (options.commitQuorum != null) {
      if (serverWireVersion < 9) {
        callback(
          new MongoCompatibilityError(
            'Option `commitQuorum` for `createIndexes` not supported on servers < 4.4'
          )
        );
        return;
      }
      cmd.commitQuorum = options.commitQuorum;
    }

    // collation is set on each index, it should not be defined at the root
    this.options.collation = undefined;

    super.executeCommand(server, session, cmd, err => {
      if (err) {
        callback(err);
        return;
      }

      const indexNames = indexes.map(index => index.name || '');
      callback(undefined, indexNames as T);
    });
  }
}

/** @internal */
export class CreateIndexOperation extends CreateIndexesOperation<string> {
  constructor(
    parent: OperationParent,
    collectionName: string,
    indexSpec: IndexSpecification,
    options?: CreateIndexesOptions
  ) {
    // createIndex can be called with a variety of styles:
    //   coll.createIndex('a');
    //   coll.createIndex({ a: 1 });
    //   coll.createIndex([['a', 1]]);
    // createIndexes is always called with an array of index spec objects

    super(parent, collectionName, [makeIndexSpec(indexSpec, options)], options);
  }
  override execute(
    server: Server,
    session: ClientSession | undefined,
    callback: Callback<string>
  ): void {
    super.execute(server, session, (err, indexNames) => {
      if (err || !indexNames) return callback(err);
      return callback(undefined, indexNames[0]);
    });
  }
}

/** @internal */
export class EnsureIndexOperation extends CreateIndexOperation {
  db: Db;

  constructor(
    db: Db,
    collectionName: string,
    indexSpec: IndexSpecification,
    options?: CreateIndexesOptions
  ) {
    super(db, collectionName, indexSpec, options);

    this.readPreference = ReadPreference.primary;
    this.db = db;
    this.collectionName = collectionName;
  }

  override execute(server: Server, session: ClientSession | undefined, callback: Callback): void {
    const indexName = this.indexes[0].name;
    const cursor = this.db.collection(this.collectionName).listIndexes({ session });
    cursor.toArray((err, indexes) => {
      /// ignore "NamespaceNotFound" errors
      if (err && (err as MongoServerError).code !== MONGODB_ERROR_CODES.NamespaceNotFound) {
        return callback(err);
      }

      if (indexes) {
        indexes = Array.isArray(indexes) ? indexes : [indexes];
        if (indexes.some(index => index.name === indexName)) {
          callback(undefined, indexName);
          return;
        }
      }

      super.execute(server, session, callback);
    });
  }
}

/** @public */
export type DropIndexesOptions = CommandOperationOptions;

/** @internal */
export class DropIndexOperation extends CommandOperation<Document> {
  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;
  }

  override execute(
    server: Server,
    session: ClientSession | undefined,
    callback: Callback<Document>
  ): void {
    const cmd = { dropIndexes: this.collection.collectionName, index: this.indexName };
    super.executeCommand(server, session, cmd, callback);
  }
}

/** @internal */
export class DropIndexesOperation extends DropIndexOperation {
  constructor(collection: Collection, options: DropIndexesOptions) {
    super(collection, '*', options);
  }

  override execute(server: Server, session: ClientSession | undefined, callback: Callback): void {
    super.execute(server, session, err => {
      if (err) return callback(err, false);
      callback(undefined, true);
    });
  }
}

/** @public */
export interface ListIndexesOptions extends CommandOperationOptions {
  /** The batchSize for the returned command cursor or if pre 2.8 the systems batch collection */
  batchSize?: number;
}

/** @internal */
export class ListIndexesOperation extends CommandOperation<Document> {
  override options: ListIndexesOptions;
  collectionNamespace: MongoDBNamespace;

  constructor(collection: Collection, options?: ListIndexesOptions) {
    super(collection, options);

    this.options = options ?? {};
    this.collectionNamespace = collection.s.namespace;
  }

  override execute(
    server: Server,
    session: ClientSession | undefined,
    callback: Callback<Document>
  ): void {
    const serverWireVersion = maxWireVersion(server);

    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 (serverWireVersion >= 9 && this.options.comment !== undefined) {
      command.comment = this.options.comment;
    }

    super.executeCommand(server, session, command, callback);
  }
}

/** @public */
export class ListIndexesCursor extends AbstractCursor {
  parent: Collection;
  options?: ListIndexesOptions;

  constructor(collection: Collection, options?: ListIndexesOptions) {
    super(getTopology(collection), collection.s.namespace, options);
    this.parent = collection;
    this.options = options;
  }

  clone(): ListIndexesCursor {
    return new ListIndexesCursor(this.parent, {
      ...this.options,
      ...this.cursorOptions
    });
  }

  /** @internal */
  _initialize(session: ClientSession | undefined, callback: Callback<ExecutionResult>): void {
    const operation = new ListIndexesOperation(this.parent, {
      ...this.cursorOptions,
      ...this.options,
      session
    });

    executeOperation(this.parent, operation, (err, response) => {
      if (err || response == null) return callback(err);

      // TODO: NODE-2882
      callback(undefined, { server: operation.server, session, response });
    });
  }
}

/** @internal */
export class IndexExistsOperation extends AbstractOperation<boolean> {
  override options: IndexInformationOptions;
  collection: Collection;
  indexes: string | string[];

  constructor(
    collection: Collection,
    indexes: string | string[],
    options: IndexInformationOptions
  ) {
    super(options);
    this.options = options;
    this.collection = collection;
    this.indexes = indexes;
  }

  override execute(
    server: Server,
    session: ClientSession | undefined,
    callback: Callback<boolean>
  ): void {
    const coll = this.collection;
    const indexes = this.indexes;

    indexInformation(
      coll.s.db,
      coll.collectionName,
      { ...this.options, readPreference: this.readPreference, session },
      (err, indexInformation) => {
        // If we have an error return
        if (err != null) return callback(err);
        // Let's check for the index names
        if (!Array.isArray(indexes)) return callback(undefined, indexInformation[indexes] != null);
        // Check in list of indexes
        for (let i = 0; i < indexes.length; i++) {
          if (indexInformation[indexes[i]] == null) {
            return callback(undefined, false);
          }
        }

        // All keys found return true
        return callback(undefined, true);
      }
    );
  }
}

/** @internal */
export class IndexInformationOperation extends AbstractOperation<Document> {
  override options: IndexInformationOptions;
  db: Db;
  name: string;

  constructor(db: Db, name: string, options?: IndexInformationOptions) {
    super(options);
    this.options = options ?? {};
    this.db = db;
    this.name = name;
  }

  override execute(
    server: Server,
    session: ClientSession | undefined,
    callback: Callback<Document>
  ): void {
    const db = this.db;
    const name = this.name;

    indexInformation(
      db,
      name,
      { ...this.options, readPreference: this.readPreference, session },
      callback
    );
  }
}

defineAspects(ListIndexesOperation, [
  Aspect.READ_OPERATION,
  Aspect.RETRYABLE,
  Aspect.CURSOR_CREATING
]);
defineAspects(CreateIndexesOperation, [Aspect.WRITE_OPERATION]);
defineAspects(CreateIndexOperation, [Aspect.WRITE_OPERATION]);
defineAspects(EnsureIndexOperation, [Aspect.WRITE_OPERATION]);
defineAspects(DropIndexOperation, [Aspect.WRITE_OPERATION]);
defineAspects(DropIndexesOperation, [Aspect.WRITE_OPERATION]);