Search moodle.org's
Developer Documentation

See Release Notes
Long Term Support Release

  • Bug fixes for general core bugs in 4.1.x will end 13 November 2023 (12 months).
  • Bug fixes for security issues in 4.1.x will end 10 November 2025 (36 months).
  • PHP version: minimum PHP 7.4.0 Note: minimum PHP version has increased since Moodle 4.0. PHP 8.0.x is supported too.

Differences Between: [Versions 310 and 401] [Versions 311 and 401] [Versions 39 and 401] [Versions 400 and 401]

   1  <?php
   2  /*
   3   * Copyright 2015-present MongoDB, Inc.
   4   *
   5   * Licensed under the Apache License, Version 2.0 (the "License");
   6   * you may not use this file except in compliance with the License.
   7   * You may obtain a copy of the License at
   8   *
   9   *   https://www.apache.org/licenses/LICENSE-2.0
  10   *
  11   * Unless required by applicable law or agreed to in writing, software
  12   * distributed under the License is distributed on an "AS IS" BASIS,
  13   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  14   * See the License for the specific language governing permissions and
  15   * limitations under the License.
  16   */
  17  
  18  namespace MongoDB\Operation;
  19  
  20  use MongoDB\Driver\Command;
  21  use MongoDB\Driver\Exception\RuntimeException as DriverRuntimeException;
  22  use MongoDB\Driver\Server;
  23  use MongoDB\Driver\Session;
  24  use MongoDB\Driver\WriteConcern;
  25  use MongoDB\Exception\InvalidArgumentException;
  26  use MongoDB\Exception\UnsupportedException;
  27  use MongoDB\Model\IndexInput;
  28  
  29  use function array_map;
  30  use function is_array;
  31  use function is_integer;
  32  use function is_string;
  33  use function MongoDB\server_supports_feature;
  34  use function sprintf;
  35  
  36  /**
  37   * Operation for the createIndexes command.
  38   *
  39   * @api
  40   * @see \MongoDB\Collection::createIndex()
  41   * @see \MongoDB\Collection::createIndexes()
  42   * @see https://mongodb.com/docs/manual/reference/command/createIndexes/
  43   */
  44  class CreateIndexes implements Executable
  45  {
  46      /** @var integer */
  47      private static $wireVersionForCommitQuorum = 9;
  48  
  49      /** @var string */
  50      private $databaseName;
  51  
  52      /** @var string */
  53      private $collectionName;
  54  
  55      /** @var array */
  56      private $indexes = [];
  57  
  58      /** @var array */
  59      private $options = [];
  60  
  61      /**
  62       * Constructs a createIndexes command.
  63       *
  64       * Supported options:
  65       *
  66       *  * comment (mixed): BSON value to attach as a comment to this command.
  67       *
  68       *    This is not supported for servers versions < 4.4.
  69       *
  70       *  * commitQuorum (integer|string): Specifies how many data-bearing members
  71       *    of a replica set, including the primary, must complete the index
  72       *    builds successfully before the primary marks the indexes as ready.
  73       *
  74       *  * maxTimeMS (integer): The maximum amount of time to allow the query to
  75       *    run.
  76       *
  77       *  * session (MongoDB\Driver\Session): Client session.
  78       *
  79       *  * writeConcern (MongoDB\Driver\WriteConcern): Write concern.
  80       *
  81       * @param string  $databaseName   Database name
  82       * @param string  $collectionName Collection name
  83       * @param array[] $indexes        List of index specifications
  84       * @param array   $options        Command options
  85       * @throws InvalidArgumentException for parameter/option parsing errors
  86       */
  87      public function __construct(string $databaseName, string $collectionName, array $indexes, array $options = [])
  88      {
  89          if (empty($indexes)) {
  90              throw new InvalidArgumentException('$indexes is empty');
  91          }
  92  
  93          $expectedIndex = 0;
  94  
  95          foreach ($indexes as $i => $index) {
  96              if ($i !== $expectedIndex) {
  97                  throw new InvalidArgumentException(sprintf('$indexes is not a list (unexpected index: "%s")', $i));
  98              }
  99  
 100              if (! is_array($index)) {
 101                  throw InvalidArgumentException::invalidType(sprintf('$index[%d]', $i), $index, 'array');
 102              }
 103  
 104              $this->indexes[] = new IndexInput($index);
 105  
 106              $expectedIndex += 1;
 107          }
 108  
 109          if (isset($options['commitQuorum']) && ! is_string($options['commitQuorum']) && ! is_integer($options['commitQuorum'])) {
 110              throw InvalidArgumentException::invalidType('"commitQuorum" option', $options['commitQuorum'], ['integer', 'string']);
 111          }
 112  
 113          if (isset($options['maxTimeMS']) && ! is_integer($options['maxTimeMS'])) {
 114              throw InvalidArgumentException::invalidType('"maxTimeMS" option', $options['maxTimeMS'], 'integer');
 115          }
 116  
 117          if (isset($options['session']) && ! $options['session'] instanceof Session) {
 118              throw InvalidArgumentException::invalidType('"session" option', $options['session'], Session::class);
 119          }
 120  
 121          if (isset($options['writeConcern']) && ! $options['writeConcern'] instanceof WriteConcern) {
 122              throw InvalidArgumentException::invalidType('"writeConcern" option', $options['writeConcern'], WriteConcern::class);
 123          }
 124  
 125          if (isset($options['writeConcern']) && $options['writeConcern']->isDefault()) {
 126              unset($options['writeConcern']);
 127          }
 128  
 129          $this->databaseName = $databaseName;
 130          $this->collectionName = $collectionName;
 131          $this->options = $options;
 132      }
 133  
 134      /**
 135       * Execute the operation.
 136       *
 137       * @see Executable::execute()
 138       * @return string[] The names of the created indexes
 139       * @throws UnsupportedException if write concern is used and unsupported
 140       * @throws DriverRuntimeException for other driver errors (e.g. connection errors)
 141       */
 142      public function execute(Server $server)
 143      {
 144          $inTransaction = isset($this->options['session']) && $this->options['session']->isInTransaction();
 145          if ($inTransaction && isset($this->options['writeConcern'])) {
 146              throw UnsupportedException::writeConcernNotSupportedInTransaction();
 147          }
 148  
 149          $this->executeCommand($server);
 150  
 151          return array_map(function (IndexInput $index) {
 152              return (string) $index;
 153          }, $this->indexes);
 154      }
 155  
 156      /**
 157       * Create options for executing the command.
 158       *
 159       * @see https://php.net/manual/en/mongodb-driver-server.executewritecommand.php
 160       */
 161      private function createOptions(): array
 162      {
 163          $options = [];
 164  
 165          if (isset($this->options['session'])) {
 166              $options['session'] = $this->options['session'];
 167          }
 168  
 169          if (isset($this->options['writeConcern'])) {
 170              $options['writeConcern'] = $this->options['writeConcern'];
 171          }
 172  
 173          return $options;
 174      }
 175  
 176      /**
 177       * Create one or more indexes for the collection using the createIndexes
 178       * command.
 179       *
 180       * @throws DriverRuntimeException for other driver errors (e.g. connection errors)
 181       */
 182      private function executeCommand(Server $server): void
 183      {
 184          $cmd = [
 185              'createIndexes' => $this->collectionName,
 186              'indexes' => $this->indexes,
 187          ];
 188  
 189          if (isset($this->options['commitQuorum'])) {
 190              /* Drivers MUST manually raise an error if this option is specified
 191               * when creating an index on a pre 4.4 server. */
 192              if (! server_supports_feature($server, self::$wireVersionForCommitQuorum)) {
 193                  throw UnsupportedException::commitQuorumNotSupported();
 194              }
 195  
 196              $cmd['commitQuorum'] = $this->options['commitQuorum'];
 197          }
 198  
 199          foreach (['comment', 'maxTimeMS'] as $option) {
 200              if (isset($this->options[$option])) {
 201                  $cmd[$option] = $this->options[$option];
 202              }
 203          }
 204  
 205          $server->executeWriteCommand($this->databaseName, new Command($cmd), $this->createOptions());
 206      }
 207  }