Completed
Push — 2.1 ( 21da0e...a39d12 )
by
unknown
10:45
created

Command::setRawSql()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 10
Code Lines 6

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 6
CRAP Score 2

Importance

Changes 0
Metric Value
dl 0
loc 10
ccs 6
cts 6
cp 1
rs 9.4285
c 0
b 0
f 0
cc 2
eloc 6
nc 2
nop 1
crap 2
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 http://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
     */
94
    private $_pendingParams = [];
95
    /**
96
     * @var string the SQL statement that this command represents
97
     */
98
    private $_sql;
99
    /**
100
     * @var string name of the table, which schema, should be refreshed after command execution.
101
     */
102
    private $_refreshTableName;
103
    /**
104
     * @var string|false|null the isolation level to use for this transaction.
105
     * See [[Transaction::begin()]] for details.
106
     */
107
    private $_isolationLevel = false;
108
    /**
109
     * @var callable a callable (e.g. anonymous function) that is called when [[\yii\db\Exception]] is thrown
110
     * when executing the command.
111
     */
112
    private $_retryHandler;
113
114
115
    /**
116
     * Enables query cache for this command.
117
     * @param int $duration the number of seconds that query result of this command can remain valid in the cache.
118
     * If this is not set, the value of [[Connection::queryCacheDuration]] will be used instead.
119
     * Use 0 to indicate that the cached data will never expire.
120
     * @param \yii\caching\Dependency $dependency the cache dependency associated with the cached query result.
121
     * @return $this the command object itself
122
     */
123 3
    public function cache($duration = null, $dependency = null)
124
    {
125 3
        $this->queryCacheDuration = $duration === null ? $this->db->queryCacheDuration : $duration;
126 3
        $this->queryCacheDependency = $dependency;
127 3
        return $this;
128
    }
129
130
    /**
131
     * Disables query cache for this command.
132
     * @return $this the command object itself
133
     */
134 3
    public function noCache()
135
    {
136 3
        $this->queryCacheDuration = -1;
137 3
        return $this;
138
    }
139
140
    /**
141
     * Returns the SQL statement for this command.
142
     * @return string the SQL statement to be executed
143
     */
144 1201
    public function getSql()
145
    {
146 1201
        return $this->_sql;
147
    }
148
149
    /**
150
     * Specifies the SQL statement to be executed. The SQL statement will be quoted using [[Connection::quoteSql()]].
151
     * The previous SQL (if any) will be discarded, and [[params]] will be cleared as well. See [[reset()]]
152
     * for details.
153
     *
154
     * @param string $sql the SQL statement to be set.
155
     * @return $this this command instance
156
     * @see reset()
157
     * @see cancel()
158
     */
159 1222
    public function setSql($sql)
160
    {
161 1222
        if ($sql !== $this->_sql) {
162 1222
            $this->cancel();
163 1222
            $this->reset();
164 1222
            $this->_sql = $this->db->quoteSql($sql);
165
        }
166
167 1222
        return $this;
168
    }
169
170
    /**
171
     * Specifies the SQL statement to be executed. The SQL statement will not be modified in any way.
172
     * The previous SQL (if any) will be discarded, and [[params]] will be cleared as well. See [[reset()]]
173
     * for details.
174
     *
175
     * @param string $sql the SQL statement to be set.
176
     * @return $this this command instance
177
     * @since 2.0.13
178
     * @see reset()
179
     * @see cancel()
180
     */
181 22
    public function setRawSql($sql)
182
    {
183 22
        if ($sql !== $this->_sql) {
184 22
            $this->cancel();
185 22
            $this->reset();
186 22
            $this->_sql = $sql;
187
        }
188
189 22
        return $this;
190
    }
191
192
    /**
193
     * Returns the raw SQL by inserting parameter values into the corresponding placeholders in [[sql]].
194
     * Note that the return value of this method should mainly be used for logging purpose.
195
     * It is likely that this method returns an invalid SQL due to improper replacement of parameter placeholders.
196
     * @return string the raw SQL with parameter values inserted into the corresponding placeholders in [[sql]].
197
     */
198 1204
    public function getRawSql()
199
    {
200 1204
        if (empty($this->params)) {
201 1049
            return $this->_sql;
202
        }
203 913
        $params = [];
204 913
        foreach ($this->params as $name => $value) {
205 913
            if (is_string($name) && strncmp(':', $name, 1)) {
206 15
                $name = ':' . $name;
207
            }
208 913
            if (is_string($value)) {
209 730
                $params[$name] = $this->db->quoteValue($value);
210 732
            } elseif (is_bool($value)) {
211 25
                $params[$name] = ($value ? 'TRUE' : 'FALSE');
212 725
            } elseif ($value === null) {
213 285
                $params[$name] = 'NULL';
214 682
            } elseif ((!is_object($value) && !is_resource($value)) || $value instanceof Expression) {
215 913
                $params[$name] = $value;
216
            }
217
        }
218 913
        if (!isset($params[1])) {
219 913
            return strtr($this->_sql, $params);
220
        }
221
        $sql = '';
222
        foreach (explode('?', $this->_sql) as $i => $part) {
223
            $sql .= (isset($params[$i]) ? $params[$i] : '') . $part;
224
        }
225
226
        return $sql;
227
    }
228
229
    /**
230
     * Prepares the SQL statement to be executed.
231
     * For complex SQL statement that is to be executed multiple times,
232
     * this may improve performance.
233
     * For SQL statement with binding parameters, this method is invoked
234
     * automatically.
235
     * @param bool $forRead whether this method is called for a read query. If null, it means
236
     * the SQL statement should be used to determine whether it is for read or write.
237
     * @throws Exception if there is any DB error
238
     */
239 1189
    public function prepare($forRead = null)
240
    {
241 1189
        if ($this->pdoStatement) {
242 48
            $this->bindPendingParams();
243 48
            return;
244
        }
245
246 1189
        $sql = $this->getSql();
247
248 1189
        if ($this->db->getTransaction()) {
249
            // master is in a transaction. use the same connection.
250 20
            $forRead = false;
251
        }
252 1189
        if ($forRead || $forRead === null && $this->db->getSchema()->isReadQuery($sql)) {
253 1145
            $pdo = $this->db->getSlavePdo();
254
        } else {
255 626
            $pdo = $this->db->getMasterPdo();
256
        }
257
258
        try {
259 1189
            $this->pdoStatement = $pdo->prepare($sql);
260 1188
            $this->bindPendingParams();
261 4
        } catch (\Exception $e) {
262 4
            $message = $e->getMessage() . "\nFailed to prepare SQL: $sql";
263 4
            $errorInfo = $e instanceof \PDOException ? $e->errorInfo : null;
264 4
            throw new Exception($message, $errorInfo, (int) $e->getCode(), $e);
265
        }
266 1188
    }
267
268
    /**
269
     * Cancels the execution of the SQL statement.
270
     * This method mainly sets [[pdoStatement]] to be null.
271
     */
272 1222
    public function cancel()
273
    {
274 1222
        $this->pdoStatement = null;
275 1222
    }
276
277
    /**
278
     * Binds a parameter to the SQL statement to be executed.
279
     * @param string|int $name parameter identifier. For a prepared statement
280
     * using named placeholders, this will be a parameter name of
281
     * the form `:name`. For a prepared statement using question mark
282
     * placeholders, this will be the 1-indexed position of the parameter.
283
     * @param mixed $value the PHP variable to bind to the SQL statement parameter (passed by reference)
284
     * @param int $dataType SQL data type of the parameter. If null, the type is determined by the PHP type of the value.
285
     * @param int $length length of the data type
286
     * @param mixed $driverOptions the driver-specific options
287
     * @return $this the current command being executed
288
     * @see http://www.php.net/manual/en/function.PDOStatement-bindParam.php
289
     */
290 3
    public function bindParam($name, &$value, $dataType = null, $length = null, $driverOptions = null)
291
    {
292 3
        $this->prepare();
293
294 3
        if ($dataType === null) {
295 3
            $dataType = $this->db->getSchema()->getPdoType($value);
296
        }
297 3
        if ($length === null) {
298 3
            $this->pdoStatement->bindParam($name, $value, $dataType);
299
        } elseif ($driverOptions === null) {
300
            $this->pdoStatement->bindParam($name, $value, $dataType, $length);
301
        } else {
302
            $this->pdoStatement->bindParam($name, $value, $dataType, $length, $driverOptions);
303
        }
304 3
        $this->params[$name] = &$value;
305
306 3
        return $this;
307
    }
308
309
    /**
310
     * Binds pending parameters that were registered via [[bindValue()]] and [[bindValues()]].
311
     * Note that this method requires an active [[pdoStatement]].
312
     */
313 1188
    protected function bindPendingParams()
314
    {
315 1188
        foreach ($this->_pendingParams as $name => $value) {
316 894
            $this->pdoStatement->bindValue($name, $value[0], $value[1]);
317
        }
318 1188
        $this->_pendingParams = [];
319 1188
    }
320
321
    /**
322
     * Binds a value to a parameter.
323
     * @param string|int $name Parameter identifier. For a prepared statement
324
     * using named placeholders, this will be a parameter name of
325
     * the form `:name`. For a prepared statement using question mark
326
     * placeholders, this will be the 1-indexed position of the parameter.
327
     * @param mixed $value The value to bind to the parameter
328
     * @param int $dataType SQL data type of the parameter. If null, the type is determined by the PHP type of the value.
329
     * @return $this the current command being executed
330
     * @see http://www.php.net/manual/en/function.PDOStatement-bindValue.php
331
     */
332 6
    public function bindValue($name, $value, $dataType = null)
333
    {
334 6
        if ($dataType === null) {
335 6
            $dataType = $this->db->getSchema()->getPdoType($value);
336
        }
337 6
        $this->_pendingParams[$name] = [$value, $dataType];
338 6
        $this->params[$name] = $value;
339
340 6
        return $this;
341
    }
342
343
    /**
344
     * Binds a list of values to the corresponding parameters.
345
     * This is similar to [[bindValue()]] except that it binds multiple values at a time.
346
     * Note that the SQL data type of each value is determined by its PHP type.
347
     * @param array $values the values to be bound. This must be given in terms of an associative
348
     * array with array keys being the parameter names, and array values the corresponding parameter values,
349
     * e.g. `[':name' => 'John', ':age' => 25]`. By default, the PDO type of each value is determined
350
     * by its PHP type. You may explicitly specify the PDO type by using an array: `[value, type]`,
351
     * e.g. `[':name' => 'John', ':profile' => [$profile, \PDO::PARAM_LOB]]`.
352
     * @return $this the current command being executed
353
     */
354 1222
    public function bindValues($values)
355
    {
356 1222
        if (empty($values)) {
357 1067
            return $this;
358
        }
359
360 913
        $schema = $this->db->getSchema();
361 913
        foreach ($values as $name => $value) {
362 913
            if (is_array($value)) {
363 97
                $this->_pendingParams[$name] = $value;
364 97
                $this->params[$name] = $value[0];
365
            } else {
366 913
                $type = $schema->getPdoType($value);
367 913
                $this->_pendingParams[$name] = [$value, $type];
368 913
                $this->params[$name] = $value;
369
            }
370
        }
371
372 913
        return $this;
373
    }
374
375
    /**
376
     * Executes the SQL statement and returns query result.
377
     * This method is for executing a SQL query that returns result set, such as `SELECT`.
378
     * @return DataReader the reader object for fetching the query result
379
     * @throws Exception execution failed
380
     */
381 9
    public function query()
382
    {
383 9
        return $this->queryInternal('');
384
    }
385
386
    /**
387
     * Executes the SQL statement and returns ALL rows at once.
388
     * @param int $fetchMode the result fetch mode. Please refer to [PHP manual](http://www.php.net/manual/en/function.PDOStatement-setFetchMode.php)
389
     * for valid fetch modes. If this parameter is null, the value set in [[fetchMode]] will be used.
390
     * @return array all rows of the query result. Each array element is an array representing a row of data.
391
     * An empty array is returned if the query results in nothing.
392
     * @throws Exception execution failed
393
     */
394 1030
    public function queryAll($fetchMode = null)
395
    {
396 1030
        return $this->queryInternal('fetchAll', $fetchMode);
397
    }
398
399
    /**
400
     * Executes the SQL statement and returns the first row of the result.
401
     * This method is best used when only the first row of result is needed for a query.
402
     * @param int $fetchMode the result fetch mode. Please refer to [PHP manual](http://php.net/manual/en/pdostatement.setfetchmode.php)
403
     * for valid fetch modes. If this parameter is null, the value set in [[fetchMode]] will be used.
404
     * @return array|false the first row (in terms of an array) of the query result. False is returned if the query
405
     * results in nothing.
406
     * @throws Exception execution failed
407
     */
408 419
    public function queryOne($fetchMode = null)
409
    {
410 419
        return $this->queryInternal('fetch', $fetchMode);
411
    }
412
413
    /**
414
     * Executes the SQL statement and returns the value of the first column in the first row of data.
415
     * This method is best used when only a single value is needed for a query.
416
     * @return string|null|false the value of the first column in the first row of the query result.
417
     * False is returned if there is no value.
418
     * @throws Exception execution failed
419
     */
420 278
    public function queryScalar()
421
    {
422 278
        $result = $this->queryInternal('fetchColumn', 0);
423 275
        if (is_resource($result) && get_resource_type($result) === 'stream') {
424 17
            return stream_get_contents($result);
425
        }
426
427 270
        return $result;
428
    }
429
430
    /**
431
     * Executes the SQL statement and returns the first column of the result.
432
     * This method is best used when only the first column of result (i.e. the first element in each row)
433
     * is needed for a query.
434
     * @return array the first column of the query result. Empty array is returned if the query results in nothing.
435
     * @throws Exception execution failed
436
     */
437 77
    public function queryColumn()
438
    {
439 77
        return $this->queryInternal('fetchAll', \PDO::FETCH_COLUMN);
440
    }
441
442
    /**
443
     * Creates an INSERT command.
444
     *
445
     * For example,
446
     *
447
     * ```php
448
     * $connection->createCommand()->insert('user', [
449
     *     'name' => 'Sam',
450
     *     'age' => 30,
451
     * ])->execute();
452
     * ```
453
     *
454
     * The method will properly escape the column names, and bind the values to be inserted.
455
     *
456
     * Note that the created command is not executed until [[execute()]] is called.
457
     *
458
     * @param string $table the table that new rows will be inserted into.
459
     * @param array|\yii\db\Query $columns the column data (name => value) to be inserted into the table or instance
460
     * of [[yii\db\Query|Query]] to perform INSERT INTO ... SELECT SQL statement.
461
     * Passing of [[yii\db\Query|Query]] is available since version 2.0.11.
462
     * @return $this the command object itself
463
     */
464 435
    public function insert($table, $columns)
465
    {
466 435
        $params = [];
467 435
        $sql = $this->db->getQueryBuilder()->insert($table, $columns, $params);
468
469 426
        return $this->setSql($sql)->bindValues($params);
470
    }
471
472
    /**
473
     * Creates a batch INSERT command.
474
     *
475
     * For example,
476
     *
477
     * ```php
478
     * $connection->createCommand()->batchInsert('user', ['name', 'age'], [
479
     *     ['Tom', 30],
480
     *     ['Jane', 20],
481
     *     ['Linda', 25],
482
     * ])->execute();
483
     * ```
484
     *
485
     * The method will properly escape the column names, and quote the values to be inserted.
486
     *
487
     * Note that the values in each row must match the corresponding column names.
488
     *
489
     * Also note that the created command is not executed until [[execute()]] is called.
490
     *
491
     * @param string $table the table that new rows will be inserted into.
492
     * @param array $columns the column names
493
     * @param array|\Generator $rows the rows to be batch inserted into the table
494
     * @return $this the command object itself
495
     */
496 22
    public function batchInsert($table, $columns, $rows)
497
    {
498 22
        $table = $this->db->quoteSql($table);
499 22
        $columns = array_map(function ($column) {
500 22
            return $this->db->quoteSql($column);
501 22
        }, $columns);
502
503 22
        $sql = $this->db->getQueryBuilder()->batchInsert($table, $columns, $rows);
504
505 22
        $this->setRawSql($sql);
506
507 22
        return $this;
508
    }
509
510
    /**
511
     * Creates an UPDATE command.
512
     *
513
     * For example,
514
     *
515
     * ```php
516
     * $connection->createCommand()->update('user', ['status' => 1], 'age > 30')->execute();
517
     * ```
518
     *
519
     * or with using parameter binding for the condition:
520
     *
521
     * ```php
522
     * $minAge = 30;
523
     * $connection->createCommand()->update('user', ['status' => 1], 'age > :minAge', [':minAge' => $minAge])->execute();
524
     * ```
525
     *
526
     * The method will properly escape the column names and bind the values to be updated.
527
     *
528
     * Note that the created command is not executed until [[execute()]] is called.
529
     *
530
     * @param string $table the table to be updated.
531
     * @param array $columns the column data (name => value) to be updated.
532
     * @param string|array $condition the condition that will be put in the WHERE part. Please
533
     * refer to [[Query::where()]] on how to specify condition.
534
     * @param array $params the parameters to be bound to the command
535
     * @return $this the command object itself
536
     */
537 111
    public function update($table, $columns, $condition = '', $params = [])
538
    {
539 111
        $sql = $this->db->getQueryBuilder()->update($table, $columns, $condition, $params);
540
541 111
        return $this->setSql($sql)->bindValues($params);
542
    }
543
544
    /**
545
     * Creates a DELETE command.
546
     *
547
     * For example,
548
     *
549
     * ```php
550
     * $connection->createCommand()->delete('user', 'status = 0')->execute();
551
     * ```
552
     *
553
     * or with using parameter binding for the condition:
554
     *
555
     * ```php
556
     * $status = 0;
557
     * $connection->createCommand()->delete('user', 'status = :status', [':status' => $status])->execute();
558
     * ```
559
     *
560
     * The method will properly escape the table and column names.
561
     *
562
     * Note that the created command is not executed until [[execute()]] is called.
563
     *
564
     * @param string $table the table where the data will be deleted from.
565
     * @param string|array $condition the condition that will be put in the WHERE part. Please
566
     * refer to [[Query::where()]] on how to specify condition.
567
     * @param array $params the parameters to be bound to the command
568
     * @return $this the command object itself
569
     */
570 336
    public function delete($table, $condition = '', $params = [])
571
    {
572 336
        $sql = $this->db->getQueryBuilder()->delete($table, $condition, $params);
573
574 336
        return $this->setSql($sql)->bindValues($params);
575
    }
576
577
    /**
578
     * Creates a SQL command for creating a new DB table.
579
     *
580
     * The columns in the new table should be specified as name-definition pairs (e.g. 'name' => 'string'),
581
     * where name stands for a column name which will be properly quoted by the method, and definition
582
     * stands for the column type which can contain an abstract DB type.
583
     * The method [[QueryBuilder::getColumnType()]] will be called
584
     * to convert the abstract column types to physical ones. For example, `string` will be converted
585
     * as `varchar(255)`, and `string not null` becomes `varchar(255) not null`.
586
     *
587
     * If a column is specified with definition only (e.g. 'PRIMARY KEY (name, type)'), it will be directly
588
     * inserted into the generated SQL.
589
     *
590
     * @param string $table the name of the table to be created. The name will be properly quoted by the method.
591
     * @param array $columns the columns (name => definition) in the new table.
592
     * @param string $options additional SQL fragment that will be appended to the generated SQL.
593
     * @return $this the command object itself
594
     */
595 125
    public function createTable($table, $columns, $options = null)
596
    {
597 125
        $sql = $this->db->getQueryBuilder()->createTable($table, $columns, $options);
598
599 125
        return $this->setSql($sql)->requireTableSchemaRefresh($table);
600
    }
601
602
    /**
603
     * Creates a SQL command for renaming a DB table.
604
     * @param string $table the table to be renamed. The name will be properly quoted by the method.
605
     * @param string $newName the new table name. The name will be properly quoted by the method.
606
     * @return $this the command object itself
607
     */
608 3
    public function renameTable($table, $newName)
609
    {
610 3
        $sql = $this->db->getQueryBuilder()->renameTable($table, $newName);
611
612 3
        return $this->setSql($sql)->requireTableSchemaRefresh($table);
613
    }
614
615
    /**
616
     * Creates a SQL command for dropping a DB table.
617
     * @param string $table the table to be dropped. The name will be properly quoted by the method.
618
     * @return $this the command object itself
619
     */
620 33
    public function dropTable($table)
621
    {
622 33
        $sql = $this->db->getQueryBuilder()->dropTable($table);
623
624 33
        return $this->setSql($sql)->requireTableSchemaRefresh($table);
625
    }
626
627
    /**
628
     * Creates a SQL command for truncating a DB table.
629
     * @param string $table the table to be truncated. The name will be properly quoted by the method.
630
     * @return $this the command object itself
631
     */
632 13
    public function truncateTable($table)
633
    {
634 13
        $sql = $this->db->getQueryBuilder()->truncateTable($table);
635
636 13
        return $this->setSql($sql);
637
    }
638
639
    /**
640
     * Creates a SQL command for adding a new DB column.
641
     * @param string $table the table that the new column will be added to. The table name will be properly quoted by the method.
642
     * @param string $column the name of the new column. The name will be properly quoted by the method.
643
     * @param string $type the column type. [[\yii\db\QueryBuilder::getColumnType()]] will be called
644
     * to convert the give column type to the physical one. For example, `string` will be converted
645
     * as `varchar(255)`, and `string not null` becomes `varchar(255) not null`.
646
     * @return $this the command object itself
647
     */
648 4
    public function addColumn($table, $column, $type)
649
    {
650 4
        $sql = $this->db->getQueryBuilder()->addColumn($table, $column, $type);
651
652 4
        return $this->setSql($sql)->requireTableSchemaRefresh($table);
653
    }
654
655
    /**
656
     * Creates a SQL command for dropping a DB column.
657
     * @param string $table the table whose column is to be dropped. The name will be properly quoted by the method.
658
     * @param string $column the name of the column to be dropped. The name will be properly quoted by the method.
659
     * @return $this the command object itself
660
     */
661
    public function dropColumn($table, $column)
662
    {
663
        $sql = $this->db->getQueryBuilder()->dropColumn($table, $column);
664
665
        return $this->setSql($sql)->requireTableSchemaRefresh($table);
666
    }
667
668
    /**
669
     * Creates a SQL command for renaming a column.
670
     * @param string $table the table whose column is to be renamed. The name will be properly quoted by the method.
671
     * @param string $oldName the old name of the column. The name will be properly quoted by the method.
672
     * @param string $newName the new name of the column. The name will be properly quoted by the method.
673
     * @return $this the command object itself
674
     */
675
    public function renameColumn($table, $oldName, $newName)
676
    {
677
        $sql = $this->db->getQueryBuilder()->renameColumn($table, $oldName, $newName);
678
679
        return $this->setSql($sql)->requireTableSchemaRefresh($table);
680
    }
681
682
    /**
683
     * Creates a SQL command for changing the definition of a column.
684
     * @param string $table the table whose column is to be changed. The table name will be properly quoted by the method.
685
     * @param string $column the name of the column to be changed. The name will be properly quoted by the method.
686
     * @param string $type the column type. [[\yii\db\QueryBuilder::getColumnType()]] will be called
687
     * to convert the give column type to the physical one. For example, `string` will be converted
688
     * as `varchar(255)`, and `string not null` becomes `varchar(255) not null`.
689
     * @return $this the command object itself
690
     */
691 2
    public function alterColumn($table, $column, $type)
692
    {
693 2
        $sql = $this->db->getQueryBuilder()->alterColumn($table, $column, $type);
694
695 2
        return $this->setSql($sql)->requireTableSchemaRefresh($table);
696
    }
697
698
    /**
699
     * Creates a SQL command for adding a primary key constraint to an existing table.
700
     * The method will properly quote the table and column names.
701
     * @param string $name the name of the primary key constraint.
702
     * @param string $table the table that the primary key constraint will be added to.
703
     * @param string|array $columns comma separated string or array of columns that the primary key will consist of.
704
     * @return $this the command object itself.
705
     */
706 2
    public function addPrimaryKey($name, $table, $columns)
707
    {
708 2
        $sql = $this->db->getQueryBuilder()->addPrimaryKey($name, $table, $columns);
709
710 2
        return $this->setSql($sql)->requireTableSchemaRefresh($table);
711
    }
712
713
    /**
714
     * Creates a SQL command for removing a primary key constraint to an existing table.
715
     * @param string $name the name of the primary key constraint to be removed.
716
     * @param string $table the table that the primary key constraint will be removed from.
717
     * @return $this the command object itself
718
     */
719 2
    public function dropPrimaryKey($name, $table)
720
    {
721 2
        $sql = $this->db->getQueryBuilder()->dropPrimaryKey($name, $table);
722
723 2
        return $this->setSql($sql)->requireTableSchemaRefresh($table);
724
    }
725
726
    /**
727
     * Creates a SQL command for adding a foreign key constraint to an existing table.
728
     * The method will properly quote the table and column names.
729
     * @param string $name the name of the foreign key constraint.
730
     * @param string $table the table that the foreign key constraint will be added to.
731
     * @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.
732
     * @param string $refTable the table that the foreign key references to.
733
     * @param string|array $refColumns the name of the column that the foreign key references to. If there are multiple columns, separate them with commas.
734
     * @param string $delete the ON DELETE option. Most DBMS support these options: RESTRICT, CASCADE, NO ACTION, SET DEFAULT, SET NULL
735
     * @param string $update the ON UPDATE option. Most DBMS support these options: RESTRICT, CASCADE, NO ACTION, SET DEFAULT, SET NULL
736
     * @return $this the command object itself
737
     */
738 4
    public function addForeignKey($name, $table, $columns, $refTable, $refColumns, $delete = null, $update = null)
739
    {
740 4
        $sql = $this->db->getQueryBuilder()->addForeignKey($name, $table, $columns, $refTable, $refColumns, $delete, $update);
741
742 4
        return $this->setSql($sql)->requireTableSchemaRefresh($table);
743
    }
744
745
    /**
746
     * Creates a SQL command for dropping a foreign key constraint.
747
     * @param string $name the name of the foreign key constraint to be dropped. The name will be properly quoted by the method.
748
     * @param string $table the table whose foreign is to be dropped. The name will be properly quoted by the method.
749
     * @return $this the command object itself
750
     */
751 4
    public function dropForeignKey($name, $table)
752
    {
753 4
        $sql = $this->db->getQueryBuilder()->dropForeignKey($name, $table);
754
755 4
        return $this->setSql($sql)->requireTableSchemaRefresh($table);
756
    }
757
758
    /**
759
     * Creates a SQL command for creating a new index.
760
     * @param string $name the name of the index. The name will be properly quoted by the method.
761
     * @param string $table the table that the new index will be created for. The table name will be properly quoted by the method.
762
     * @param string|array $columns the column(s) that should be included in the index. If there are multiple columns, please separate them
763
     * by commas. The column names will be properly quoted by the method.
764
     * @param bool $unique whether to add UNIQUE constraint on the created index.
765
     * @return $this the command object itself
766
     */
767 12
    public function createIndex($name, $table, $columns, $unique = false)
768
    {
769 12
        $sql = $this->db->getQueryBuilder()->createIndex($name, $table, $columns, $unique);
770
771 12
        return $this->setSql($sql)->requireTableSchemaRefresh($table);
772
    }
773
774
    /**
775
     * Creates a SQL command for dropping an index.
776
     * @param string $name the name of the index to be dropped. The name will be properly quoted by the method.
777
     * @param string $table the table whose index is to be dropped. The name will be properly quoted by the method.
778
     * @return $this the command object itself
779
     */
780 3
    public function dropIndex($name, $table)
781
    {
782 3
        $sql = $this->db->getQueryBuilder()->dropIndex($name, $table);
783
784 3
        return $this->setSql($sql)->requireTableSchemaRefresh($table);
785
    }
786
787
    /**
788
     * Creates a SQL command for adding an unique constraint to an existing table.
789
     * @param string $name the name of the unique constraint.
790
     * The name will be properly quoted by the method.
791
     * @param string $table the table that the unique constraint will be added to.
792
     * The name will be properly quoted by the method.
793
     * @param string|array $columns the name of the column to that the constraint will be added on.
794
     * If there are multiple columns, separate them with commas.
795
     * The name will be properly quoted by the method.
796
     * @return $this the command object itself.
797
     * @since 2.0.13
798
     */
799 2
    public function addUnique($name, $table, $columns)
800
    {
801 2
        $sql = $this->db->getQueryBuilder()->addUnique($name, $table, $columns);
802
803 2
        return $this->setSql($sql)->requireTableSchemaRefresh($table);
804
    }
805
806
    /**
807
     * Creates a SQL command for dropping an unique constraint.
808
     * @param string $name the name of the unique constraint to be dropped.
809
     * The name will be properly quoted by the method.
810
     * @param string $table the table whose unique constraint is to be dropped.
811
     * The name will be properly quoted by the method.
812
     * @return $this the command object itself.
813
     * @since 2.0.13
814
     */
815 2
    public function dropUnique($name, $table)
816
    {
817 2
        $sql = $this->db->getQueryBuilder()->dropUnique($name, $table);
818
819 2
        return $this->setSql($sql)->requireTableSchemaRefresh($table);
820
    }
821
822
    /**
823
     * Creates a SQL command for adding a check constraint to an existing table.
824
     * @param string $name the name of the check constraint.
825
     * The name will be properly quoted by the method.
826
     * @param string $table the table that the check constraint will be added to.
827
     * The name will be properly quoted by the method.
828
     * @param string $expression the SQL of the `CHECK` constraint.
829
     * @return $this the command object itself.
830
     * @since 2.0.13
831
     */
832 1
    public function addCheck($name, $table, $expression)
833
    {
834 1
        $sql = $this->db->getQueryBuilder()->addCheck($name, $table, $expression);
835
836 1
        return $this->setSql($sql)->requireTableSchemaRefresh($table);
837
    }
838
839
    /**
840
     * Creates a SQL command for dropping a check constraint.
841
     * @param string $name the name of the check constraint to be dropped.
842
     * The name will be properly quoted by the method.
843
     * @param string $table the table whose check constraint is to be dropped.
844
     * The name will be properly quoted by the method.
845
     * @return $this the command object itself.
846
     * @since 2.0.13
847
     */
848 1
    public function dropCheck($name, $table)
849
    {
850 1
        $sql = $this->db->getQueryBuilder()->dropCheck($name, $table);
851
852 1
        return $this->setSql($sql)->requireTableSchemaRefresh($table);
853
    }
854
855
    /**
856
     * Creates a SQL command for adding a default value constraint to an existing table.
857
     * @param string $name the name of the default value constraint.
858
     * The name will be properly quoted by the method.
859
     * @param string $table the table that the default value constraint will be added to.
860
     * The name will be properly quoted by the method.
861
     * @param string $column the name of the column to that the constraint will be added on.
862
     * The name will be properly quoted by the method.
863
     * @param mixed $value default value.
864
     * @return $this the command object itself.
865
     * @since 2.0.13
866
     */
867
    public function addDefaultValue($name, $table, $column, $value)
868
    {
869
        $sql = $this->db->getQueryBuilder()->addDefaultValue($name, $table, $column, $value);
870
871
        return $this->setSql($sql)->requireTableSchemaRefresh($table);
872
    }
873
874
    /**
875
     * Creates a SQL command for dropping a default value constraint.
876
     * @param string $name the name of the default value constraint to be dropped.
877
     * The name will be properly quoted by the method.
878
     * @param string $table the table whose default value constraint is to be dropped.
879
     * The name will be properly quoted by the method.
880
     * @return $this the command object itself.
881
     * @since 2.0.13
882
     */
883
    public function dropDefaultValue($name, $table)
884
    {
885
        $sql = $this->db->getQueryBuilder()->dropDefaultValue($name, $table);
886
887
        return $this->setSql($sql)->requireTableSchemaRefresh($table);
888
    }
889
890
    /**
891
     * Creates a SQL command for resetting the sequence value of a table's primary key.
892
     * The sequence will be reset such that the primary key of the next new row inserted
893
     * will have the specified value or 1.
894
     * @param string $table the name of the table whose primary key sequence will be reset
895
     * @param mixed $value the value for the primary key of the next new row inserted. If this is not set,
896
     * the next new row's primary key will have a value 1.
897
     * @return $this the command object itself
898
     * @throws NotSupportedException if this is not supported by the underlying DBMS
899
     */
900 8
    public function resetSequence($table, $value = null)
901
    {
902 8
        $sql = $this->db->getQueryBuilder()->resetSequence($table, $value);
903
904 8
        return $this->setSql($sql);
905
    }
906
907
    /**
908
     * Builds a SQL command for enabling or disabling integrity check.
909
     * @param bool $check whether to turn on or off the integrity check.
910
     * @param string $schema the schema name of the tables. Defaults to empty string, meaning the current
911
     * or default schema.
912
     * @param string $table the table name.
913
     * @return $this the command object itself
914
     * @throws NotSupportedException if this is not supported by the underlying DBMS
915
     */
916 4
    public function checkIntegrity($check = true, $schema = '', $table = '')
917
    {
918 4
        $sql = $this->db->getQueryBuilder()->checkIntegrity($check, $schema, $table);
919
920 4
        return $this->setSql($sql);
921
    }
922
923
    /**
924
     * Builds a SQL command for adding comment to column.
925
     *
926
     * @param string $table the table whose column is to be commented. The table name will be properly quoted by the method.
927
     * @param string $column the name of the column to be commented. The column name will be properly quoted by the method.
928
     * @param string $comment the text of the comment to be added. The comment will be properly quoted by the method.
929
     * @return $this the command object itself
930
     * @since 2.0.8
931
     */
932 2
    public function addCommentOnColumn($table, $column, $comment)
933
    {
934 2
        $sql = $this->db->getQueryBuilder()->addCommentOnColumn($table, $column, $comment);
935
936 2
        return $this->setSql($sql)->requireTableSchemaRefresh($table);
937
    }
938
939
    /**
940
     * Builds a SQL command for adding comment to table.
941
     *
942
     * @param string $table the table whose column is to be commented. The table name will be properly quoted by the method.
943
     * @param string $comment the text of the comment to be added. The comment will be properly quoted by the method.
944
     * @return $this the command object itself
945
     * @since 2.0.8
946
     */
947
    public function addCommentOnTable($table, $comment)
948
    {
949
        $sql = $this->db->getQueryBuilder()->addCommentOnTable($table, $comment);
950
951
        return $this->setSql($sql);
952
    }
953
954
    /**
955
     * Builds a SQL command for dropping comment from column.
956
     *
957
     * @param string $table the table whose column is to be commented. The table name will be properly quoted by the method.
958
     * @param string $column the name of the column to be commented. The column name will be properly quoted by the method.
959
     * @return $this the command object itself
960
     * @since 2.0.8
961
     */
962 2
    public function dropCommentFromColumn($table, $column)
963
    {
964 2
        $sql = $this->db->getQueryBuilder()->dropCommentFromColumn($table, $column);
965
966 2
        return $this->setSql($sql)->requireTableSchemaRefresh($table);
967
    }
968
969
    /**
970
     * Builds a SQL command for dropping comment from table.
971
     *
972
     * @param string $table the table whose column is to be commented. The table name will be properly quoted by the method.
973
     * @return $this the command object itself
974
     * @since 2.0.8
975
     */
976
    public function dropCommentFromTable($table)
977
    {
978
        $sql = $this->db->getQueryBuilder()->dropCommentFromTable($table);
979
980
        return $this->setSql($sql);
981
    }
982
983
    /**
984
     * Creates a SQL View.
985
     *
986
     * @param string $viewName the name of the view to be created.
987
     * @param string|Query $subquery the select statement which defines the view.
988
     * This can be either a string or a [[Query]] object.
989
     * @return $this the command object itself.
990
     * @since 2.0.14
991
     */
992 3
    public function createView($viewName, $subquery)
993
    {
994 3
        $sql = $this->db->getQueryBuilder()->createView($viewName, $subquery);
995
996 3
        return $this->setSql($sql)->requireTableSchemaRefresh($viewName);
997
    }
998
    
999
    /**
1000
     * Drops a SQL View.
1001
     *
1002
     * @param string $viewName the name of the view to be dropped.
1003
     * @return $this the command object itself.
1004
     * @since 2.0.14
1005
     */
1006 3
    public function dropView($viewName)
1007
    {
1008 3
        $sql = $this->db->getQueryBuilder()->dropView($viewName);
1009
1010 3
        return $this->setSql($sql)->requireTableSchemaRefresh($viewName);
1011
    }
1012
1013
    /**
1014
     * Executes the SQL statement.
1015
     * This method should only be used for executing non-query SQL statement, such as `INSERT`, `DELETE`, `UPDATE` SQLs.
1016
     * No result set will be returned.
1017
     * @return int number of rows affected by the execution.
1018
     * @throws Exception execution failed
1019
     */
1020 615
    public function execute()
1021
    {
1022 615
        $sql = $this->getSql();
1023 615
        [$profile, $rawSql] = $this->logQuery(__METHOD__);
0 ignored issues
show
Bug introduced by
The variable $profile does not exist. Did you forget to declare it?

This check marks access to variables or properties that have not been declared yet. While PHP has no explicit notion of declaring a variable, accessing it before a value is assigned to it is most likely a bug.

Loading history...
Bug introduced by
The variable $rawSql does not exist. Did you forget to declare it?

This check marks access to variables or properties that have not been declared yet. While PHP has no explicit notion of declaring a variable, accessing it before a value is assigned to it is most likely a bug.

Loading history...
1024
1025 615
        if ($sql == '') {
1026 6
            return 0;
1027
        }
1028
1029 612
        $this->prepare(false);
1030
1031
        try {
1032 612
            $profile and Yii::beginProfile($rawSql, __METHOD__);
1033
1034 612
            $this->internalExecute($rawSql);
1035 609
            $n = $this->pdoStatement->rowCount();
1036
1037 609
            $profile and Yii::endProfile($rawSql, __METHOD__);
1038
1039 609
            $this->refreshTableSchema();
1040
1041 609
            return $n;
1042 13
        } catch (Exception $e) {
1043 13
            $profile and Yii::endProfile($rawSql, __METHOD__);
1044 13
            throw $e;
1045
        }
1046
    }
1047
1048
    /**
1049
     * Logs the current database query if query logging is enabled and returns
1050
     * the profiling token if profiling is enabled.
1051
     * @param string $category the log category.
1052
     * @return array array of two elements, the first is boolean of whether profiling is enabled or not.
1053
     * The second is the rawSql if it has been created.
1054
     */
1055 1186
    private function logQuery($category)
1056
    {
1057 1186
        if ($this->db->enableLogging) {
1058 1186
            $rawSql = $this->getRawSql();
1059 1186
            Yii::info($rawSql, $category);
1060
        }
1061 1186
        if (!$this->db->enableProfiling) {
1062 7
            return [false, isset($rawSql) ? $rawSql : null];
1063
        }
1064
1065 1186
        return [true, isset($rawSql) ? $rawSql : $this->getRawSql()];
1066
    }
1067
1068
    /**
1069
     * Performs the actual DB query of a SQL statement.
1070
     * @param string $method method of PDOStatement to be called
1071
     * @param int $fetchMode the result fetch mode. Please refer to [PHP manual](http://www.php.net/manual/en/function.PDOStatement-setFetchMode.php)
1072
     * for valid fetch modes. If this parameter is null, the value set in [[fetchMode]] will be used.
1073
     * @return mixed the method execution result
1074
     * @throws Exception if the query causes any problem
1075
     * @since 2.0.1 this method is protected (was private before).
1076
     */
1077 1146
    protected function queryInternal($method, $fetchMode = null)
1078
    {
1079 1146
        [$profile, $rawSql] = $this->logQuery('yii\db\Command::query');
0 ignored issues
show
Bug introduced by
The variable $profile does not exist. Did you forget to declare it?

This check marks access to variables or properties that have not been declared yet. While PHP has no explicit notion of declaring a variable, accessing it before a value is assigned to it is most likely a bug.

Loading history...
Bug introduced by
The variable $rawSql seems only to be defined at a later point. Did you maybe move this code here without moving the variable definition?

This error can happen if you refactor code and forget to move the variable initialization.

Let’s take a look at a simple example:

function someFunction() {
    $x = 5;
    echo $x;
}

The above code is perfectly fine. Now imagine that we re-order the statements:

function someFunction() {
    echo $x;
    $x = 5;
}

In that case, $x would be read before it is initialized. This was a very basic example, however the principle is the same for the found issue.

Loading history...
1080
1081 1146
        if ($method !== '') {
1082 1143
            $info = $this->db->getQueryCacheInfo($this->queryCacheDuration, $this->queryCacheDependency);
1083 1143
            if (is_array($info)) {
1084
                /* @var $cache \yii\caching\CacheInterface */
1085 3
                $cache = $info[0];
1086
                $cacheKey = [
1087 3
                    __CLASS__,
1088 3
                    $method,
1089 3
                    $fetchMode,
1090 3
                    $this->db->dsn,
1091 3
                    $this->db->username,
1092 3
                    $rawSql ?: $rawSql = $this->getRawSql(),
0 ignored issues
show
Bug introduced by
The variable $rawSql seems only to be defined at a later point. Did you maybe move this code here without moving the variable definition?

This error can happen if you refactor code and forget to move the variable initialization.

Let’s take a look at a simple example:

function someFunction() {
    $x = 5;
    echo $x;
}

The above code is perfectly fine. Now imagine that we re-order the statements:

function someFunction() {
    echo $x;
    $x = 5;
}

In that case, $x would be read before it is initialized. This was a very basic example, however the principle is the same for the found issue.

Loading history...
1093
                ];
1094 3
                $result = $cache->get($cacheKey);
0 ignored issues
show
Documentation introduced by
$cacheKey is of type array<integer,?,{"0":"st...,"4":"string","5":"?"}>, but the function expects a string.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
1095 3
                if (is_array($result) && isset($result[0])) {
1096 3
                    Yii::debug('Query result served from cache', 'yii\db\Command::query');
1097 3
                    return $result[0];
1098
                }
1099
            }
1100
        }
1101
1102 1146
        $this->prepare(true);
1103
1104
        try {
1105 1145
            $profile and Yii::beginProfile($rawSql, 'yii\db\Command::query');
0 ignored issues
show
Bug introduced by
The variable $rawSql does not seem to be defined for all execution paths leading up to this point.

If you define a variable conditionally, it can happen that it is not defined for all execution paths.

Let’s take a look at an example:

function myFunction($a) {
    switch ($a) {
        case 'foo':
            $x = 1;
            break;

        case 'bar':
            $x = 2;
            break;
    }

    // $x is potentially undefined here.
    echo $x;
}

In the above example, the variable $x is defined if you pass “foo” or “bar” as argument for $a. However, since the switch statement has no default case statement, if you pass any other value, the variable $x would be undefined.

Available Fixes

  1. Check for existence of the variable explicitly:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        if (isset($x)) { // Make sure it's always set.
            echo $x;
        }
    }
    
  2. Define a default value for the variable:

    function myFunction($a) {
        $x = ''; // Set a default which gets overridden for certain paths.
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        echo $x;
    }
    
  3. Add a value for the missing path:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
    
            // We add support for the missing case.
            default:
                $x = '';
                break;
        }
    
        echo $x;
    }
    
Loading history...
1106
1107 1145
            $this->internalExecute($rawSql);
1108
1109 1142
            if ($method === '') {
1110 9
                $result = new DataReader($this);
1111
            } else {
1112 1139
                if ($fetchMode === null) {
1113 1046
                    $fetchMode = $this->fetchMode;
1114
                }
1115 1139
                $result = call_user_func_array([$this->pdoStatement, $method], (array) $fetchMode);
1116 1139
                $this->pdoStatement->closeCursor();
1117
            }
1118
1119 1142
            $profile and Yii::endProfile($rawSql, 'yii\db\Command::query');
1120 22
        } catch (Exception $e) {
1121 22
            $profile and Yii::endProfile($rawSql, 'yii\db\Command::query');
1122 22
            throw $e;
1123
        }
1124
1125 1142
        if (isset($cache, $cacheKey, $info)) {
1126 3
            $cache->set($cacheKey, [$result], $info[1], $info[2]);
1127 3
            Yii::debug('Saved query result in cache', 'yii\db\Command::query');
1128
        }
1129
1130 1142
        return $result;
1131
    }
1132
1133
    /**
1134
     * Marks a specified table schema to be refreshed after command execution.
1135
     * @param string $name name of the table, which schema should be refreshed.
1136
     * @return $this this command instance
1137
     * @since 2.0.6
1138
     */
1139 134
    protected function requireTableSchemaRefresh($name)
1140
    {
1141 134
        $this->_refreshTableName = $name;
1142 134
        return $this;
1143
    }
1144
1145
    /**
1146
     * Refreshes table schema, which was marked by [[requireTableSchemaRefresh()]].
1147
     * @since 2.0.6
1148
     */
1149 609
    protected function refreshTableSchema()
1150
    {
1151 609
        if ($this->_refreshTableName !== null) {
1152 134
            $this->db->getSchema()->refreshTableSchema($this->_refreshTableName);
1153
        }
1154 609
    }
1155
1156
    /**
1157
     * Marks the command to be executed in transaction.
1158
     * @param string|null $isolationLevel The isolation level to use for this transaction.
1159
     * See [[Transaction::begin()]] for details.
1160
     * @return $this this command instance.
1161
     * @since 2.0.14
1162
     */
1163 3
    protected function requireTransaction($isolationLevel = null)
1164
    {
1165 3
        $this->_isolationLevel = $isolationLevel;
1166 3
        return $this;
1167
    }
1168
1169
    /**
1170
     * Sets a callable (e.g. anonymous function) that is called when [[Exception]] is thrown
1171
     * when executing the command. The signature of the callable should be:
1172
     *
1173
     * ```php
1174
     * function (\yii\db\Exception $e, $attempt)
1175
     * {
1176
     *     // return true or false (whether to retry the command or rethrow $e)
1177
     * }
1178
     * ```
1179
     *
1180
     * The callable will recieve a database exception thrown and a current attempt
1181
     * (to execute the command) number starting from 1.
1182
     *
1183
     * @param callable $handler a PHP callback to handle database exceptions.
1184
     * @return $this this command instance.
1185
     * @since 2.0.14
1186
     */
1187 3
    protected function setRetryHandler(callable $handler)
1188
    {
1189 3
        $this->_retryHandler = $handler;
1190 3
        return $this;
1191
    }
1192
1193
    /**
1194
     * Executes a prepared statement.
1195
     *
1196
     * It's a wrapper around [[\PDOStatement::execute()]] to support transactions
1197
     * and retry handlers.
1198
     *
1199
     * @param string|null $rawSql the rawSql if it has been created.
1200
     * @throws Exception if execution failed.
1201
     * @since 2.0.14
1202
     */
1203 1185
    protected function internalExecute($rawSql)
1204
    {
1205 1185
        $attempt = 0;
1206 1185
        while (true) {
1207
            try {
1208
                if (
1209 1185
                    ++$attempt === 1
1210 1185
                    && $this->_isolationLevel !== false
1211 1185
                    && $this->db->getTransaction() === null
1212
                ) {
1213 3
                    $this->db->transaction(function () use ($rawSql) {
1214 3
                        $this->internalExecute($rawSql);
1215 3
                    }, $this->_isolationLevel);
1216
                } else {
1217 1185
                    $this->pdoStatement->execute();
1218
                }
1219 1182
                break;
1220 32
            } catch (\Exception $e) {
1221 32
                $rawSql = $rawSql ?: $this->getRawSql();
1222 32
                $e = $this->db->getSchema()->convertException($e, $rawSql);
1223 32
                if ($this->_retryHandler === null || !call_user_func($this->_retryHandler, $e, $attempt)) {
1224 32
                    throw $e;
1225
                }
1226
            }
1227
        }
1228 1182
    }
1229
1230
    /**
1231
     * Resets command properties to their initial state.
1232
     *
1233
     * @since 2.0.13
1234
     */
1235 1222
    protected function reset()
1236
    {
1237 1222
        $this->_sql = null;
1238 1222
        $this->_pendingParams = [];
1239 1222
        $this->params = [];
1240 1222
        $this->_refreshTableName = null;
1241 1222
        $this->_isolationLevel = false;
1242 1222
        $this->_retryHandler = null;
1243 1222
    }
1244
}
1245