Search moodle.org's
Developer Documentation

See Release Notes

  • Bug fixes for general core bugs in 3.11.x will end 14 Nov 2022 (12 months plus 6 months extension).
  • Bug fixes for security issues in 3.11.x will end 13 Nov 2023 (18 months plus 12 months extension).
  • PHP version: minimum PHP 7.3.0 Note: minimum PHP version has increased since Moodle 3.10. PHP 7.4.x is supported too.

Differences Between: [Versions 311 and 401]

   1  <?php
   2  /*
   3   * Copyright 2015-2017 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   *   http://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\BulkWrite as Bulk;
  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\InsertManyResult;
  28  use function is_array;
  29  use function is_bool;
  30  use function is_object;
  31  use function MongoDB\server_supports_feature;
  32  use function sprintf;
  33  
  34  /**
  35   * Operation for inserting multiple documents with the insert command.
  36   *
  37   * @api
  38   * @see \MongoDB\Collection::insertMany()
  39   * @see http://docs.mongodb.org/manual/reference/command/insert/
  40   */
  41  class InsertMany implements Executable
  42  {
  43      /** @var integer */
  44      private static $wireVersionForDocumentLevelValidation = 4;
  45  
  46      /** @var string */
  47      private $databaseName;
  48  
  49      /** @var string */
  50      private $collectionName;
  51  
  52      /** @var object[]|array[] */
  53      private $documents;
  54  
  55      /** @var array */
  56      private $options;
  57  
  58      /**
  59       * Constructs an insert command.
  60       *
  61       * Supported options:
  62       *
  63       *  * bypassDocumentValidation (boolean): If true, allows the write to
  64       *    circumvent document level validation.
  65       *
  66       *    For servers < 3.2, this option is ignored as document level validation
  67       *    is not available.
  68       *
  69       *  * ordered (boolean): If true, when an insert fails, return without
  70       *    performing the remaining writes. If false, when a write fails,
  71       *    continue with the remaining writes, if any. The default is true.
  72       *
  73       *  * session (MongoDB\Driver\Session): Client session.
  74       *
  75       *    Sessions are not supported for server versions < 3.6.
  76       *
  77       *  * writeConcern (MongoDB\Driver\WriteConcern): Write concern.
  78       *
  79       * @param string           $databaseName   Database name
  80       * @param string           $collectionName Collection name
  81       * @param array[]|object[] $documents      List of documents to insert
  82       * @param array            $options        Command options
  83       * @throws InvalidArgumentException for parameter/option parsing errors
  84       */
  85      public function __construct($databaseName, $collectionName, array $documents, array $options = [])
  86      {
  87          if (empty($documents)) {
  88              throw new InvalidArgumentException('$documents is empty');
  89          }
  90  
  91          $expectedIndex = 0;
  92  
  93          foreach ($documents as $i => $document) {
  94              if ($i !== $expectedIndex) {
  95                  throw new InvalidArgumentException(sprintf('$documents is not a list (unexpected index: "%s")', $i));
  96              }
  97  
  98              if (! is_array($document) && ! is_object($document)) {
  99                  throw InvalidArgumentException::invalidType(sprintf('$documents[%d]', $i), $document, 'array or object');
 100              }
 101  
 102              $expectedIndex += 1;
 103          }
 104  
 105          $options += ['ordered' => true];
 106  
 107          if (isset($options['bypassDocumentValidation']) && ! is_bool($options['bypassDocumentValidation'])) {
 108              throw InvalidArgumentException::invalidType('"bypassDocumentValidation" option', $options['bypassDocumentValidation'], 'boolean');
 109          }
 110  
 111          if (! is_bool($options['ordered'])) {
 112              throw InvalidArgumentException::invalidType('"ordered" option', $options['ordered'], 'boolean');
 113          }
 114  
 115          if (isset($options['session']) && ! $options['session'] instanceof Session) {
 116              throw InvalidArgumentException::invalidType('"session" option', $options['session'], Session::class);
 117          }
 118  
 119          if (isset($options['writeConcern']) && ! $options['writeConcern'] instanceof WriteConcern) {
 120              throw InvalidArgumentException::invalidType('"writeConcern" option', $options['writeConcern'], WriteConcern::class);
 121          }
 122  
 123          if (isset($options['writeConcern']) && $options['writeConcern']->isDefault()) {
 124              unset($options['writeConcern']);
 125          }
 126  
 127          $this->databaseName = (string) $databaseName;
 128          $this->collectionName = (string) $collectionName;
 129          $this->documents = $documents;
 130          $this->options = $options;
 131      }
 132  
 133      /**
 134       * Execute the operation.
 135       *
 136       * @see Executable::execute()
 137       * @param Server $server
 138       * @return InsertManyResult
 139       * @throws DriverRuntimeException for other driver errors (e.g. connection errors)
 140       */
 141      public function execute(Server $server)
 142      {
 143          $inTransaction = isset($this->options['session']) && $this->options['session']->isInTransaction();
 144          if ($inTransaction && isset($this->options['writeConcern'])) {
 145              throw UnsupportedException::writeConcernNotSupportedInTransaction();
 146          }
 147  
 148          $options = ['ordered' => $this->options['ordered']];
 149  
 150          if (! empty($this->options['bypassDocumentValidation']) &&
 151              server_supports_feature($server, self::$wireVersionForDocumentLevelValidation)
 152          ) {
 153              $options['bypassDocumentValidation'] = $this->options['bypassDocumentValidation'];
 154          }
 155  
 156          $bulk = new Bulk($options);
 157          $insertedIds = [];
 158  
 159          foreach ($this->documents as $i => $document) {
 160              $insertedIds[$i] = $bulk->insert($document);
 161          }
 162  
 163          $writeResult = $server->executeBulkWrite($this->databaseName . '.' . $this->collectionName, $bulk, $this->createOptions());
 164  
 165          return new InsertManyResult($writeResult, $insertedIds);
 166      }
 167  
 168      /**
 169       * Create options for executing the bulk write.
 170       *
 171       * @see http://php.net/manual/en/mongodb-driver-server.executebulkwrite.php
 172       * @return array
 173       */
 174      private function createOptions()
 175      {
 176          $options = [];
 177  
 178          if (isset($this->options['session'])) {
 179              $options['session'] = $this->options['session'];
 180          }
 181  
 182          if (isset($this->options['writeConcern'])) {
 183              $options['writeConcern'] = $this->options['writeConcern'];
 184          }
 185  
 186          return $options;
 187      }
 188  }