Update.php 10.9 KB
Newer Older
1
<?php
2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
/*
 * Copyright 2015-2017 MongoDB, Inc.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
17 18 19

namespace MongoDB\Operation;

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 25
use MongoDB\Driver\WriteConcern;
use MongoDB\Exception\InvalidArgumentException;
26
use MongoDB\Exception\UnsupportedException;
27 28 29 30
use MongoDB\UpdateResult;
use function is_array;
use function is_bool;
use function is_object;
31
use function is_string;
32
use function MongoDB\is_first_key_operator;
33
use function MongoDB\is_pipeline;
34
use function MongoDB\server_supports_feature;
35 36 37 38 39 40 41 42 43 44

/**
 * Operation for the update command.
 *
 * This class is used internally by the ReplaceOne, UpdateMany, and UpdateOne
 * operation classes.
 *
 * @internal
 * @see http://docs.mongodb.org/manual/reference/command/update/
 */
45
class Update implements Executable, Explainable
46
{
47
    /** @var integer */
48
    private static $wireVersionForArrayFilters = 6;
49 50

    /** @var integer */
51
    private static $wireVersionForCollation = 5;
52 53

    /** @var integer */
54 55
    private static $wireVersionForDocumentLevelValidation = 4;

56
    /** @var integer */
57
    private static $wireVersionForHintServerSideError = 5;
58

59
    /** @var string */
60
    private $databaseName;
61 62

    /** @var string */
63
    private $collectionName;
64 65

    /** @var array|object */
66
    private $filter;
67 68

    /** @var array|object */
69
    private $update;
70 71

    /** @var array */
72 73 74 75 76 77 78
    private $options;

    /**
     * Constructs a update command.
     *
     * Supported options:
     *
79 80 81 82 83 84
     *  * arrayFilters (document array): A set of filters specifying to which
     *    array elements an update should apply.
     *
     *    This is not supported for server versions < 3.6 and will result in an
     *    exception at execution time if used.
     *
85 86 87 88 89
     *  * bypassDocumentValidation (boolean): If true, allows the write to
     *    circumvent document level validation.
     *
     *    For servers < 3.2, this option is ignored as document level validation
     *    is not available.
90
     *
91 92 93 94 95
     *  * collation (document): Collation specification.
     *
     *    This is not supported for server versions < 3.4 and will result in an
     *    exception at execution time if used.
     *
96 97 98 99 100 101 102
     *  * hint (string|document): The index to use. Specify either the index
     *    name as a string or the index key pattern as a document. If specified,
     *    then the query system will only consider plans using the hinted index.
     *
     *    This is not supported for server versions < 4.2 and will result in an
     *    exception at execution time if used.
     *
103 104 105 106
     *  * multi (boolean): When true, updates all documents matching the query.
     *    This option cannot be true if the $update argument is a replacement
     *    document (i.e. contains no update operators). The default is false.
     *
107 108 109 110
     *  * session (MongoDB\Driver\Session): Client session.
     *
     *    Sessions are not supported for server versions < 3.6.
     *
111 112 113 114 115 116 117 118 119 120 121
     *  * upsert (boolean): When true, a new document is created if no document
     *    matches the query. The default is false.
     *
     *  * writeConcern (MongoDB\Driver\WriteConcern): Write concern.
     *
     * @param string       $databaseName   Database name
     * @param string       $collectionName Collection name
     * @param array|object $filter         Query by which to delete documents
     * @param array|object $update         Update to apply to the matched
     *                                     document(s) or a replacement document
     * @param array        $options        Command options
122
     * @throws InvalidArgumentException for parameter/option parsing errors
123
     */
Jeremy Mikola's avatar
Jeremy Mikola committed
124
    public function __construct($databaseName, $collectionName, $filter, $update, array $options = [])
125
    {
126
        if (! is_array($filter) && ! is_object($filter)) {
127
            throw InvalidArgumentException::invalidType('$filter', $filter, 'array or object');
128 129
        }

130
        if (! is_array($update) && ! is_object($update)) {
131
            throw InvalidArgumentException::invalidType('$update', $filter, 'array or object');
132 133
        }

Jeremy Mikola's avatar
Jeremy Mikola committed
134
        $options += [
135 136
            'multi' => false,
            'upsert' => false,
Jeremy Mikola's avatar
Jeremy Mikola committed
137
        ];
138

139 140 141 142
        if (isset($options['arrayFilters']) && ! is_array($options['arrayFilters'])) {
            throw InvalidArgumentException::invalidType('"arrayFilters" option', $options['arrayFilters'], 'array');
        }

143
        if (isset($options['bypassDocumentValidation']) && ! is_bool($options['bypassDocumentValidation'])) {
144
            throw InvalidArgumentException::invalidType('"bypassDocumentValidation" option', $options['bypassDocumentValidation'], 'boolean');
145 146
        }

147 148 149 150
        if (isset($options['collation']) && ! is_array($options['collation']) && ! is_object($options['collation'])) {
            throw InvalidArgumentException::invalidType('"collation" option', $options['collation'], 'array or object');
        }

151 152 153 154
        if (isset($options['hint']) && ! is_string($options['hint']) && ! is_array($options['hint']) && ! is_object($options['hint'])) {
            throw InvalidArgumentException::invalidType('"hint" option', $options['hint'], ['string', 'array', 'object']);
        }

155
        if (! is_bool($options['multi'])) {
156
            throw InvalidArgumentException::invalidType('"multi" option', $options['multi'], 'boolean');
157 158
        }

159
        if ($options['multi'] && ! is_first_key_operator($update) && ! is_pipeline($update)) {
160 161 162
            throw new InvalidArgumentException('"multi" option cannot be true if $update is a replacement document');
        }

163
        if (isset($options['session']) && ! $options['session'] instanceof Session) {
164
            throw InvalidArgumentException::invalidType('"session" option', $options['session'], Session::class);
165 166
        }

167
        if (! is_bool($options['upsert'])) {
168
            throw InvalidArgumentException::invalidType('"upsert" option', $options['upsert'], 'boolean');
169 170
        }

171
        if (isset($options['writeConcern']) && ! $options['writeConcern'] instanceof WriteConcern) {
172
            throw InvalidArgumentException::invalidType('"writeConcern" option', $options['writeConcern'], WriteConcern::class);
173 174
        }

175 176 177 178
        if (isset($options['writeConcern']) && $options['writeConcern']->isDefault()) {
            unset($options['writeConcern']);
        }

179 180 181 182 183 184 185 186 187 188 189 190 191
        $this->databaseName = (string) $databaseName;
        $this->collectionName = (string) $collectionName;
        $this->filter = $filter;
        $this->update = $update;
        $this->options = $options;
    }

    /**
     * Execute the operation.
     *
     * @see Executable::execute()
     * @param Server $server
     * @return UpdateResult
192
     * @throws UnsupportedException if array filters or collation is used and unsupported
193
     * @throws DriverRuntimeException for other driver errors (e.g. connection errors)
194 195 196
     */
    public function execute(Server $server)
    {
197
        if (isset($this->options['arrayFilters']) && ! server_supports_feature($server, self::$wireVersionForArrayFilters)) {
198 199 200
            throw UnsupportedException::arrayFiltersNotSupported();
        }

201
        if (isset($this->options['collation']) && ! server_supports_feature($server, self::$wireVersionForCollation)) {
202 203 204
            throw UnsupportedException::collationNotSupported();
        }

205 206 207 208
        /* Server versions >= 3.4.0 raise errors for unknown update
         * options. For previous versions, the CRUD spec requires a client-side
         * error. */
        if (isset($this->options['hint']) && ! server_supports_feature($server, self::$wireVersionForHintServerSideError)) {
209 210 211
            throw UnsupportedException::hintNotSupported();
        }

212 213 214 215 216
        $inTransaction = isset($this->options['session']) && $this->options['session']->isInTransaction();
        if ($inTransaction && isset($this->options['writeConcern'])) {
            throw UnsupportedException::writeConcernNotSupportedInTransaction();
        }

217 218
        $bulkOptions = [];

219 220
        if (! empty($this->options['bypassDocumentValidation']) &&
            server_supports_feature($server, self::$wireVersionForDocumentLevelValidation)
221
        ) {
222 223 224 225
            $bulkOptions['bypassDocumentValidation'] = $this->options['bypassDocumentValidation'];
        }

        $bulk = new Bulk($bulkOptions);
226
        $bulk->update($this->filter, $this->update, $this->createUpdateOptions());
227

228
        $writeResult = $server->executeBulkWrite($this->databaseName . '.' . $this->collectionName, $bulk, $this->createExecuteOptions());
229 230 231

        return new UpdateResult($writeResult);
    }
232

233
    public function getCommandDocument(Server $server)
234
    {
235 236 237 238 239 240
        $cmd = ['update' => $this->collectionName, 'updates' => [['q' => $this->filter, 'u' => $this->update] + $this->createUpdateOptions()]];

        if (isset($this->options['writeConcern'])) {
            $cmd['writeConcern'] = $this->options['writeConcern'];
        }

241 242
        if (! empty($this->options['bypassDocumentValidation']) &&
            server_supports_feature($server, self::$wireVersionForDocumentLevelValidation)
243
        ) {
244 245 246 247
            $cmd['bypassDocumentValidation'] = $this->options['bypassDocumentValidation'];
        }

        return $cmd;
248 249
    }

250 251 252 253 254 255
    /**
     * Create options for executing the bulk write.
     *
     * @see http://php.net/manual/en/mongodb-driver-server.executebulkwrite.php
     * @return array
     */
256
    private function createExecuteOptions()
257 258 259 260 261 262 263 264 265 266 267 268 269
    {
        $options = [];

        if (isset($this->options['session'])) {
            $options['session'] = $this->options['session'];
        }

        if (isset($this->options['writeConcern'])) {
            $options['writeConcern'] = $this->options['writeConcern'];
        }

        return $options;
    }
270 271 272 273 274

    /**
     * Create options for the update command.
     *
     * Note that these options are different from the bulk write options, which
275
     * are created in createExecuteOptions().
276 277 278 279 280 281 282 283 284 285
     *
     * @return array
     */
    private function createUpdateOptions()
    {
        $updateOptions = [
            'multi' => $this->options['multi'],
            'upsert' => $this->options['upsert'],
        ];

286 287 288 289
        foreach (['arrayFilters', 'hint'] as $option) {
            if (isset($this->options[$option])) {
                $updateOptions[$option] = $this->options[$option];
            }
290 291 292 293 294 295 296 297
        }

        if (isset($this->options['collation'])) {
            $updateOptions['collation'] = (object) $this->options['collation'];
        }

        return $updateOptions;
    }
298
}