Completed
Push — 14593-added-after-execute-even... ( c818c1 )
by Alexander
24:27 queued 21:14
created

Command   D

Complexity

Total Complexity 122

Size/Duplication

Total Lines 1198
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 10

Test Coverage

Coverage 91.8%

Importance

Changes 0
Metric Value
wmc 122
lcom 1
cbo 10
dl 0
loc 1198
c 0
b 0
f 0
ccs 280
cts 305
cp 0.918
rs 4.4102

58 Methods

Rating   Name   Duplication   Size   Complexity  
A cache() 0 6 2
A noCache() 0 5 1
A getSql() 0 4 1
A setSql() 0 10 2
A setRawSql() 0 10 2
C getRawSql() 0 30 15
C prepare() 0 28 8
A cancel() 0 4 1
A bindParam() 0 18 4
A bindPendingParams() 0 7 2
A bindValue() 0 10 2
A bindValues() 0 20 4
A query() 0 4 1
A queryAll() 0 4 1
A queryOne() 0 4 1
A queryScalar() 0 9 3
A queryColumn() 0 4 1
A insert() 0 7 1
A batchInsert() 0 13 1
A update() 0 6 1
A delete() 0 6 1
A createTable() 0 6 1
A renameTable() 0 6 1
A dropTable() 0 6 1
A truncateTable() 0 6 1
A addColumn() 0 6 1
A dropColumn() 0 6 1
A renameColumn() 0 6 1
A alterColumn() 0 6 1
A addPrimaryKey() 0 6 1
A dropPrimaryKey() 0 6 1
A addForeignKey() 0 6 1
A dropForeignKey() 0 6 1
A createIndex() 0 6 1
A dropIndex() 0 6 1
A addUnique() 0 6 1
A dropUnique() 0 6 1
A addCheck() 0 6 1
A dropCheck() 0 6 1
A addDefaultValue() 0 6 1
A dropDefaultValue() 0 6 1
A resetSequence() 0 6 1
A checkIntegrity() 0 6 1
A addCommentOnColumn() 0 6 1
A addCommentOnTable() 0 6 1
A dropCommentFromColumn() 0 6 1
A dropCommentFromTable() 0 6 1
A createView() 0 6 1
A dropView() 0 6 1
B execute() 0 31 6
B logQuery() 0 12 5
D queryInternal() 0 55 13
A requireTableSchemaRefresh() 0 5 1
A refreshTableSchema() 0 6 2
A requireTransaction() 0 5 1
A setRetryHandler() 0 5 1
D internalExecute() 0 26 9
A reset() 0 9 1

How to fix   Complexity   

Complex Class

Complex classes like Command often do a lot of different things. To break such a class down, we need to identify a cohesive component within that class. A common approach to find such a component is to look for fields/methods that share the same prefixes, or suffixes. You can also have a look at the cohesion graph to spot any un-connected, or weakly-connected components.

Once you have determined the fields that belong together, you can apply the Extract Class refactoring. If the component makes sense as a sub-class, Extract Subclass is also a candidate, and is often faster.

While breaking up the class, it is a good idea to analyze how other classes use Command, and based on these observations, apply Extract Interface, too.

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
     * @event Event an event that is triggered after a command is executed
61
     * @since 2.0.14
62
     */
63
    const EVENT_AFTER_EXECUTE = 'afterExecute';
64
65
    /**
66
     * @var Connection the DB connection that this command is associated with
67
     */
68
    public $db;
69
    /**
70
     * @var \PDOStatement the PDOStatement object that this command is associated with
71
     */
72
    public $pdoStatement;
73
    /**
74
     * @var int the default fetch mode for this command.
75
     * @see http://www.php.net/manual/en/pdostatement.setfetchmode.php
76
     */
77
    public $fetchMode = \PDO::FETCH_ASSOC;
78
    /**
79
     * @var array the parameters (name => value) that are bound to the current PDO statement.
80
     * This property is maintained by methods such as [[bindValue()]]. It is mainly provided for logging purpose
81
     * and is used to generate [[rawSql]]. Do not modify it directly.
82
     */
83
    public $params = [];
84
    /**
85
     * @var int the default number of seconds that query results can remain valid in cache.
86
     * Use 0 to indicate that the cached data will never expire. And use a negative number to indicate
87
     * query cache should not be used.
88
     * @see cache()
89
     */
90
    public $queryCacheDuration;
91
    /**
92
     * @var \yii\caching\Dependency the dependency to be associated with the cached query result for this command
93
     * @see cache()
94
     */
95
    public $queryCacheDependency;
96
97
    /**
98
     * @var array pending parameters to be bound to the current PDO statement.
99
     */
100
    private $_pendingParams = [];
101
    /**
102
     * @var string the SQL statement that this command represents
103
     */
104
    private $_sql;
105
    /**
106
     * @var string name of the table, which schema, should be refreshed after command execution.
107
     */
108
    private $_refreshTableName;
109
    /**
110
     * @var string|false|null the isolation level to use for this transaction.
111
     * See [[Transaction::begin()]] for details.
112
     */
113
    private $_isolationLevel = false;
114
    /**
115
     * @var callable a callable (e.g. anonymous function) that is called when [[\yii\db\Exception]] is thrown
116
     * when executing the command.
117
     */
118
    private $_retryHandler;
119
120
121
    /**
122
     * Enables query cache for this command.
123
     * @param int $duration the number of seconds that query result of this command can remain valid in the cache.
124
     * If this is not set, the value of [[Connection::queryCacheDuration]] will be used instead.
125
     * Use 0 to indicate that the cached data will never expire.
126
     * @param \yii\caching\Dependency $dependency the cache dependency associated with the cached query result.
127
     * @return $this the command object itself
128
     */
129 3
    public function cache($duration = null, $dependency = null)
130
    {
131 3
        $this->queryCacheDuration = $duration === null ? $this->db->queryCacheDuration : $duration;
132 3
        $this->queryCacheDependency = $dependency;
133 3
        return $this;
134
    }
135
136
    /**
137
     * Disables query cache for this command.
138
     * @return $this the command object itself
139
     */
140 3
    public function noCache()
141
    {
142 3
        $this->queryCacheDuration = -1;
143 3
        return $this;
144
    }
145
146
    /**
147
     * Returns the SQL statement for this command.
148
     * @return string the SQL statement to be executed
149
     */
150 1222
    public function getSql()
151
    {
152 1222
        return $this->_sql;
153
    }
154
155
    /**
156
     * Specifies the SQL statement to be executed. The SQL statement will be quoted using [[Connection::quoteSql()]].
157
     * The previous SQL (if any) will be discarded, and [[params]] will be cleared as well. See [[reset()]]
158
     * for details.
159
     *
160
     * @param string $sql the SQL statement to be set.
161
     * @return $this this command instance
162
     * @see reset()
163
     * @see cancel()
164
     */
165 1243
    public function setSql($sql)
166
    {
167 1243
        if ($sql !== $this->_sql) {
168 1243
            $this->cancel();
169 1243
            $this->reset();
170 1243
            $this->_sql = $this->db->quoteSql($sql);
171
        }
172
173 1243
        return $this;
174
    }
175
176
    /**
177
     * Specifies the SQL statement to be executed. The SQL statement will not be modified in any way.
178
     * The previous SQL (if any) will be discarded, and [[params]] will be cleared as well. See [[reset()]]
179
     * for details.
180
     *
181
     * @param string $sql the SQL statement to be set.
182
     * @return $this this command instance
183
     * @since 2.0.13
184
     * @see reset()
185
     * @see cancel()
186
     */
187 22
    public function setRawSql($sql)
188
    {
189 22
        if ($sql !== $this->_sql) {
190 22
            $this->cancel();
191 22
            $this->reset();
192 22
            $this->_sql = $sql;
193
        }
194
195 22
        return $this;
196
    }
197
198
    /**
199
     * Returns the raw SQL by inserting parameter values into the corresponding placeholders in [[sql]].
200
     * Note that the return value of this method should mainly be used for logging purpose.
201
     * It is likely that this method returns an invalid SQL due to improper replacement of parameter placeholders.
202
     * @return string the raw SQL with parameter values inserted into the corresponding placeholders in [[sql]].
203
     */
204 1225
    public function getRawSql()
205
    {
206 1225
        if (empty($this->params)) {
207 1067
            return $this->_sql;
208
        }
209 933
        $params = [];
210 933
        foreach ($this->params as $name => $value) {
211 933
            if (is_string($name) && strncmp(':', $name, 1)) {
212 15
                $name = ':' . $name;
213
            }
214 933
            if (is_string($value)) {
215 743
                $params[$name] = $this->db->quoteValue($value);
216 751
            } elseif (is_bool($value)) {
217 25
                $params[$name] = ($value ? 'TRUE' : 'FALSE');
218 744
            } elseif ($value === null) {
219 287
                $params[$name] = 'NULL';
220 701
            } elseif ((!is_object($value) && !is_resource($value)) || $value instanceof Expression) {
221 933
                $params[$name] = $value;
222
            }
223
        }
224 933
        if (!isset($params[1])) {
225 933
            return strtr($this->_sql, $params);
226
        }
227
        $sql = '';
228
        foreach (explode('?', $this->_sql) as $i => $part) {
229
            $sql .= (isset($params[$i]) ? $params[$i] : '') . $part;
230
        }
231
232
        return $sql;
233
    }
234
235
    /**
236
     * Prepares the SQL statement to be executed.
237
     * For complex SQL statement that is to be executed multiple times,
238
     * this may improve performance.
239
     * For SQL statement with binding parameters, this method is invoked
240
     * automatically.
241
     * @param bool $forRead whether this method is called for a read query. If null, it means
242
     * the SQL statement should be used to determine whether it is for read or write.
243
     * @throws Exception if there is any DB error
244
     */
245 1210
    public function prepare($forRead = null)
246
    {
247 1210
        if ($this->pdoStatement) {
248 53
            $this->bindPendingParams();
249 53
            return;
250
        }
251
252 1210
        $sql = $this->getSql();
253
254 1210
        if ($this->db->getTransaction()) {
255
            // master is in a transaction. use the same connection.
256 21
            $forRead = false;
257
        }
258 1210
        if ($forRead || $forRead === null && $this->db->getSchema()->isReadQuery($sql)) {
259 1165
            $pdo = $this->db->getSlavePdo();
260
        } else {
261 638
            $pdo = $this->db->getMasterPdo();
262
        }
263
264
        try {
265 1210
            $this->pdoStatement = $pdo->prepare($sql);
266 1209
            $this->bindPendingParams();
267 4
        } catch (\Exception $e) {
268 4
            $message = $e->getMessage() . "\nFailed to prepare SQL: $sql";
269 4
            $errorInfo = $e instanceof \PDOException ? $e->errorInfo : null;
270 4
            throw new Exception($message, $errorInfo, (int) $e->getCode(), $e);
271
        }
272 1209
    }
273
274
    /**
275
     * Cancels the execution of the SQL statement.
276
     * This method mainly sets [[pdoStatement]] to be null.
277
     */
278 1243
    public function cancel()
279
    {
280 1243
        $this->pdoStatement = null;
281 1243
    }
282
283
    /**
284
     * Binds a parameter to the SQL statement to be executed.
285
     * @param string|int $name parameter identifier. For a prepared statement
286
     * using named placeholders, this will be a parameter name of
287
     * the form `:name`. For a prepared statement using question mark
288
     * placeholders, this will be the 1-indexed position of the parameter.
289
     * @param mixed $value the PHP variable to bind to the SQL statement parameter (passed by reference)
290
     * @param int $dataType SQL data type of the parameter. If null, the type is determined by the PHP type of the value.
291
     * @param int $length length of the data type
292
     * @param mixed $driverOptions the driver-specific options
293
     * @return $this the current command being executed
294
     * @see http://www.php.net/manual/en/function.PDOStatement-bindParam.php
295
     */
296 3
    public function bindParam($name, &$value, $dataType = null, $length = null, $driverOptions = null)
297
    {
298 3
        $this->prepare();
299
300 3
        if ($dataType === null) {
301 3
            $dataType = $this->db->getSchema()->getPdoType($value);
302
        }
303 3
        if ($length === null) {
304 3
            $this->pdoStatement->bindParam($name, $value, $dataType);
305
        } elseif ($driverOptions === null) {
306
            $this->pdoStatement->bindParam($name, $value, $dataType, $length);
307
        } else {
308
            $this->pdoStatement->bindParam($name, $value, $dataType, $length, $driverOptions);
309
        }
310 3
        $this->params[$name] = &$value;
311
312 3
        return $this;
313
    }
314
315
    /**
316
     * Binds pending parameters that were registered via [[bindValue()]] and [[bindValues()]].
317
     * Note that this method requires an active [[pdoStatement]].
318
     */
319 1209
    protected function bindPendingParams()
320
    {
321 1209
        foreach ($this->_pendingParams as $name => $value) {
322 914
            $this->pdoStatement->bindValue($name, $value[0], $value[1]);
323
        }
324 1209
        $this->_pendingParams = [];
325 1209
    }
326
327
    /**
328
     * Binds a value to a parameter.
329
     * @param string|int $name Parameter identifier. For a prepared statement
330
     * using named placeholders, this will be a parameter name of
331
     * the form `:name`. For a prepared statement using question mark
332
     * placeholders, this will be the 1-indexed position of the parameter.
333
     * @param mixed $value The value to bind to the parameter
334
     * @param int $dataType SQL data type of the parameter. If null, the type is determined by the PHP type of the value.
335
     * @return $this the current command being executed
336
     * @see http://www.php.net/manual/en/function.PDOStatement-bindValue.php
337
     */
338 6
    public function bindValue($name, $value, $dataType = null)
339
    {
340 6
        if ($dataType === null) {
341 6
            $dataType = $this->db->getSchema()->getPdoType($value);
342
        }
343 6
        $this->_pendingParams[$name] = [$value, $dataType];
344 6
        $this->params[$name] = $value;
345
346 6
        return $this;
347
    }
348
349
    /**
350
     * Binds a list of values to the corresponding parameters.
351
     * This is similar to [[bindValue()]] except that it binds multiple values at a time.
352
     * Note that the SQL data type of each value is determined by its PHP type.
353
     * @param array $values the values to be bound. This must be given in terms of an associative
354
     * array with array keys being the parameter names, and array values the corresponding parameter values,
355
     * e.g. `[':name' => 'John', ':age' => 25]`. By default, the PDO type of each value is determined
356
     * by its PHP type. You may explicitly specify the PDO type by using a [[yii\db\PdoValue]] class: `new PdoValue(value, type)`,
357
     * e.g. `[':name' => 'John', ':profile' => new PdoValue($profile, \PDO::PARAM_LOB)]`.
358
     * @return $this the current command being executed
359
     */
360 1243
    public function bindValues($values)
361
    {
362 1243
        if (empty($values)) {
363 1085
            return $this;
364
        }
365
366 933
        $schema = $this->db->getSchema();
367 933
        foreach ($values as $name => $value) {
368 933
            if ($value instanceof PdoValue) {
369 89
                $this->_pendingParams[$name] = [$value->getValue(), $value->getType()];
370 89
                $this->params[$name] = $value->getValue();
371
            } else {
372 933
                $type = $schema->getPdoType($value);
373 933
                $this->_pendingParams[$name] = [$value, $type];
374 933
                $this->params[$name] = $value;
375
            }
376
        }
377
378 933
        return $this;
379
    }
380
381
    /**
382
     * Executes the SQL statement and returns query result.
383
     * This method is for executing a SQL query that returns result set, such as `SELECT`.
384
     * @return DataReader the reader object for fetching the query result
385
     * @throws Exception execution failed
386
     */
387 9
    public function query()
388
    {
389 9
        return $this->queryInternal('');
390
    }
391
392
    /**
393
     * Executes the SQL statement and returns ALL rows at once.
394
     * @param int $fetchMode the result fetch mode. Please refer to [PHP manual](http://www.php.net/manual/en/function.PDOStatement-setFetchMode.php)
395
     * for valid fetch modes. If this parameter is null, the value set in [[fetchMode]] will be used.
396
     * @return array all rows of the query result. Each array element is an array representing a row of data.
397
     * An empty array is returned if the query results in nothing.
398
     * @throws Exception execution failed
399
     */
400 1047
    public function queryAll($fetchMode = null)
401
    {
402 1047
        return $this->queryInternal('fetchAll', $fetchMode);
403
    }
404
405
    /**
406
     * Executes the SQL statement and returns the first row of the result.
407
     * This method is best used when only the first row of result is needed for a query.
408
     * @param int $fetchMode the result fetch mode. Please refer to [PHP manual](http://php.net/manual/en/pdostatement.setfetchmode.php)
409
     * for valid fetch modes. If this parameter is null, the value set in [[fetchMode]] will be used.
410
     * @return array|false the first row (in terms of an array) of the query result. False is returned if the query
411
     * results in nothing.
412
     * @throws Exception execution failed
413
     */
414 439
    public function queryOne($fetchMode = null)
415
    {
416 439
        return $this->queryInternal('fetch', $fetchMode);
417
    }
418
419
    /**
420
     * Executes the SQL statement and returns the value of the first column in the first row of data.
421
     * This method is best used when only a single value is needed for a query.
422
     * @return string|null|false the value of the first column in the first row of the query result.
423
     * False is returned if there is no value.
424
     * @throws Exception execution failed
425
     */
426 278
    public function queryScalar()
427
    {
428 278
        $result = $this->queryInternal('fetchColumn', 0);
429 275
        if (is_resource($result) && get_resource_type($result) === 'stream') {
430 17
            return stream_get_contents($result);
431
        }
432
433 270
        return $result;
434
    }
435
436
    /**
437
     * Executes the SQL statement and returns the first column of the result.
438
     * This method is best used when only the first column of result (i.e. the first element in each row)
439
     * is needed for a query.
440
     * @return array the first column of the query result. Empty array is returned if the query results in nothing.
441
     * @throws Exception execution failed
442
     */
443 77
    public function queryColumn()
444
    {
445 77
        return $this->queryInternal('fetchAll', \PDO::FETCH_COLUMN);
446
    }
447
448
    /**
449
     * Creates an INSERT command.
450
     *
451
     * For example,
452
     *
453
     * ```php
454
     * $connection->createCommand()->insert('user', [
455
     *     'name' => 'Sam',
456
     *     'age' => 30,
457
     * ])->execute();
458
     * ```
459
     *
460
     * The method will properly escape the column names, and bind the values to be inserted.
461
     *
462
     * Note that the created command is not executed until [[execute()]] is called.
463
     *
464
     * @param string $table the table that new rows will be inserted into.
465
     * @param array|\yii\db\Query $columns the column data (name => value) to be inserted into the table or instance
466
     * of [[yii\db\Query|Query]] to perform INSERT INTO ... SELECT SQL statement.
467
     * Passing of [[yii\db\Query|Query]] is available since version 2.0.11.
468
     * @return $this the command object itself
469
     */
470 440
    public function insert($table, $columns)
471
    {
472 440
        $params = [];
473 440
        $sql = $this->db->getQueryBuilder()->insert($table, $columns, $params);
474
475 431
        return $this->setSql($sql)->bindValues($params);
476
    }
477
478
    /**
479
     * Creates a batch INSERT command.
480
     *
481
     * For example,
482
     *
483
     * ```php
484
     * $connection->createCommand()->batchInsert('user', ['name', 'age'], [
485
     *     ['Tom', 30],
486
     *     ['Jane', 20],
487
     *     ['Linda', 25],
488
     * ])->execute();
489
     * ```
490
     *
491
     * The method will properly escape the column names, and quote the values to be inserted.
492
     *
493
     * Note that the values in each row must match the corresponding column names.
494
     *
495
     * Also note that the created command is not executed until [[execute()]] is called.
496
     *
497
     * @param string $table the table that new rows will be inserted into.
498
     * @param array $columns the column names
499
     * @param array|\Generator $rows the rows to be batch inserted into the table
500
     * @return $this the command object itself
501
     */
502 22
    public function batchInsert($table, $columns, $rows)
503
    {
504 22
        $table = $this->db->quoteSql($table);
505
        $columns = array_map(function ($column) {
506 22
            return $this->db->quoteSql($column);
507 22
        }, $columns);
508
509 22
        $sql = $this->db->getQueryBuilder()->batchInsert($table, $columns, $rows);
510
511 22
        $this->setRawSql($sql);
512
513 22
        return $this;
514
    }
515
516
    /**
517
     * Creates an UPDATE command.
518
     *
519
     * For example,
520
     *
521
     * ```php
522
     * $connection->createCommand()->update('user', ['status' => 1], 'age > 30')->execute();
523
     * ```
524
     *
525
     * or with using parameter binding for the condition:
526
     *
527
     * ```php
528
     * $minAge = 30;
529
     * $connection->createCommand()->update('user', ['status' => 1], 'age > :minAge', [':minAge' => $minAge])->execute();
530
     * ```
531
     *
532
     * The method will properly escape the column names and bind the values to be updated.
533
     *
534
     * Note that the created command is not executed until [[execute()]] is called.
535
     *
536
     * @param string $table the table to be updated.
537
     * @param array $columns the column data (name => value) to be updated.
538
     * @param string|array $condition the condition that will be put in the WHERE part. Please
539
     * refer to [[Query::where()]] on how to specify condition.
540
     * @param array $params the parameters to be bound to the command
541
     * @return $this the command object itself
542
     */
543 109
    public function update($table, $columns, $condition = '', $params = [])
544
    {
545 109
        $sql = $this->db->getQueryBuilder()->update($table, $columns, $condition, $params);
546
547 109
        return $this->setSql($sql)->bindValues($params);
548
    }
549
550
    /**
551
     * Creates a DELETE command.
552
     *
553
     * For example,
554
     *
555
     * ```php
556
     * $connection->createCommand()->delete('user', 'status = 0')->execute();
557
     * ```
558
     *
559
     * or with using parameter binding for the condition:
560
     *
561
     * ```php
562
     * $status = 0;
563
     * $connection->createCommand()->delete('user', 'status = :status', [':status' => $status])->execute();
564
     * ```
565
     *
566
     * The method will properly escape the table and column names.
567
     *
568
     * Note that the created command is not executed until [[execute()]] is called.
569
     *
570
     * @param string $table the table where the data will be deleted from.
571
     * @param string|array $condition the condition that will be put in the WHERE part. Please
572
     * refer to [[Query::where()]] on how to specify condition.
573
     * @param array $params the parameters to be bound to the command
574
     * @return $this the command object itself
575
     */
576 344
    public function delete($table, $condition = '', $params = [])
577
    {
578 344
        $sql = $this->db->getQueryBuilder()->delete($table, $condition, $params);
579
580 344
        return $this->setSql($sql)->bindValues($params);
581
    }
582
583
    /**
584
     * Creates a SQL command for creating a new DB table.
585
     *
586
     * The columns in the new table should be specified as name-definition pairs (e.g. 'name' => 'string'),
587
     * where name stands for a column name which will be properly quoted by the method, and definition
588
     * stands for the column type which can contain an abstract DB type.
589
     * The method [[QueryBuilder::getColumnType()]] will be called
590
     * to convert the abstract column types to physical ones. For example, `string` will be converted
591
     * as `varchar(255)`, and `string not null` becomes `varchar(255) not null`.
592
     *
593
     * If a column is specified with definition only (e.g. 'PRIMARY KEY (name, type)'), it will be directly
594
     * inserted into the generated SQL.
595
     *
596
     * @param string $table the name of the table to be created. The name will be properly quoted by the method.
597
     * @param array $columns the columns (name => definition) in the new table.
598
     * @param string $options additional SQL fragment that will be appended to the generated SQL.
599
     * @return $this the command object itself
600
     */
601 125
    public function createTable($table, $columns, $options = null)
602
    {
603 125
        $sql = $this->db->getQueryBuilder()->createTable($table, $columns, $options);
604
605 125
        return $this->setSql($sql)->requireTableSchemaRefresh($table);
606
    }
607
608
    /**
609
     * Creates a SQL command for renaming a DB table.
610
     * @param string $table the table to be renamed. The name will be properly quoted by the method.
611
     * @param string $newName the new table name. The name will be properly quoted by the method.
612
     * @return $this the command object itself
613
     */
614 3
    public function renameTable($table, $newName)
615
    {
616 3
        $sql = $this->db->getQueryBuilder()->renameTable($table, $newName);
617
618 3
        return $this->setSql($sql)->requireTableSchemaRefresh($table);
619
    }
620
621
    /**
622
     * Creates a SQL command for dropping a DB table.
623
     * @param string $table the table to be dropped. The name will be properly quoted by the method.
624
     * @return $this the command object itself
625
     */
626 33
    public function dropTable($table)
627
    {
628 33
        $sql = $this->db->getQueryBuilder()->dropTable($table);
629
630 33
        return $this->setSql($sql)->requireTableSchemaRefresh($table);
631
    }
632
633
    /**
634
     * Creates a SQL command for truncating a DB table.
635
     * @param string $table the table to be truncated. The name will be properly quoted by the method.
636
     * @return $this the command object itself
637
     */
638 13
    public function truncateTable($table)
639
    {
640 13
        $sql = $this->db->getQueryBuilder()->truncateTable($table);
641
642 13
        return $this->setSql($sql);
643
    }
644
645
    /**
646
     * Creates a SQL command for adding a new DB column.
647
     * @param string $table the table that the new column will be added to. The table name will be properly quoted by the method.
648
     * @param string $column the name of the new column. The name will be properly quoted by the method.
649
     * @param string $type the column type. [[\yii\db\QueryBuilder::getColumnType()]] will be called
650
     * to convert the give column type to the physical one. For example, `string` will be converted
651
     * as `varchar(255)`, and `string not null` becomes `varchar(255) not null`.
652
     * @return $this the command object itself
653
     */
654 4
    public function addColumn($table, $column, $type)
655
    {
656 4
        $sql = $this->db->getQueryBuilder()->addColumn($table, $column, $type);
657
658 4
        return $this->setSql($sql)->requireTableSchemaRefresh($table);
659
    }
660
661
    /**
662
     * Creates a SQL command for dropping a DB column.
663
     * @param string $table the table whose column is to be dropped. The name will be properly quoted by the method.
664
     * @param string $column the name of the column to be dropped. The name will be properly quoted by the method.
665
     * @return $this the command object itself
666
     */
667
    public function dropColumn($table, $column)
668
    {
669
        $sql = $this->db->getQueryBuilder()->dropColumn($table, $column);
670
671
        return $this->setSql($sql)->requireTableSchemaRefresh($table);
672
    }
673
674
    /**
675
     * Creates a SQL command for renaming a column.
676
     * @param string $table the table whose column is to be renamed. The name will be properly quoted by the method.
677
     * @param string $oldName the old name of the column. The name will be properly quoted by the method.
678
     * @param string $newName the new name of the column. The name will be properly quoted by the method.
679
     * @return $this the command object itself
680
     */
681
    public function renameColumn($table, $oldName, $newName)
682
    {
683
        $sql = $this->db->getQueryBuilder()->renameColumn($table, $oldName, $newName);
684
685
        return $this->setSql($sql)->requireTableSchemaRefresh($table);
686
    }
687
688
    /**
689
     * Creates a SQL command for changing the definition of a column.
690
     * @param string $table the table whose column is to be changed. The table name will be properly quoted by the method.
691
     * @param string $column the name of the column to be changed. The name will be properly quoted by the method.
692
     * @param string $type the column type. [[\yii\db\QueryBuilder::getColumnType()]] will be called
693
     * to convert the give column type to the physical one. For example, `string` will be converted
694
     * as `varchar(255)`, and `string not null` becomes `varchar(255) not null`.
695
     * @return $this the command object itself
696
     */
697 2
    public function alterColumn($table, $column, $type)
698
    {
699 2
        $sql = $this->db->getQueryBuilder()->alterColumn($table, $column, $type);
700
701 2
        return $this->setSql($sql)->requireTableSchemaRefresh($table);
702
    }
703
704
    /**
705
     * Creates a SQL command for adding a primary key constraint to an existing table.
706
     * The method will properly quote the table and column names.
707
     * @param string $name the name of the primary key constraint.
708
     * @param string $table the table that the primary key constraint will be added to.
709
     * @param string|array $columns comma separated string or array of columns that the primary key will consist of.
710
     * @return $this the command object itself.
711
     */
712 2
    public function addPrimaryKey($name, $table, $columns)
713
    {
714 2
        $sql = $this->db->getQueryBuilder()->addPrimaryKey($name, $table, $columns);
715
716 2
        return $this->setSql($sql)->requireTableSchemaRefresh($table);
717
    }
718
719
    /**
720
     * Creates a SQL command for removing a primary key constraint to an existing table.
721
     * @param string $name the name of the primary key constraint to be removed.
722
     * @param string $table the table that the primary key constraint will be removed from.
723
     * @return $this the command object itself
724
     */
725 2
    public function dropPrimaryKey($name, $table)
726
    {
727 2
        $sql = $this->db->getQueryBuilder()->dropPrimaryKey($name, $table);
728
729 2
        return $this->setSql($sql)->requireTableSchemaRefresh($table);
730
    }
731
732
    /**
733
     * Creates a SQL command for adding a foreign key constraint to an existing table.
734
     * The method will properly quote the table and column names.
735
     * @param string $name the name of the foreign key constraint.
736
     * @param string $table the table that the foreign key constraint will be added to.
737
     * @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.
738
     * @param string $refTable the table that the foreign key references to.
739
     * @param string|array $refColumns the name of the column that the foreign key references to. If there are multiple columns, separate them with commas.
740
     * @param string $delete the ON DELETE option. Most DBMS support these options: RESTRICT, CASCADE, NO ACTION, SET DEFAULT, SET NULL
741
     * @param string $update the ON UPDATE option. Most DBMS support these options: RESTRICT, CASCADE, NO ACTION, SET DEFAULT, SET NULL
742
     * @return $this the command object itself
743
     */
744 4
    public function addForeignKey($name, $table, $columns, $refTable, $refColumns, $delete = null, $update = null)
745
    {
746 4
        $sql = $this->db->getQueryBuilder()->addForeignKey($name, $table, $columns, $refTable, $refColumns, $delete, $update);
747
748 4
        return $this->setSql($sql)->requireTableSchemaRefresh($table);
749
    }
750
751
    /**
752
     * Creates a SQL command for dropping a foreign key constraint.
753
     * @param string $name the name of the foreign key constraint to be dropped. The name will be properly quoted by the method.
754
     * @param string $table the table whose foreign is to be dropped. The name will be properly quoted by the method.
755
     * @return $this the command object itself
756
     */
757 4
    public function dropForeignKey($name, $table)
758
    {
759 4
        $sql = $this->db->getQueryBuilder()->dropForeignKey($name, $table);
760
761 4
        return $this->setSql($sql)->requireTableSchemaRefresh($table);
762
    }
763
764
    /**
765
     * Creates a SQL command for creating a new index.
766
     * @param string $name the name of the index. The name will be properly quoted by the method.
767
     * @param string $table the table that the new index will be created for. The table name will be properly quoted by the method.
768
     * @param string|array $columns the column(s) that should be included in the index. If there are multiple columns, please separate them
769
     * by commas. The column names will be properly quoted by the method.
770
     * @param bool $unique whether to add UNIQUE constraint on the created index.
771
     * @return $this the command object itself
772
     */
773 12
    public function createIndex($name, $table, $columns, $unique = false)
774
    {
775 12
        $sql = $this->db->getQueryBuilder()->createIndex($name, $table, $columns, $unique);
776
777 12
        return $this->setSql($sql)->requireTableSchemaRefresh($table);
778
    }
779
780
    /**
781
     * Creates a SQL command for dropping an index.
782
     * @param string $name the name of the index to be dropped. The name will be properly quoted by the method.
783
     * @param string $table the table whose index is to be dropped. The name will be properly quoted by the method.
784
     * @return $this the command object itself
785
     */
786 3
    public function dropIndex($name, $table)
787
    {
788 3
        $sql = $this->db->getQueryBuilder()->dropIndex($name, $table);
789
790 3
        return $this->setSql($sql)->requireTableSchemaRefresh($table);
791
    }
792
793
    /**
794
     * Creates a SQL command for adding an unique constraint to an existing table.
795
     * @param string $name the name of the unique constraint.
796
     * The name will be properly quoted by the method.
797
     * @param string $table the table that the unique constraint will be added to.
798
     * The name will be properly quoted by the method.
799
     * @param string|array $columns the name of the column to that the constraint will be added on.
800
     * If there are multiple columns, separate them with commas.
801
     * The name will be properly quoted by the method.
802
     * @return $this the command object itself.
803
     * @since 2.0.13
804
     */
805 2
    public function addUnique($name, $table, $columns)
806
    {
807 2
        $sql = $this->db->getQueryBuilder()->addUnique($name, $table, $columns);
808
809 2
        return $this->setSql($sql)->requireTableSchemaRefresh($table);
810
    }
811
812
    /**
813
     * Creates a SQL command for dropping an unique constraint.
814
     * @param string $name the name of the unique constraint to be dropped.
815
     * The name will be properly quoted by the method.
816
     * @param string $table the table whose unique constraint is to be dropped.
817
     * The name will be properly quoted by the method.
818
     * @return $this the command object itself.
819
     * @since 2.0.13
820
     */
821 2
    public function dropUnique($name, $table)
822
    {
823 2
        $sql = $this->db->getQueryBuilder()->dropUnique($name, $table);
824
825 2
        return $this->setSql($sql)->requireTableSchemaRefresh($table);
826
    }
827
828
    /**
829
     * Creates a SQL command for adding a check constraint to an existing table.
830
     * @param string $name the name of the check constraint.
831
     * The name will be properly quoted by the method.
832
     * @param string $table the table that the check constraint will be added to.
833
     * The name will be properly quoted by the method.
834
     * @param string $expression the SQL of the `CHECK` constraint.
835
     * @return $this the command object itself.
836
     * @since 2.0.13
837
     */
838 1
    public function addCheck($name, $table, $expression)
839
    {
840 1
        $sql = $this->db->getQueryBuilder()->addCheck($name, $table, $expression);
841
842 1
        return $this->setSql($sql)->requireTableSchemaRefresh($table);
843
    }
844
845
    /**
846
     * Creates a SQL command for dropping a check constraint.
847
     * @param string $name the name of the check constraint to be dropped.
848
     * The name will be properly quoted by the method.
849
     * @param string $table the table whose check constraint is to be dropped.
850
     * The name will be properly quoted by the method.
851
     * @return $this the command object itself.
852
     * @since 2.0.13
853
     */
854 1
    public function dropCheck($name, $table)
855
    {
856 1
        $sql = $this->db->getQueryBuilder()->dropCheck($name, $table);
857
858 1
        return $this->setSql($sql)->requireTableSchemaRefresh($table);
859
    }
860
861
    /**
862
     * Creates a SQL command for adding a default value constraint to an existing table.
863
     * @param string $name the name of the default value constraint.
864
     * The name will be properly quoted by the method.
865
     * @param string $table the table that the default value constraint will be added to.
866
     * The name will be properly quoted by the method.
867
     * @param string $column the name of the column to that the constraint will be added on.
868
     * The name will be properly quoted by the method.
869
     * @param mixed $value default value.
870
     * @return $this the command object itself.
871
     * @since 2.0.13
872
     */
873
    public function addDefaultValue($name, $table, $column, $value)
874
    {
875
        $sql = $this->db->getQueryBuilder()->addDefaultValue($name, $table, $column, $value);
876
877
        return $this->setSql($sql)->requireTableSchemaRefresh($table);
878
    }
879
880
    /**
881
     * Creates a SQL command for dropping a default value constraint.
882
     * @param string $name the name of the default value constraint to be dropped.
883
     * The name will be properly quoted by the method.
884
     * @param string $table the table whose default value constraint is to be dropped.
885
     * The name will be properly quoted by the method.
886
     * @return $this the command object itself.
887
     * @since 2.0.13
888
     */
889
    public function dropDefaultValue($name, $table)
890
    {
891
        $sql = $this->db->getQueryBuilder()->dropDefaultValue($name, $table);
892
893
        return $this->setSql($sql)->requireTableSchemaRefresh($table);
894
    }
895
896
    /**
897
     * Creates a SQL command for resetting the sequence value of a table's primary key.
898
     * The sequence will be reset such that the primary key of the next new row inserted
899
     * will have the specified value or 1.
900
     * @param string $table the name of the table whose primary key sequence will be reset
901
     * @param mixed $value the value for the primary key of the next new row inserted. If this is not set,
902
     * the next new row's primary key will have a value 1.
903
     * @return $this the command object itself
904
     * @throws NotSupportedException if this is not supported by the underlying DBMS
905
     */
906 16
    public function resetSequence($table, $value = null)
907
    {
908 16
        $sql = $this->db->getQueryBuilder()->resetSequence($table, $value);
909
910 16
        return $this->setSql($sql);
911
    }
912
913
    /**
914
     * Builds a SQL command for enabling or disabling integrity check.
915
     * @param bool $check whether to turn on or off the integrity check.
916
     * @param string $schema the schema name of the tables. Defaults to empty string, meaning the current
917
     * or default schema.
918
     * @param string $table the table name.
919
     * @return $this the command object itself
920
     * @throws NotSupportedException if this is not supported by the underlying DBMS
921
     */
922 4
    public function checkIntegrity($check = true, $schema = '', $table = '')
923
    {
924 4
        $sql = $this->db->getQueryBuilder()->checkIntegrity($check, $schema, $table);
925
926 4
        return $this->setSql($sql);
927
    }
928
929
    /**
930
     * Builds a SQL command for adding comment to column.
931
     *
932
     * @param string $table the table whose column is to be commented. The table name will be properly quoted by the method.
933
     * @param string $column the name of the column to be commented. The column name will be properly quoted by the method.
934
     * @param string $comment the text of the comment to be added. The comment will be properly quoted by the method.
935
     * @return $this the command object itself
936
     * @since 2.0.8
937
     */
938 2
    public function addCommentOnColumn($table, $column, $comment)
939
    {
940 2
        $sql = $this->db->getQueryBuilder()->addCommentOnColumn($table, $column, $comment);
941
942 2
        return $this->setSql($sql)->requireTableSchemaRefresh($table);
943
    }
944
945
    /**
946
     * Builds a SQL command for adding comment to table.
947
     *
948
     * @param string $table the table whose column is to be commented. The table name will be properly quoted by the method.
949
     * @param string $comment the text of the comment to be added. The comment will be properly quoted by the method.
950
     * @return $this the command object itself
951
     * @since 2.0.8
952
     */
953
    public function addCommentOnTable($table, $comment)
954
    {
955
        $sql = $this->db->getQueryBuilder()->addCommentOnTable($table, $comment);
956
957
        return $this->setSql($sql);
958
    }
959
960
    /**
961
     * Builds a SQL command for dropping comment from column.
962
     *
963
     * @param string $table the table whose column is to be commented. The table name will be properly quoted by the method.
964
     * @param string $column the name of the column to be commented. The column name will be properly quoted by the method.
965
     * @return $this the command object itself
966
     * @since 2.0.8
967
     */
968 2
    public function dropCommentFromColumn($table, $column)
969
    {
970 2
        $sql = $this->db->getQueryBuilder()->dropCommentFromColumn($table, $column);
971
972 2
        return $this->setSql($sql)->requireTableSchemaRefresh($table);
973
    }
974
975
    /**
976
     * Builds a SQL command for dropping comment from table.
977
     *
978
     * @param string $table the table whose column is to be commented. The table name will be properly quoted by the method.
979
     * @return $this the command object itself
980
     * @since 2.0.8
981
     */
982
    public function dropCommentFromTable($table)
983
    {
984
        $sql = $this->db->getQueryBuilder()->dropCommentFromTable($table);
985
986
        return $this->setSql($sql);
987
    }
988
989
    /**
990
     * Creates a SQL View.
991
     *
992
     * @param string $viewName the name of the view to be created.
993
     * @param string|Query $subquery the select statement which defines the view.
994
     * This can be either a string or a [[Query]] object.
995
     * @return $this the command object itself.
996
     * @since 2.0.14
997
     */
998 3
    public function createView($viewName, $subquery)
999
    {
1000 3
        $sql = $this->db->getQueryBuilder()->createView($viewName, $subquery);
1001
1002 3
        return $this->setSql($sql)->requireTableSchemaRefresh($viewName);
1003
    }
1004
    
1005
    /**
1006
     * Drops a SQL View.
1007
     *
1008
     * @param string $viewName the name of the view to be dropped.
1009
     * @return $this the command object itself.
1010
     * @since 2.0.14
1011
     */
1012 3
    public function dropView($viewName)
1013
    {
1014 3
        $sql = $this->db->getQueryBuilder()->dropView($viewName);
1015
1016 3
        return $this->setSql($sql)->requireTableSchemaRefresh($viewName);
1017
    }
1018
1019
    /**
1020
     * Executes the SQL statement.
1021
     * This method should only be used for executing non-query SQL statement, such as `INSERT`, `DELETE`, `UPDATE` SQLs.
1022
     * No result set will be returned.
1023
     * @return int number of rows affected by the execution.
1024
     * @throws Exception execution failed
1025
     */
1026 624
    public function execute()
1027
    {
1028 624
        $sql = $this->getSql();
1029 624
        list($profile, $rawSql) = $this->logQuery(__METHOD__);
1030
1031 624
        if ($sql == '') {
1032 6
            return 0;
1033
        }
1034
1035 621
        $this->prepare(false);
1036
1037
        try {
1038 621
            $profile and Yii::beginProfile($rawSql, __METHOD__);
1039
1040 621
            $this->internalExecute($rawSql);
1041 618
            $n = $this->pdoStatement->rowCount();
1042
1043 618
            $profile and Yii::endProfile($rawSql, __METHOD__);
1044
1045 618
            $this->trigger(self::EVENT_AFTER_EXECUTE, new AfterExecuteEvent([
1046 618
                'command' => $this,
1047
            ]));
1048
1049 618
            $this->refreshTableSchema();
1050
1051 618
            return $n;
1052 18
        } catch (Exception $e) {
1053 18
            $profile and Yii::endProfile($rawSql, __METHOD__);
1054 18
            throw $e;
1055
        }
1056
    }
1057
1058
    /**
1059
     * Logs the current database query if query logging is enabled and returns
1060
     * the profiling token if profiling is enabled.
1061
     * @param string $category the log category.
1062
     * @return array array of two elements, the first is boolean of whether profiling is enabled or not.
1063
     * The second is the rawSql if it has been created.
1064
     */
1065 1207
    private function logQuery($category)
1066
    {
1067 1207
        if ($this->db->enableLogging) {
1068 1207
            $rawSql = $this->getRawSql();
1069 1207
            Yii::info($rawSql, $category);
1070
        }
1071 1207
        if (!$this->db->enableProfiling) {
1072 7
            return [false, isset($rawSql) ? $rawSql : null];
1073
        }
1074
1075 1207
        return [true, isset($rawSql) ? $rawSql : $this->getRawSql()];
1076
    }
1077
1078
    /**
1079
     * Performs the actual DB query of a SQL statement.
1080
     * @param string $method method of PDOStatement to be called
1081
     * @param int $fetchMode the result fetch mode. Please refer to [PHP manual](http://www.php.net/manual/en/function.PDOStatement-setFetchMode.php)
1082
     * for valid fetch modes. If this parameter is null, the value set in [[fetchMode]] will be used.
1083
     * @return mixed the method execution result
1084
     * @throws Exception if the query causes any problem
1085
     * @since 2.0.1 this method is protected (was private before).
1086
     */
1087 1166
    protected function queryInternal($method, $fetchMode = null)
1088
    {
1089 1166
        list($profile, $rawSql) = $this->logQuery('yii\db\Command::query');
1090
1091 1166
        if ($method !== '') {
1092 1163
            $info = $this->db->getQueryCacheInfo($this->queryCacheDuration, $this->queryCacheDependency);
1093 1163
            if (is_array($info)) {
1094
                /* @var $cache \yii\caching\CacheInterface */
1095 3
                $cache = $info[0];
1096
                $cacheKey = [
1097 3
                    __CLASS__,
1098 3
                    $method,
1099 3
                    $fetchMode,
1100 3
                    $this->db->dsn,
1101 3
                    $this->db->username,
1102 3
                    $rawSql ?: $rawSql = $this->getRawSql(),
1103
                ];
1104 3
                $result = $cache->get($cacheKey);
1105 3
                if (is_array($result) && isset($result[0])) {
1106 3
                    Yii::trace('Query result served from cache', 'yii\db\Command::query');
1107 3
                    return $result[0];
1108
                }
1109
            }
1110
        }
1111
1112 1166
        $this->prepare(true);
1113
1114
        try {
1115 1165
            $profile and Yii::beginProfile($rawSql, 'yii\db\Command::query');
1116
1117 1165
            $this->internalExecute($rawSql);
1118
1119 1162
            if ($method === '') {
1120 9
                $result = new DataReader($this);
1121
            } else {
1122 1159
                if ($fetchMode === null) {
1123 1066
                    $fetchMode = $this->fetchMode;
1124
                }
1125 1159
                $result = call_user_func_array([$this->pdoStatement, $method], (array) $fetchMode);
1126 1159
                $this->pdoStatement->closeCursor();
1127
            }
1128
1129 1162
            $profile and Yii::endProfile($rawSql, 'yii\db\Command::query');
1130 22
        } catch (Exception $e) {
1131 22
            $profile and Yii::endProfile($rawSql, 'yii\db\Command::query');
1132 22
            throw $e;
1133
        }
1134
1135 1162
        if (isset($cache, $cacheKey, $info)) {
1136 3
            $cache->set($cacheKey, [$result], $info[1], $info[2]);
1137 3
            Yii::trace('Saved query result in cache', 'yii\db\Command::query');
1138
        }
1139
1140 1162
        return $result;
1141
    }
1142
1143
    /**
1144
     * Marks a specified table schema to be refreshed after command execution.
1145
     * @param string $name name of the table, which schema should be refreshed.
1146
     * @return $this this command instance
1147
     * @since 2.0.6
1148
     */
1149 134
    protected function requireTableSchemaRefresh($name)
1150
    {
1151 134
        $this->_refreshTableName = $name;
1152 134
        return $this;
1153
    }
1154
1155
    /**
1156
     * Refreshes table schema, which was marked by [[requireTableSchemaRefresh()]].
1157
     * @since 2.0.6
1158
     */
1159 618
    protected function refreshTableSchema()
1160
    {
1161 618
        if ($this->_refreshTableName !== null) {
1162 134
            $this->db->getSchema()->refreshTableSchema($this->_refreshTableName);
1163
        }
1164 618
    }
1165
1166
    /**
1167
     * Marks the command to be executed in transaction.
1168
     * @param string|null $isolationLevel The isolation level to use for this transaction.
1169
     * See [[Transaction::begin()]] for details.
1170
     * @return $this this command instance.
1171
     * @since 2.0.14
1172
     */
1173 3
    protected function requireTransaction($isolationLevel = null)
1174
    {
1175 3
        $this->_isolationLevel = $isolationLevel;
1176 3
        return $this;
1177
    }
1178
1179
    /**
1180
     * Sets a callable (e.g. anonymous function) that is called when [[Exception]] is thrown
1181
     * when executing the command. The signature of the callable should be:
1182
     *
1183
     * ```php
1184
     * function (\yii\db\Exception $e, $attempt)
1185
     * {
1186
     *     // return true or false (whether to retry the command or rethrow $e)
1187
     * }
1188
     * ```
1189
     *
1190
     * The callable will recieve a database exception thrown and a current attempt
1191
     * (to execute the command) number starting from 1.
1192
     *
1193
     * @param callable $handler a PHP callback to handle database exceptions.
1194
     * @return $this this command instance.
1195
     * @since 2.0.14
1196
     */
1197 3
    protected function setRetryHandler(callable $handler)
1198
    {
1199 3
        $this->_retryHandler = $handler;
1200 3
        return $this;
1201
    }
1202
1203
    /**
1204
     * Executes a prepared statement.
1205
     *
1206
     * It's a wrapper around [[\PDOStatement::execute()]] to support transactions
1207
     * and retry handlers.
1208
     *
1209
     * @param string|null $rawSql the rawSql if it has been created.
1210
     * @throws Exception if execution failed.
1211
     * @since 2.0.14
1212
     */
1213 1206
    protected function internalExecute($rawSql)
1214
    {
1215 1206
        $attempt = 0;
1216 1206
        while (true) {
1217
            try {
1218
                if (
1219 1206
                    ++$attempt === 1
1220 1206
                    && $this->_isolationLevel !== false
1221 1206
                    && $this->db->getTransaction() === null
1222
                ) {
1223 3
                    $this->db->transaction(function () use ($rawSql) {
1224 3
                        $this->internalExecute($rawSql);
1225 3
                    }, $this->_isolationLevel);
1226
                } else {
1227 1206
                    $this->pdoStatement->execute();
1228
                }
1229 1203
                break;
1230 37
            } catch (\Exception $e) {
1231 37
                $rawSql = $rawSql ?: $this->getRawSql();
1232 37
                $e = $this->db->getSchema()->convertException($e, $rawSql);
1233 37
                if ($this->_retryHandler === null || !call_user_func($this->_retryHandler, $e, $attempt)) {
1234 37
                    throw $e;
1235
                }
1236
            }
1237
        }
1238 1203
    }
1239
1240
    /**
1241
     * Resets command properties to their initial state.
1242
     *
1243
     * @since 2.0.13
1244
     */
1245 1243
    protected function reset()
1246
    {
1247 1243
        $this->_sql = null;
1248 1243
        $this->_pendingParams = [];
1249 1243
        $this->params = [];
1250 1243
        $this->_refreshTableName = null;
1251 1243
        $this->_isolationLevel = false;
1252 1243
        $this->_retryHandler = null;
1253 1243
    }
1254
}
1255