Passed
Push — fix-php8 ( 3aefe5...729f03 )
by Alexander
11:01 queued 07:03
created

Command::resetSequence()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 5
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 3
CRAP Score 1

Importance

Changes 0
Metric Value
cc 1
eloc 2
nc 1
nop 2
dl 0
loc 5
ccs 3
cts 3
cp 1
crap 1
rs 10
c 0
b 0
f 0
1
<?php
2
/**
3
 * @link http://www.yiiframework.com/
4
 * @copyright Copyright (c) 2008 Yii Software LLC
5
 * @license http://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://secure.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|false|null 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 $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 $dependency the cache dependency associated with the cached query result.
123
     * @return $this the command object itself
124
     */
125 6
    public function cache($duration = null, $dependency = null)
126
    {
127 6
        $this->queryCacheDuration = $duration === null ? $this->db->queryCacheDuration : $duration;
128 6
        $this->queryCacheDependency = $dependency;
129 6
        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 1576
    public function getSql()
147
    {
148 1576
        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 1603
    public function setSql($sql)
162
    {
163 1603
        if ($sql !== $this->_sql) {
164 1603
            $this->cancel();
165 1603
            $this->reset();
166 1603
            $this->_sql = $this->db->quoteSql($sql);
167
        }
168
169 1603
        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 1582
    public function getRawSql()
201
    {
202 1582
        if (empty($this->params)) {
203 1396
            return $this->_sql;
204
        }
205 1134
        $params = [];
206 1134
        foreach ($this->params as $name => $value) {
207 1134
            if (is_string($name) && strncmp(':', $name, 1)) {
208 15
                $name = ':' . $name;
209
            }
210 1134
            if (is_string($value) || $value instanceof Expression) {
211 890
                $params[$name] = $this->db->quoteValue((string)$value);
212 887
            } elseif (is_bool($value)) {
213 25
                $params[$name] = ($value ? 'TRUE' : 'FALSE');
214 880
            } elseif ($value === null) {
215 329
                $params[$name] = 'NULL';
216 823
            } elseif (!is_object($value) && !is_resource($value)) {
217 1134
                $params[$name] = $value;
218
            }
219
        }
220 1134
        if (!isset($params[1])) {
221 1134
            return strtr($this->_sql, $params);
222
        }
223
        $sql = '';
224
        foreach (explode('?', $this->_sql) as $i => $part) {
225
            $sql .= (isset($params[$i]) ? $params[$i] : '') . $part;
226
        }
227
228
        return $sql;
229
    }
230
231
    /**
232
     * Prepares the SQL statement to be executed.
233
     * For complex SQL statement that is to be executed multiple times,
234
     * this may improve performance.
235
     * For SQL statement with binding parameters, this method is invoked
236
     * automatically.
237
     * @param bool $forRead whether this method is called for a read query. If null, it means
238
     * the SQL statement should be used to determine whether it is for read or write.
239
     * @throws Exception if there is any DB error
240
     */
241 1564
    public function prepare($forRead = null)
242
    {
243 1564
        if ($this->pdoStatement) {
244 60
            $this->bindPendingParams();
245 60
            return;
246
        }
247
248 1564
        $sql = $this->getSql();
249
250 1564
        if ($this->db->getTransaction()) {
251
            // master is in a transaction. use the same connection.
252 21
            $forRead = false;
253
        }
254 1564
        if ($forRead || $forRead === null && $this->db->getSchema()->isReadQuery($sql)) {
255 1514
            $pdo = $this->db->getSlavePdo();
256
        } else {
257 720
            $pdo = $this->db->getMasterPdo();
258
        }
259
260
        try {
261 1564
            $this->pdoStatement = $pdo->prepare($sql);
0 ignored issues
show
Documentation Bug introduced by
It seems like $pdo->prepare($sql) can also be of type boolean. However, the property $pdoStatement is declared as type PDOStatement. Maybe add an additional type check?

Our type inference engine has found a suspicous assignment of a value to a property. This check raises an issue when a value that can be of a mixed type is assigned to a property that is type hinted more strictly.

For example, imagine you have a variable $accountId that can either hold an Id object or false (if there is no account id yet). Your code now assigns that value to the id property of an instance of the Account class. This class holds a proper account, so the id value must no longer be false.

Either this assignment is in error or a type check should be added for that assignment.

class Id
{
    public $id;

    public function __construct($id)
    {
        $this->id = $id;
    }

}

class Account
{
    /** @var  Id $id */
    public $id;
}

$account_id = false;

if (starsAreRight()) {
    $account_id = new Id(42);
}

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

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