Passed
Pull Request — master (#19887)
by
unknown
08:11
created

Command::prepare()   B

Complexity

Conditions 10
Paths 30

Size

Total Lines 32
Code Lines 22

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 18
CRAP Score 10.2918

Importance

Changes 0
Metric Value
cc 10
eloc 22
c 0
b 0
f 0
nc 30
nop 1
dl 0
loc 32
ccs 18
cts 21
cp 0.8571
crap 10.2918
rs 7.6666

How to fix   Complexity   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

1
<?php
2
/**
3
 * @link https://www.yiiframework.com/
4
 * @copyright Copyright (c) 2008 Yii Software LLC
5
 * @license https://www.yiiframework.com/license/
6
 */
7
8
namespace yii\db;
9
10
use Yii;
11
use yii\base\Component;
12
use yii\base\NotSupportedException;
13
14
/**
15
 * Command represents a SQL statement to be executed against a database.
16
 *
17
 * A command object is usually created by calling [[Connection::createCommand()]].
18
 * The SQL statement it represents can be set via the [[sql]] property.
19
 *
20
 * To execute a non-query SQL (such as INSERT, DELETE, UPDATE), call [[execute()]].
21
 * To execute a SQL statement that returns a result data set (such as SELECT),
22
 * use [[queryAll()]], [[queryOne()]], [[queryColumn()]], [[queryScalar()]], or [[query()]].
23
 *
24
 * For example,
25
 *
26
 * ```php
27
 * $users = $connection->createCommand('SELECT * FROM user')->queryAll();
28
 * ```
29
 *
30
 * Command supports SQL statement preparation and parameter binding.
31
 * Call [[bindValue()]] to bind a value to a SQL parameter;
32
 * Call [[bindParam()]] to bind a PHP variable to a SQL parameter.
33
 * When binding a parameter, the SQL statement is automatically prepared.
34
 * You may also call [[prepare()]] explicitly to prepare a SQL statement.
35
 *
36
 * Command also supports building SQL statements by providing methods such as [[insert()]],
37
 * [[update()]], etc. For example, the following code will create and execute an INSERT SQL statement:
38
 *
39
 * ```php
40
 * $connection->createCommand()->insert('user', [
41
 *     'name' => 'Sam',
42
 *     'age' => 30,
43
 * ])->execute();
44
 * ```
45
 *
46
 * To build SELECT SQL statements, please use [[Query]] instead.
47
 *
48
 * For more details and usage information on Command, see the [guide article on Database Access Objects](guide:db-dao).
49
 *
50
 * @property string $rawSql The raw SQL with parameter values inserted into the corresponding placeholders in
51
 * [[sql]].
52
 * @property string $sql The SQL statement to be executed.
53
 *
54
 * @author Qiang Xue <[email protected]>
55
 * @since 2.0
56
 */
57
class Command extends Component
58
{
59
    /**
60
     * @var Connection the DB connection that this command is associated with
61
     */
62
    public $db;
63
    /**
64
     * @var \PDOStatement the PDOStatement object that this command is associated with
65
     */
66
    public $pdoStatement;
67
    /**
68
     * @var int the default fetch mode for this command.
69
     * @see https://www.php.net/manual/en/pdostatement.setfetchmode.php
70
     */
71
    public $fetchMode = \PDO::FETCH_ASSOC;
72
    /**
73
     * @var array the parameters (name => value) that are bound to the current PDO statement.
74
     * This property is maintained by methods such as [[bindValue()]]. It is mainly provided for logging purpose
75
     * and is used to generate [[rawSql]]. Do not modify it directly.
76
     */
77
    public $params = [];
78
    /**
79
     * @var int the default number of seconds that query results can remain valid in cache.
80
     * Use 0 to indicate that the cached data will never expire. And use a negative number to indicate
81
     * query cache should not be used.
82
     * @see cache()
83
     */
84
    public $queryCacheDuration;
85
    /**
86
     * @var \yii\caching\Dependency the dependency to be associated with the cached query result for this command
87
     * @see cache()
88
     */
89
    public $queryCacheDependency;
90
91
    /**
92
     * @var array pending parameters to be bound to the current PDO statement.
93
     * @since 2.0.33
94
     */
95
    protected $pendingParams = [];
96
97
    /**
98
     * @var string the SQL statement that this command represents
99
     */
100
    private $_sql;
101
    /**
102
     * @var string name of the table, which schema, should be refreshed after command execution.
103
     */
104
    private $_refreshTableName;
105
    /**
106
     * @var string|null|false the isolation level to use for this transaction.
107
     * See [[Transaction::begin()]] for details.
108
     */
109
    private $_isolationLevel = false;
110
    /**
111
     * @var callable a callable (e.g. anonymous function) that is called when [[\yii\db\Exception]] is thrown
112
     * when executing the command.
113
     */
114
    private $_retryHandler;
115
116
117
    /**
118
     * Enables query cache for this command.
119
     * @param int|null $duration the number of seconds that query result of this command can remain valid in the cache.
120
     * If this is not set, the value of [[Connection::queryCacheDuration]] will be used instead.
121
     * Use 0 to indicate that the cached data will never expire.
122
     * @param \yii\caching\Dependency|null $dependency the cache dependency associated with the cached query result.
123
     * @return $this the command object itself
124
     */
125 35
    public function cache($duration = null, $dependency = null)
126
    {
127 35
        $this->queryCacheDuration = $duration === null ? $this->db->queryCacheDuration : $duration;
128 35
        $this->queryCacheDependency = $dependency;
129 35
        return $this;
130
    }
131
132
    /**
133
     * Disables query cache for this command.
134
     * @return $this the command object itself
135
     */
136 3
    public function noCache()
137
    {
138 3
        $this->queryCacheDuration = -1;
139 3
        return $this;
140
    }
141
142
    /**
143
     * Returns the SQL statement for this command.
144
     * @return string the SQL statement to be executed
145
     */
146 1648
    public function getSql()
147
    {
148 1648
        return $this->_sql;
149
    }
150
151
    /**
152
     * Specifies the SQL statement to be executed. The SQL statement will be quoted using [[Connection::quoteSql()]].
153
     * The previous SQL (if any) will be discarded, and [[params]] will be cleared as well. See [[reset()]]
154
     * for details.
155
     *
156
     * @param string $sql the SQL statement to be set.
157
     * @return $this this command instance
158
     * @see reset()
159
     * @see cancel()
160
     */
161 1679
    public function setSql($sql)
162
    {
163 1679
        if ($sql !== $this->_sql) {
164 1679
            $this->cancel();
165 1679
            $this->reset();
166 1679
            $this->_sql = $this->db->quoteSql($sql);
167
        }
168
169 1679
        return $this;
170
    }
171
172
    /**
173
     * Specifies the SQL statement to be executed. The SQL statement will not be modified in any way.
174
     * The previous SQL (if any) will be discarded, and [[params]] will be cleared as well. See [[reset()]]
175
     * for details.
176
     *
177
     * @param string $sql the SQL statement to be set.
178
     * @return $this this command instance
179
     * @since 2.0.13
180
     * @see reset()
181
     * @see cancel()
182
     */
183 31
    public function setRawSql($sql)
184
    {
185 31
        if ($sql !== $this->_sql) {
186 31
            $this->cancel();
187 31
            $this->reset();
188 31
            $this->_sql = $sql;
189
        }
190
191 31
        return $this;
192
    }
193
194
    /**
195
     * Returns the raw SQL by inserting parameter values into the corresponding placeholders in [[sql]].
196
     * Note that the return value of this method should mainly be used for logging purpose.
197
     * It is likely that this method returns an invalid SQL due to improper replacement of parameter placeholders.
198
     * @return string the raw SQL with parameter values inserted into the corresponding placeholders in [[sql]].
199
     */
200 1658
    public function getRawSql()
201
    {
202 1658
        if (empty($this->params)) {
203 1456
            return $this->_sql;
204
        }
205 1189
        $params = [];
206 1189
        foreach ($this->params as $name => $value) {
207 1189
            if (is_string($name) && strncmp(':', $name, 1)) {
208 15
                $name = ':' . $name;
209
            }
210 1189
            if (is_string($value) || $value instanceof Expression) {
211 937
                $params[$name] = $this->db->quoteValue((string)$value);
212 935
            } elseif (is_bool($value)) {
213 29
                $params[$name] = ($value ? 'TRUE' : 'FALSE');
214 928
            } elseif ($value === null) {
215 341
                $params[$name] = 'NULL';
216 871
            } elseif (!is_object($value) && !is_resource($value)) {
217 871
                $params[$name] = $value;
218
            }
219
        }
220 1189
        if (!isset($params[1])) {
221
            return preg_replace_callback('#(:\w+)#', function($matches) use ($params) {
222 1186
                $m = $matches[1];
223 1186
                return isset($params[$m]) ? $params[$m] : $m;
224 1186
            }, $this->_sql);
225
        }
226 3
        $sql = '';
227 3
        foreach (explode('?', $this->_sql) as $i => $part) {
228 3
            $sql .= (isset($params[$i]) ? $params[$i] : '') . $part;
229
        }
230
231 3
        return $sql;
232
    }
233
234
    /**
235
     * Prepares the SQL statement to be executed.
236
     * For complex SQL statement that is to be executed multiple times,
237
     * this may improve performance.
238
     * For SQL statement with binding parameters, this method is invoked
239
     * automatically.
240
     * @param bool|null $forRead whether this method is called for a read query. If null, it means
241
     * the SQL statement should be used to determine whether it is for read or write.
242
     * @throws Exception if there is any DB error
243
     */
244 1636
    public function prepare($forRead = null)
245
    {
246 1636
        if ($this->pdoStatement) {
247 60
            $this->bindPendingParams();
248 60
            return;
249
        }
250
251 1636
        $sql = $this->getSql();
252 1636
        if ($sql === '') {
253 3
            return;
254
        }
255
256 1636
        if ($this->db->getTransaction()) {
257
            // master is in a transaction. use the same connection.
258 23
            $forRead = false;
259
        }
260 1636
        if ($forRead || $forRead === null && $this->db->getSchema()->isReadQuery($sql)) {
261 1579
            $pdo = $this->db->getSlavePdo(true);
262
        } else {
263 748
            $pdo = $this->db->getMasterPdo();
264
        }
265
266
        try {
267 1636
            $this->pdoStatement = $pdo->prepare($sql);
268 1635
            $this->bindPendingParams();
269 5
        } catch (\Exception $e) {
270 5
            $message = $e->getMessage() . "\nFailed to prepare SQL: $sql";
271 5
            $errorInfo = $e instanceof \PDOException ? $e->errorInfo : null;
272 5
            throw new Exception($message, $errorInfo, $e->getCode(), $e);
273
        } catch (\Throwable $e) {
274
            $message = $e->getMessage() . "\nFailed to prepare SQL: $sql";
275
            throw new Exception($message, null, $e->getCode(), $e);
276
        }
277 1635
    }
278
279
    /**
280
     * Cancels the execution of the SQL statement.
281
     * This method mainly sets [[pdoStatement]] to be null.
282
     */
283 1679
    public function cancel()
284
    {
285 1679
        $this->pdoStatement = null;
286 1679
    }
287
288
    /**
289
     * Binds a parameter to the SQL statement to be executed.
290
     * @param string|int $name parameter identifier. For a prepared statement
291
     * using named placeholders, this will be a parameter name of
292
     * the form `:name`. For a prepared statement using question mark
293
     * placeholders, this will be the 1-indexed position of the parameter.
294
     * @param mixed $value the PHP variable to bind to the SQL statement parameter (passed by reference)
295
     * @param int|null $dataType SQL data type of the parameter. If null, the type is determined by the PHP type of the value.
296
     * @param int|null $length length of the data type
297
     * @param mixed $driverOptions the driver-specific options
298
     * @return $this the current command being executed
299
     * @see https://www.php.net/manual/en/function.PDOStatement-bindParam.php
300
     */
301 3
    public function bindParam($name, &$value, $dataType = null, $length = null, $driverOptions = null)
302
    {
303 3
        $this->prepare();
304
305 3
        if ($dataType === null) {
306 3
            $dataType = $this->db->getSchema()->getPdoType($value);
307
        }
308 3
        if ($length === null) {
309 3
            $this->pdoStatement->bindParam($name, $value, $dataType);
310
        } elseif ($driverOptions === null) {
311
            $this->pdoStatement->bindParam($name, $value, $dataType, $length);
312
        } else {
313
            $this->pdoStatement->bindParam($name, $value, $dataType, $length, $driverOptions);
314
        }
315 3
        $this->params[$name] = &$value;
316
317 3
        return $this;
318
    }
319
320
    /**
321
     * Binds pending parameters that were registered via [[bindValue()]] and [[bindValues()]].
322
     * Note that this method requires an active [[pdoStatement]].
323
     */
324 1635
    protected function bindPendingParams()
325
    {
326 1635
        foreach ($this->pendingParams as $name => $value) {
327 1168
            $this->pdoStatement->bindValue($name, $value[0], $value[1]);
328
        }
329 1635
        $this->pendingParams = [];
330 1635
    }
331
332
    /**
333
     * Binds a value to a parameter.
334
     * @param string|int $name Parameter identifier. For a prepared statement
335
     * using named placeholders, this will be a parameter name of
336
     * the form `:name`. For a prepared statement using question mark
337
     * placeholders, this will be the 1-indexed position of the parameter.
338
     * @param mixed $value The value to bind to the parameter
339
     * @param int|null $dataType SQL data type of the parameter. If null, the type is determined by the PHP type of the value.
340
     * @return $this the current command being executed
341
     * @see https://www.php.net/manual/en/function.PDOStatement-bindValue.php
342
     */
343 6
    public function bindValue($name, $value, $dataType = null)
344
    {
345 6
        if ($dataType === null) {
346 6
            $dataType = $this->db->getSchema()->getPdoType($value);
347
        }
348 6
        $this->pendingParams[$name] = [$value, $dataType];
349 6
        $this->params[$name] = $value;
350
351 6
        return $this;
352
    }
353
354
    /**
355
     * Binds a list of values to the corresponding parameters.
356
     * This is similar to [[bindValue()]] except that it binds multiple values at a time.
357
     * Note that the SQL data type of each value is determined by its PHP type.
358
     * @param array $values the values to be bound. This must be given in terms of an associative
359
     * array with array keys being the parameter names, and array values the corresponding parameter values,
360
     * e.g. `[':name' => 'John', ':age' => 25]`. By default, the PDO type of each value is determined
361
     * by its PHP type. You may explicitly specify the PDO type by using a [[yii\db\PdoValue]] class: `new PdoValue(value, type)`,
362
     * e.g. `[':name' => 'John', ':profile' => new PdoValue($profile, \PDO::PARAM_LOB)]`.
363
     * @return $this the current command being executed
364
     */
365 1679
    public function bindValues($values)
366
    {
367 1679
        if (empty($values)) {
368 1480
            return $this;
369
        }
370
371 1197
        $schema = $this->db->getSchema();
372 1197
        foreach ($values as $name => $value) {
373 1197
            if (is_array($value)) { // TODO: Drop in Yii 2.1
374 3
                $this->pendingParams[$name] = $value;
375 3
                $this->params[$name] = $value[0];
376 1194
            } elseif ($value instanceof PdoValue) {
377 108
                $this->pendingParams[$name] = [$value->getValue(), $value->getType()];
378 108
                $this->params[$name] = $value->getValue();
379
            } else {
380 1194
                if (version_compare(PHP_VERSION, '8.1.0') >= 0
381 1194
                    && $value instanceof \UnitEnum
0 ignored issues
show
Bug introduced by
The type UnitEnum was not found. Maybe you did not declare it correctly or list all dependencies?

The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g. excluded_paths: ["lib/*"], you can move it to the dependency path list as follows:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

Loading history...
382
                ) {
383
                    $value = isset($value->value) ? $value->value : $value->name;
384
                }
385 1194
                $type = $schema->getPdoType($value);
386 1194
                $this->pendingParams[$name] = [$value, $type];
387 1194
                $this->params[$name] = $value;
388
            }
389
        }
390
391 1197
        return $this;
392
    }
393
394
    /**
395
     * Executes the SQL statement and returns query result.
396
     * This method is for executing a SQL query that returns result set, such as `SELECT`.
397
     * @return DataReader the reader object for fetching the query result
398
     * @throws Exception execution failed
399
     */
400 15
    public function query()
401
    {
402 15
        return $this->queryInternal('');
403
    }
404
405
    /**
406
     * Executes the SQL statement and returns ALL rows at once.
407
     * @param int|null $fetchMode the result fetch mode. Please refer to [PHP manual](https://www.php.net/manual/en/function.PDOStatement-setFetchMode.php)
408
     * for valid fetch modes. If this parameter is null, the value set in [[fetchMode]] will be used.
409
     * @return array all rows of the query result. Each array element is an array representing a row of data.
410
     * An empty array is returned if the query results in nothing.
411
     * @throws Exception execution failed
412
     */
413 1422
    public function queryAll($fetchMode = null)
414
    {
415 1422
        return $this->queryInternal('fetchAll', $fetchMode);
416
    }
417
418
    /**
419
     * Executes the SQL statement and returns the first row of the result.
420
     * This method is best used when only the first row of result is needed for a query.
421
     * @param int|null $fetchMode the result fetch mode. Please refer to [PHP manual](https://www.php.net/manual/en/pdostatement.setfetchmode.php)
422
     * for valid fetch modes. If this parameter is null, the value set in [[fetchMode]] will be used.
423
     * @return array|false the first row (in terms of an array) of the query result. False is returned if the query
424
     * results in nothing.
425
     * @throws Exception execution failed
426
     */
427 518
    public function queryOne($fetchMode = null)
428
    {
429 518
        return $this->queryInternal('fetch', $fetchMode);
430
    }
431
432
    /**
433
     * Executes the SQL statement and returns the value of the first column in the first row of data.
434
     * This method is best used when only a single value is needed for a query.
435
     * @return string|int|null|false the value of the first column in the first row of the query result.
436
     * False is returned if there is no value.
437
     * @throws Exception execution failed
438
     */
439 371
    public function queryScalar()
440
    {
441 371
        $result = $this->queryInternal('fetchColumn', 0);
442 368
        if (is_resource($result) && get_resource_type($result) === 'stream') {
443 21
            return stream_get_contents($result);
444
        }
445
446 360
        return $result;
447
    }
448
449
    /**
450
     * Executes the SQL statement and returns the first column of the result.
451
     * This method is best used when only the first column of result (i.e. the first element in each row)
452
     * is needed for a query.
453
     * @return array the first column of the query result. Empty array is returned if the query results in nothing.
454
     * @throws Exception execution failed
455
     */
456 93
    public function queryColumn()
457
    {
458 93
        return $this->queryInternal('fetchAll', \PDO::FETCH_COLUMN);
459
    }
460
461
    /**
462
     * Creates an INSERT command.
463
     *
464
     * For example,
465
     *
466
     * ```php
467
     * $connection->createCommand()->insert('user', [
468
     *     'name' => 'Sam',
469
     *     'age' => 30,
470
     * ])->execute();
471
     * ```
472
     *
473
     * The method will properly escape the column names, and bind the values to be inserted.
474
     *
475
     * Note that the created command is not executed until [[execute()]] is called.
476
     *
477
     * @param string $table the table that new rows will be inserted into.
478
     * @param array|\yii\db\Query $columns the column data (name => value) to be inserted into the table or instance
479
     * of [[yii\db\Query|Query]] to perform INSERT INTO ... SELECT SQL statement.
480
     * Passing of [[yii\db\Query|Query]] is available since version 2.0.11.
481
     * @return $this the command object itself
482
     */
483 452
    public function insert($table, $columns)
484
    {
485 452
        $params = [];
486 452
        $sql = $this->db->getQueryBuilder()->insert($table, $columns, $params);
487
488 443
        return $this->setSql($sql)->bindValues($params);
489
    }
490
491
    /**
492
     * Creates a batch INSERT command.
493
     *
494
     * For example,
495
     *
496
     * ```php
497
     * $connection->createCommand()->batchInsert('user', ['name', 'age'], [
498
     *     ['Tom', 30],
499
     *     ['Jane', 20],
500
     *     ['Linda', 25],
501
     * ])->execute();
502
     * ```
503
     *
504
     * The method will properly escape the column names, and quote the values to be inserted.
505
     *
506
     * Note that the values in each row must match the corresponding column names.
507
     *
508
     * Also note that the created command is not executed until [[execute()]] is called.
509
     *
510
     * @param string $table the table that new rows will be inserted into.
511
     * @param array $columns the column names
512
     * @param array|\Generator $rows the rows to be batch inserted into the table
513
     * @return $this the command object itself
514
     */
515 31
    public function batchInsert($table, $columns, $rows)
516
    {
517 31
        $table = $this->db->quoteSql($table);
518
        $columns = array_map(function ($column) {
519 31
            return $this->db->quoteSql($column);
520 31
        }, $columns);
521
522 31
        $params = [];
523 31
        $sql = $this->db->getQueryBuilder()->batchInsert($table, $columns, $rows, $params);
524
525 31
        $this->setRawSql($sql);
526 31
        $this->bindValues($params);
527
528 31
        return $this;
529
    }
530
531
    /**
532
     * Creates a command to insert rows into a database table if
533
     * they do not already exist (matching unique constraints),
534
     * or update them if they do.
535
     *
536
     * For example,
537
     *
538
     * ```php
539
     * $sql = $queryBuilder->upsert('pages', [
540
     *     'name' => 'Front page',
541
     *     'url' => 'https://example.com/', // url is unique
542
     *     'visits' => 0,
543
     * ], [
544
     *     'visits' => new \yii\db\Expression('visits + 1'),
545
     * ], $params);
546
     * ```
547
     *
548
     * The method will properly escape the table and column names.
549
     *
550
     * @param string $table the table that new rows will be inserted into/updated in.
551
     * @param array|Query $insertColumns the column data (name => value) to be inserted into the table or instance
552
     * of [[Query]] to perform `INSERT INTO ... SELECT` SQL statement.
553
     * @param array|bool $updateColumns the column data (name => value) to be updated if they already exist.
554
     * If `true` is passed, the column data will be updated to match the insert column data.
555
     * If `false` is passed, no update will be performed if the column data already exists.
556
     * @param array $params the parameters to be bound to the command.
557
     * @return $this the command object itself.
558
     * @since 2.0.14
559
     */
560 71
    public function upsert($table, $insertColumns, $updateColumns = true, $params = [])
561
    {
562 71
        $sql = $this->db->getQueryBuilder()->upsert($table, $insertColumns, $updateColumns, $params);
563
564 71
        return $this->setSql($sql)->bindValues($params);
565
    }
566
567
    /**
568
     * Creates an UPDATE command.
569
     *
570
     * For example,
571
     *
572
     * ```php
573
     * $connection->createCommand()->update('user', ['status' => 1], 'age > 30')->execute();
574
     * ```
575
     *
576
     * or with using parameter binding for the condition:
577
     *
578
     * ```php
579
     * $minAge = 30;
580
     * $connection->createCommand()->update('user', ['status' => 1], 'age > :minAge', [':minAge' => $minAge])->execute();
581
     * ```
582
     *
583
     * The method will properly escape the column names and bind the values to be updated.
584
     *
585
     * Note that the created command is not executed until [[execute()]] is called.
586
     *
587
     * @param string $table the table to be updated.
588
     * @param array $columns the column data (name => value) to be updated.
589
     * @param string|array $condition the condition that will be put in the WHERE part. Please
590
     * refer to [[Query::where()]] on how to specify condition.
591
     * @param array $params the parameters to be bound to the command
592
     * @return $this the command object itself
593
     */
594 97
    public function update($table, $columns, $condition = '', $params = [])
595
    {
596 97
        $sql = $this->db->getQueryBuilder()->update($table, $columns, $condition, $params);
597
598 97
        return $this->setSql($sql)->bindValues($params);
599
    }
600
601
    /**
602
     * Creates a DELETE command.
603
     *
604
     * For example,
605
     *
606
     * ```php
607
     * $connection->createCommand()->delete('user', 'status = 0')->execute();
608
     * ```
609
     *
610
     * or with using parameter binding for the condition:
611
     *
612
     * ```php
613
     * $status = 0;
614
     * $connection->createCommand()->delete('user', 'status = :status', [':status' => $status])->execute();
615
     * ```
616
     *
617
     * The method will properly escape the table and column names.
618
     *
619
     * Note that the created command is not executed until [[execute()]] is called.
620
     *
621
     * @param string $table the table where the data will be deleted from.
622
     * @param string|array $condition the condition that will be put in the WHERE part. Please
623
     * refer to [[Query::where()]] on how to specify condition.
624
     * @param array $params the parameters to be bound to the command
625
     * @return $this the command object itself
626
     */
627 384
    public function delete($table, $condition = '', $params = [])
628
    {
629 384
        $sql = $this->db->getQueryBuilder()->delete($table, $condition, $params);
630
631 384
        return $this->setSql($sql)->bindValues($params);
632
    }
633
634
    /**
635
     * Creates a SQL command for creating a new DB table.
636
     *
637
     * The columns in the new table should be specified as name-definition pairs (e.g. 'name' => 'string'),
638
     * where name stands for a column name which will be properly quoted by the method, and definition
639
     * stands for the column type which must contain an abstract DB type. 
640
     * 
641
     * The method [[QueryBuilder::getColumnType()]] will be called
642
     * to convert the abstract column types to physical ones. For example, `string` will be converted
643
     * as `varchar(255)`, and `string not null` becomes `varchar(255) not null`.
644
     *
645
     * If a column is specified with definition only (e.g. 'PRIMARY KEY (name, type)'), it will be directly
646
     * inserted into the generated SQL.
647
     * 
648
     * Example usage:
649
     * ```php
650
     * Yii::$app->db->createCommand()->createTable('post', [
651
     *     'id' => 'pk',
652
     *     'title' => 'string',
653
     *     'text' => 'text',
654
     *     'column_name double precision null default null',
655
     * ]);                   
656
     * ```
657
     *
658
     * @param string $table the name of the table to be created. The name will be properly quoted by the method.
659
     * @param array $columns the columns (name => definition) in the new table.
660
     * @param string|null $options additional SQL fragment that will be appended to the generated SQL.
661
     * @return $this the command object itself
662
     */
663 161
    public function createTable($table, $columns, $options = null)
664
    {
665 161
        $sql = $this->db->getQueryBuilder()->createTable($table, $columns, $options);
666
667 161
        return $this->setSql($sql)->requireTableSchemaRefresh($table);
668
    }
669
670
    /**
671
     * Creates a SQL command for renaming a DB table.
672
     * @param string $table the table to be renamed. The name will be properly quoted by the method.
673
     * @param string $newName the new table name. The name will be properly quoted by the method.
674
     * @return $this the command object itself
675
     */
676 6
    public function renameTable($table, $newName)
677
    {
678 6
        $sql = $this->db->getQueryBuilder()->renameTable($table, $newName);
679
680 6
        return $this->setSql($sql)->requireTableSchemaRefresh($table);
681
    }
682
683
    /**
684
     * Creates a SQL command for dropping a DB table.
685
     * @param string $table the table to be dropped. The name will be properly quoted by the method.
686
     * @return $this the command object itself
687
     */
688 51
    public function dropTable($table)
689
    {
690 51
        $sql = $this->db->getQueryBuilder()->dropTable($table);
691
692 51
        return $this->setSql($sql)->requireTableSchemaRefresh($table);
693
    }
694
695
    /**
696
     * Creates a SQL command for truncating a DB table.
697
     * @param string $table the table to be truncated. The name will be properly quoted by the method.
698
     * @return $this the command object itself
699
     */
700 13
    public function truncateTable($table)
701
    {
702 13
        $sql = $this->db->getQueryBuilder()->truncateTable($table);
703
704 13
        return $this->setSql($sql);
705
    }
706
707
    /**
708
     * Creates a SQL command for adding a new DB column.
709
     * @param string $table the table that the new column will be added to. The table name will be properly quoted by the method.
710
     * @param string $column the name of the new column. The name will be properly quoted by the method.
711
     * @param string $type the column type. [[\yii\db\QueryBuilder::getColumnType()]] will be called
712
     * to convert the given column type to the physical one. For example, `string` will be converted
713
     * as `varchar(255)`, and `string not null` becomes `varchar(255) not null`.
714
     * @return $this the command object itself
715
     */
716 7
    public function addColumn($table, $column, $type)
717
    {
718 7
        $sql = $this->db->getQueryBuilder()->addColumn($table, $column, $type);
719
720 7
        return $this->setSql($sql)->requireTableSchemaRefresh($table);
721
    }
722
723
    /**
724
     * Creates a SQL command for dropping a DB column.
725
     * @param string $table the table whose column is to be dropped. The name will be properly quoted by the method.
726
     * @param string $column the name of the column to be dropped. The name will be properly quoted by the method.
727
     * @return $this the command object itself
728
     */
729
    public function dropColumn($table, $column)
730
    {
731
        $sql = $this->db->getQueryBuilder()->dropColumn($table, $column);
732
733
        return $this->setSql($sql)->requireTableSchemaRefresh($table);
734
    }
735
736
    /**
737
     * Creates a SQL command for renaming a column.
738
     * @param string $table the table whose column is to be renamed. The name will be properly quoted by the method.
739
     * @param string $oldName the old name of the column. The name will be properly quoted by the method.
740
     * @param string $newName the new name of the column. The name will be properly quoted by the method.
741
     * @return $this the command object itself
742
     */
743
    public function renameColumn($table, $oldName, $newName)
744
    {
745
        $sql = $this->db->getQueryBuilder()->renameColumn($table, $oldName, $newName);
746
747
        return $this->setSql($sql)->requireTableSchemaRefresh($table);
748
    }
749
750
    /**
751
     * Creates a SQL command for changing the definition of a column.
752
     * @param string $table the table whose column is to be changed. The table name will be properly quoted by the method.
753
     * @param string $column the name of the column to be changed. The name will be properly quoted by the method.
754
     * @param string $type the column type. [[\yii\db\QueryBuilder::getColumnType()]] will be called
755
     * to convert the give column type to the physical one. For example, `string` will be converted
756
     * as `varchar(255)`, and `string not null` becomes `varchar(255) not null`.
757
     * @return $this the command object itself
758
     */
759 2
    public function alterColumn($table, $column, $type)
760
    {
761 2
        $sql = $this->db->getQueryBuilder()->alterColumn($table, $column, $type);
762
763 2
        return $this->setSql($sql)->requireTableSchemaRefresh($table);
764
    }
765
766
    /**
767
     * Creates a SQL command for adding a primary key constraint to an existing table.
768
     * The method will properly quote the table and column names.
769
     * @param string $name the name of the primary key constraint.
770
     * @param string $table the table that the primary key constraint will be added to.
771
     * @param string|array $columns comma separated string or array of columns that the primary key will consist of.
772
     * @return $this the command object itself.
773
     */
774 2
    public function addPrimaryKey($name, $table, $columns)
775
    {
776 2
        $sql = $this->db->getQueryBuilder()->addPrimaryKey($name, $table, $columns);
777
778 2
        return $this->setSql($sql)->requireTableSchemaRefresh($table);
779
    }
780
781
    /**
782
     * Creates a SQL command for removing a primary key constraint to an existing table.
783
     * @param string $name the name of the primary key constraint to be removed.
784
     * @param string $table the table that the primary key constraint will be removed from.
785
     * @return $this the command object itself
786
     */
787 2
    public function dropPrimaryKey($name, $table)
788
    {
789 2
        $sql = $this->db->getQueryBuilder()->dropPrimaryKey($name, $table);
790
791 2
        return $this->setSql($sql)->requireTableSchemaRefresh($table);
792
    }
793
794
    /**
795
     * Creates a SQL command for adding a foreign key constraint to an existing table.
796
     * The method will properly quote the table and column names.
797
     * @param string $name the name of the foreign key constraint.
798
     * @param string $table the table that the foreign key constraint will be added to.
799
     * @param string|array $columns the name of the column to that the constraint will be added on. If there are multiple columns, separate them with commas.
800
     * @param string $refTable the table that the foreign key references to.
801
     * @param string|array $refColumns the name of the column that the foreign key references to. If there are multiple columns, separate them with commas.
802
     * @param string|null $delete the ON DELETE option. Most DBMS support these options: RESTRICT, CASCADE, NO ACTION, SET DEFAULT, SET NULL
803
     * @param string|null $update the ON UPDATE option. Most DBMS support these options: RESTRICT, CASCADE, NO ACTION, SET DEFAULT, SET NULL
804
     * @return $this the command object itself
805
     */
806 4
    public function addForeignKey($name, $table, $columns, $refTable, $refColumns, $delete = null, $update = null)
807
    {
808 4
        $sql = $this->db->getQueryBuilder()->addForeignKey($name, $table, $columns, $refTable, $refColumns, $delete, $update);
809
810 4
        return $this->setSql($sql)->requireTableSchemaRefresh($table);
811
    }
812
813
    /**
814
     * Creates a SQL command for dropping a foreign key constraint.
815
     * @param string $name the name of the foreign key constraint to be dropped. The name will be properly quoted by the method.
816
     * @param string $table the table whose foreign is to be dropped. The name will be properly quoted by the method.
817
     * @return $this the command object itself
818
     */
819 5
    public function dropForeignKey($name, $table)
820
    {
821 5
        $sql = $this->db->getQueryBuilder()->dropForeignKey($name, $table);
822
823 5
        return $this->setSql($sql)->requireTableSchemaRefresh($table);
824
    }
825
826
    /**
827
     * Creates a SQL command for creating a new index.
828
     * @param string $name the name of the index. The name will be properly quoted by the method.
829
     * @param string $table the table that the new index will be created for. The table name will be properly quoted by the method.
830
     * @param string|array $columns the column(s) that should be included in the index. If there are multiple columns, please separate them
831
     * by commas. The column names will be properly quoted by the method.
832
     * @param bool $unique whether to add UNIQUE constraint on the created index.
833
     * @return $this the command object itself
834
     */
835 12
    public function createIndex($name, $table, $columns, $unique = false)
836
    {
837 12
        $sql = $this->db->getQueryBuilder()->createIndex($name, $table, $columns, $unique);
838
839 12
        return $this->setSql($sql)->requireTableSchemaRefresh($table);
840
    }
841
842
    /**
843
     * Creates a SQL command for dropping an index.
844
     * @param string $name the name of the index to be dropped. The name will be properly quoted by the method.
845
     * @param string $table the table whose index is to be dropped. The name will be properly quoted by the method.
846
     * @return $this the command object itself
847
     */
848 3
    public function dropIndex($name, $table)
849
    {
850 3
        $sql = $this->db->getQueryBuilder()->dropIndex($name, $table);
851
852 3
        return $this->setSql($sql)->requireTableSchemaRefresh($table);
853
    }
854
855
    /**
856
     * Creates a SQL command for adding an unique constraint to an existing table.
857
     * @param string $name the name of the unique constraint.
858
     * The name will be properly quoted by the method.
859
     * @param string $table the table that the unique constraint will be added to.
860
     * The name will be properly quoted by the method.
861
     * @param string|array $columns the name of the column to that the constraint will be added on.
862
     * If there are multiple columns, separate them with commas.
863
     * The name will be properly quoted by the method.
864
     * @return $this the command object itself.
865
     * @since 2.0.13
866
     */
867 2
    public function addUnique($name, $table, $columns)
868
    {
869 2
        $sql = $this->db->getQueryBuilder()->addUnique($name, $table, $columns);
870
871 2
        return $this->setSql($sql)->requireTableSchemaRefresh($table);
872
    }
873
874
    /**
875
     * Creates a SQL command for dropping an unique constraint.
876
     * @param string $name the name of the unique constraint to be dropped.
877
     * The name will be properly quoted by the method.
878
     * @param string $table the table whose unique constraint is to be dropped.
879
     * The name will be properly quoted by the method.
880
     * @return $this the command object itself.
881
     * @since 2.0.13
882
     */
883 2
    public function dropUnique($name, $table)
884
    {
885 2
        $sql = $this->db->getQueryBuilder()->dropUnique($name, $table);
886
887 2
        return $this->setSql($sql)->requireTableSchemaRefresh($table);
888
    }
889
890
    /**
891
     * Creates a SQL command for adding a check constraint to an existing table.
892
     * @param string $name the name of the check constraint.
893
     * The name will be properly quoted by the method.
894
     * @param string $table the table that the check constraint will be added to.
895
     * The name will be properly quoted by the method.
896
     * @param string $expression the SQL of the `CHECK` constraint.
897
     * @return $this the command object itself.
898
     * @since 2.0.13
899
     */
900 1
    public function addCheck($name, $table, $expression)
901
    {
902 1
        $sql = $this->db->getQueryBuilder()->addCheck($name, $table, $expression);
903
904 1
        return $this->setSql($sql)->requireTableSchemaRefresh($table);
905
    }
906
907
    /**
908
     * Creates a SQL command for dropping a check constraint.
909
     * @param string $name the name of the check constraint to be dropped.
910
     * The name will be properly quoted by the method.
911
     * @param string $table the table whose check constraint is to be dropped.
912
     * The name will be properly quoted by the method.
913
     * @return $this the command object itself.
914
     * @since 2.0.13
915
     */
916 1
    public function dropCheck($name, $table)
917
    {
918 1
        $sql = $this->db->getQueryBuilder()->dropCheck($name, $table);
919
920 1
        return $this->setSql($sql)->requireTableSchemaRefresh($table);
921
    }
922
923
    /**
924
     * Creates a SQL command for adding a default value constraint to an existing table.
925
     * @param string $name the name of the default value constraint.
926
     * The name will be properly quoted by the method.
927
     * @param string $table the table that the default value constraint will be added to.
928
     * The name will be properly quoted by the method.
929
     * @param string $column the name of the column to that the constraint will be added on.
930
     * The name will be properly quoted by the method.
931
     * @param mixed $value default value.
932
     * @return $this the command object itself.
933
     * @since 2.0.13
934
     */
935
    public function addDefaultValue($name, $table, $column, $value)
936
    {
937
        $sql = $this->db->getQueryBuilder()->addDefaultValue($name, $table, $column, $value);
938
939
        return $this->setSql($sql)->requireTableSchemaRefresh($table);
940
    }
941
942
    /**
943
     * Creates a SQL command for dropping a default value constraint.
944
     * @param string $name the name of the default value constraint to be dropped.
945
     * The name will be properly quoted by the method.
946
     * @param string $table the table whose default value constraint is to be dropped.
947
     * The name will be properly quoted by the method.
948
     * @return $this the command object itself.
949
     * @since 2.0.13
950
     */
951
    public function dropDefaultValue($name, $table)
952
    {
953
        $sql = $this->db->getQueryBuilder()->dropDefaultValue($name, $table);
954
955
        return $this->setSql($sql)->requireTableSchemaRefresh($table);
956
    }
957
958
    /**
959
     * Creates a SQL command for resetting the sequence value of a table's primary key.
960
     * The sequence will be reset such that the primary key of the next new row inserted
961
     * will have the specified value or the maximum existing value +1.
962
     * @param string $table the name of the table whose primary key sequence will be reset
963
     * @param mixed $value the value for the primary key of the next new row inserted. If this is not set,
964
     * the next new row's primary key will have the maximum existing value +1.
965
     * @return $this the command object itself
966
     * @throws NotSupportedException if this is not supported by the underlying DBMS
967
     */
968 25
    public function resetSequence($table, $value = null)
969
    {
970 25
        $sql = $this->db->getQueryBuilder()->resetSequence($table, $value);
971
972 25
        return $this->setSql($sql);
973
    }
974
975
    /**
976
     * Executes a db command resetting the sequence value of a table's primary key.
977
     * Reason for execute is that some databases (Oracle) need several queries to do so.
978
     * The sequence is reset such that the primary key of the next new row inserted
979
     * will have the specified value or the maximum existing value +1.
980
     * @param string $table the name of the table whose primary key sequence is reset
981
     * @param mixed $value the value for the primary key of the next new row inserted. If this is not set,
982
     * the next new row's primary key will have the maximum existing value +1.
983
     * @throws NotSupportedException if this is not supported by the underlying DBMS
984
     * @since 2.0.16
985
     */
986 25
    public function executeResetSequence($table, $value = null)
987
    {
988 25
        return $this->db->getQueryBuilder()->executeResetSequence($table, $value);
989
    }
990
991
    /**
992
     * Builds a SQL command for enabling or disabling integrity check.
993
     * @param bool $check whether to turn on or off the integrity check.
994
     * @param string $schema the schema name of the tables. Defaults to empty string, meaning the current
995
     * or default schema.
996
     * @param string $table the table name.
997
     * @return $this the command object itself
998
     * @throws NotSupportedException if this is not supported by the underlying DBMS
999
     */
1000 4
    public function checkIntegrity($check = true, $schema = '', $table = '')
1001
    {
1002 4
        $sql = $this->db->getQueryBuilder()->checkIntegrity($check, $schema, $table);
1003
1004 4
        return $this->setSql($sql);
1005
    }
1006
1007
    /**
1008
     * Builds a SQL command for adding comment to column.
1009
     *
1010
     * @param string $table the table whose column is to be commented. The table name will be properly quoted by the method.
1011
     * @param string $column the name of the column to be commented. The column name will be properly quoted by the method.
1012
     * @param string $comment the text of the comment to be added. The comment will be properly quoted by the method.
1013
     * @return $this the command object itself
1014
     * @since 2.0.8
1015
     */
1016 2
    public function addCommentOnColumn($table, $column, $comment)
1017
    {
1018 2
        $sql = $this->db->getQueryBuilder()->addCommentOnColumn($table, $column, $comment);
1019
1020 2
        return $this->setSql($sql)->requireTableSchemaRefresh($table);
1021
    }
1022
1023
    /**
1024
     * Builds a SQL command for adding comment to table.
1025
     *
1026
     * @param string $table the table whose column is to be commented. The table name will be properly quoted by the method.
1027
     * @param string $comment the text of the comment to be added. The comment will be properly quoted by the method.
1028
     * @return $this the command object itself
1029
     * @since 2.0.8
1030
     */
1031
    public function addCommentOnTable($table, $comment)
1032
    {
1033
        $sql = $this->db->getQueryBuilder()->addCommentOnTable($table, $comment);
1034
1035
        return $this->setSql($sql);
1036
    }
1037
1038
    /**
1039
     * Builds a SQL command for dropping comment from column.
1040
     *
1041
     * @param string $table the table whose column is to be commented. The table name will be properly quoted by the method.
1042
     * @param string $column the name of the column to be commented. The column name will be properly quoted by the method.
1043
     * @return $this the command object itself
1044
     * @since 2.0.8
1045
     */
1046 2
    public function dropCommentFromColumn($table, $column)
1047
    {
1048 2
        $sql = $this->db->getQueryBuilder()->dropCommentFromColumn($table, $column);
1049
1050 2
        return $this->setSql($sql)->requireTableSchemaRefresh($table);
1051
    }
1052
1053
    /**
1054
     * Builds a SQL command for dropping comment from table.
1055
     *
1056
     * @param string $table the table whose column is to be commented. The table name will be properly quoted by the method.
1057
     * @return $this the command object itself
1058
     * @since 2.0.8
1059
     */
1060
    public function dropCommentFromTable($table)
1061
    {
1062
        $sql = $this->db->getQueryBuilder()->dropCommentFromTable($table);
1063
1064
        return $this->setSql($sql);
1065
    }
1066
1067
    /**
1068
     * Creates a SQL View.
1069
     *
1070
     * @param string $viewName the name of the view to be created.
1071
     * @param string|Query $subquery the select statement which defines the view.
1072
     * This can be either a string or a [[Query]] object.
1073
     * @return $this the command object itself.
1074
     * @since 2.0.14
1075
     */
1076 3
    public function createView($viewName, $subquery)
1077
    {
1078 3
        $sql = $this->db->getQueryBuilder()->createView($viewName, $subquery);
1079
1080 3
        return $this->setSql($sql)->requireTableSchemaRefresh($viewName);
1081
    }
1082
1083
    /**
1084
     * Drops a SQL View.
1085
     *
1086
     * @param string $viewName the name of the view to be dropped.
1087
     * @return $this the command object itself.
1088
     * @since 2.0.14
1089
     */
1090 5
    public function dropView($viewName)
1091
    {
1092 5
        $sql = $this->db->getQueryBuilder()->dropView($viewName);
1093
1094 5
        return $this->setSql($sql)->requireTableSchemaRefresh($viewName);
1095
    }
1096
1097
    /**
1098
     * Executes the SQL statement.
1099
     * This method should only be used for executing non-query SQL statement, such as `INSERT`, `DELETE`, `UPDATE` SQLs.
1100
     * No result set will be returned.
1101
     * @return int number of rows affected by the execution.
1102
     * @throws Exception execution failed
1103
     */
1104 724
    public function execute()
1105
    {
1106 724
        $sql = $this->getSql();
1107 724
        list($profile, $rawSql) = $this->logQuery(__METHOD__);
1108
1109 724
        if ($sql == '') {
1110 6
            return 0;
1111
        }
1112
1113 721
        $this->prepare(false);
1114
1115
        try {
1116 721
            $profile and Yii::beginProfile($rawSql, __METHOD__);
1117
1118 721
            $this->internalExecute($rawSql);
1119 718
            $n = $this->pdoStatement->rowCount();
1120
1121 718
            $profile and Yii::endProfile($rawSql, __METHOD__);
1122
1123 718
            $this->refreshTableSchema();
1124
1125 718
            return $n;
1126 18
        } catch (Exception $e) {
1127 18
            $profile and Yii::endProfile($rawSql, __METHOD__);
1128 18
            throw $e;
1129
        }
1130
    }
1131
1132
    /**
1133
     * Logs the current database query if query logging is enabled and returns
1134
     * the profiling token if profiling is enabled.
1135
     * @param string $category the log category.
1136
     * @return array array of two elements, the first is boolean of whether profiling is enabled or not.
1137
     * The second is the rawSql if it has been created.
1138
     */
1139 1633
    protected function logQuery($category)
1140
    {
1141 1633
        if ($this->db->enableLogging) {
1142 1633
            $rawSql = $this->getRawSql();
1143 1633
            Yii::info($rawSql, $category);
1144
        }
1145 1633
        if (!$this->db->enableProfiling) {
1146 7
            return [false, isset($rawSql) ? $rawSql : null];
1147
        }
1148
1149 1633
        return [true, isset($rawSql) ? $rawSql : $this->getRawSql()];
1150
    }
1151
1152
    /**
1153
     * Performs the actual DB query of a SQL statement.
1154
     * @param string $method method of PDOStatement to be called
1155
     * @param int|null $fetchMode the result fetch mode. Please refer to [PHP manual](https://www.php.net/manual/en/function.PDOStatement-setFetchMode.php)
1156
     * for valid fetch modes. If this parameter is null, the value set in [[fetchMode]] will be used.
1157
     * @return mixed the method execution result
1158
     * @throws Exception if the query causes any problem
1159
     * @since 2.0.1 this method is protected (was private before).
1160
     */
1161 1580
    protected function queryInternal($method, $fetchMode = null)
1162
    {
1163 1580
        list($profile, $rawSql) = $this->logQuery('yii\db\Command::query');
1164
1165 1580
        if ($method !== '') {
1166 1577
            $info = $this->db->getQueryCacheInfo($this->queryCacheDuration, $this->queryCacheDependency);
1167 1577
            if (is_array($info)) {
1168
                /* @var $cache \yii\caching\CacheInterface */
1169 6
                $cache = $info[0];
1170 6
                $cacheKey = $this->getCacheKey($method, $fetchMode, '');
1171 6
                $result = $cache->get($cacheKey);
1172 6
                if (is_array($result) && array_key_exists(0, $result)) {
1173 6
                    Yii::debug('Query result served from cache', 'yii\db\Command::query');
1174 6
                    return $result[0];
1175
                }
1176
            }
1177
        }
1178
1179 1580
        $this->prepare(true);
1180
1181
        try {
1182 1579
            $profile and Yii::beginProfile($rawSql, 'yii\db\Command::query');
1183
1184 1579
            $this->internalExecute($rawSql);
1185
1186 1576
            if ($method === '') {
1187 15
                $result = new DataReader($this);
1188
            } else {
1189 1573
                if ($fetchMode === null) {
1190 1441
                    $fetchMode = $this->fetchMode;
1191
                }
1192 1573
                $result = call_user_func_array([$this->pdoStatement, $method], (array) $fetchMode);
1193 1573
                $this->pdoStatement->closeCursor();
1194
            }
1195
1196 1576
            $profile and Yii::endProfile($rawSql, 'yii\db\Command::query');
1197 22
        } catch (Exception $e) {
1198 22
            $profile and Yii::endProfile($rawSql, 'yii\db\Command::query');
1199 22
            throw $e;
1200
        }
1201
1202 1576
        if (isset($cache, $cacheKey, $info)) {
1203 6
            $cache->set($cacheKey, [$result], $info[1], $info[2]);
1204 6
            Yii::debug('Saved query result in cache', 'yii\db\Command::query');
1205
        }
1206
1207 1576
        return $result;
1208
    }
1209
1210
    /**
1211
     * Returns the cache key for the query.
1212
     *
1213
     * @param string $method method of PDOStatement to be called
1214
     * @param int $fetchMode the result fetch mode. Please refer to [PHP manual](https://www.php.net/manual/en/function.PDOStatement-setFetchMode.php)
1215
     * for valid fetch modes.
1216
     * @return array the cache key
1217
     * @since 2.0.16
1218
     */
1219 6
    protected function getCacheKey($method, $fetchMode, $rawSql)
1220
    {
1221 6
        $params = $this->params;
1222 6
        ksort($params);
1223
        return [
1224 6
            __CLASS__,
1225 6
            $method,
1226 6
            $fetchMode,
1227 6
            $this->db->dsn,
1228 6
            $this->db->username,
1229 6
            $this->getSql(),
1230 6
            json_encode($params),
1231
        ];
1232
    }
1233
1234
    /**
1235
     * Marks a specified table schema to be refreshed after command execution.
1236
     * @param string $name name of the table, which schema should be refreshed.
1237
     * @return $this this command instance
1238
     * @since 2.0.6
1239
     */
1240 173
    protected function requireTableSchemaRefresh($name)
1241
    {
1242 173
        $this->_refreshTableName = $name;
1243 173
        return $this;
1244
    }
1245
1246
    /**
1247
     * Refreshes table schema, which was marked by [[requireTableSchemaRefresh()]].
1248
     * @since 2.0.6
1249
     */
1250 718
    protected function refreshTableSchema()
1251
    {
1252 718
        if ($this->_refreshTableName !== null) {
1253 170
            $this->db->getSchema()->refreshTableSchema($this->_refreshTableName);
1254
        }
1255 718
    }
1256
1257
    /**
1258
     * Marks the command to be executed in transaction.
1259
     * @param string|null $isolationLevel The isolation level to use for this transaction.
1260
     * See [[Transaction::begin()]] for details.
1261
     * @return $this this command instance.
1262
     * @since 2.0.14
1263
     */
1264 3
    protected function requireTransaction($isolationLevel = null)
1265
    {
1266 3
        $this->_isolationLevel = $isolationLevel;
1267 3
        return $this;
1268
    }
1269
1270
    /**
1271
     * Sets a callable (e.g. anonymous function) that is called when [[Exception]] is thrown
1272
     * when executing the command. The signature of the callable should be:
1273
     *
1274
     * ```php
1275
     * function (\yii\db\Exception $e, $attempt)
1276
     * {
1277
     *     // return true or false (whether to retry the command or rethrow $e)
1278
     * }
1279
     * ```
1280
     *
1281
     * The callable will recieve a database exception thrown and a current attempt
1282
     * (to execute the command) number starting from 1.
1283
     *
1284
     * @param callable $handler a PHP callback to handle database exceptions.
1285
     * @return $this this command instance.
1286
     * @since 2.0.14
1287
     */
1288 3
    protected function setRetryHandler(callable $handler)
1289
    {
1290 3
        $this->_retryHandler = $handler;
1291 3
        return $this;
1292
    }
1293
1294
    /**
1295
     * Executes a prepared statement.
1296
     *
1297
     * It's a wrapper around [[\PDOStatement::execute()]] to support transactions
1298
     * and retry handlers.
1299
     *
1300
     * @param string|null $rawSql the rawSql if it has been created.
1301
     * @throws Exception if execution failed.
1302
     * @since 2.0.14
1303
     */
1304 1632
    protected function internalExecute($rawSql)
1305
    {
1306 1632
        $attempt = 0;
1307 1632
        while (true) {
1308
            try {
1309
                if (
1310 1632
                    ++$attempt === 1
1311 1632
                    && $this->_isolationLevel !== false
1312 1632
                    && $this->db->getTransaction() === null
1313
                ) {
1314 3
                    $this->db->transaction(function () use ($rawSql) {
1315 3
                        $this->internalExecute($rawSql);
1316 3
                    }, $this->_isolationLevel);
0 ignored issues
show
Bug introduced by
It seems like $this->_isolationLevel can also be of type true; however, parameter $isolationLevel of yii\db\Connection::transaction() does only seem to accept null|string, maybe add an additional type check? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

1316
                    }, /** @scrutinizer ignore-type */ $this->_isolationLevel);
Loading history...
1317
                } else {
1318 1632
                    $this->pdoStatement->execute();
1319
                }
1320 1629
                break;
1321 36
            } catch (\Exception $e) {
1322 36
                $rawSql = $rawSql ?: $this->getRawSql();
1323 36
                $e = $this->db->getSchema()->convertException($e, $rawSql);
1324 36
                if ($this->_retryHandler === null || !call_user_func($this->_retryHandler, $e, $attempt)) {
1325 36
                    throw $e;
1326
                }
1327
            }
1328
        }
1329 1629
    }
1330
1331
    /**
1332
     * Resets command properties to their initial state.
1333
     *
1334
     * @since 2.0.13
1335
     */
1336 1679
    protected function reset()
1337
    {
1338 1679
        $this->_sql = null;
1339 1679
        $this->pendingParams = [];
1340 1679
        $this->params = [];
1341 1679
        $this->_refreshTableName = null;
1342 1679
        $this->_isolationLevel = false;
1343 1679
    }
1344
}
1345