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

1300
                    }, /** @scrutinizer ignore-type */ $this->_isolationLevel);
Loading history...
1301
                } else {
1302 1623
                    $this->pdoStatement->execute();
1303
                }
1304 1620
                break;
1305 36
            } catch (\Exception $e) {
1306 36
                $rawSql = $rawSql ?: $this->getRawSql();
1307 36
                $e = $this->db->getSchema()->convertException($e, $rawSql);
1308 36
                if ($this->_retryHandler === null || !call_user_func($this->_retryHandler, $e, $attempt)) {
1309 36
                    throw $e;
1310
                }
1311
            }
1312
        }
1313 1620
    }
1314
1315
    /**
1316
     * Resets command properties to their initial state.
1317
     *
1318
     * @since 2.0.13
1319
     */
1320 1670
    protected function reset()
1321
    {
1322 1670
        $this->_sql = null;
1323 1670
        $this->pendingParams = [];
1324 1670
        $this->params = [];
1325 1670
        $this->_refreshTableName = null;
1326 1670
        $this->_isolationLevel = false;
1327 1670
    }
1328
}
1329