Passed
Push — fix-php8 ( 665a65...6c59e2 )
by Alexander
09:42 queued 15s
created

Command   F

Complexity

Total Complexity 127

Size/Duplication

Total Lines 1268
Duplicated Lines 0 %

Test Coverage

Coverage 91.3%

Importance

Changes 3
Bugs 0 Features 0
Metric Value
eloc 280
c 3
b 0
f 0
dl 0
loc 1268
ccs 294
cts 322
cp 0.913
rs 2
wmc 127

61 Methods

Rating   Name   Duplication   Size   Complexity  
A noCache() 0 4 1
A cache() 0 5 2
C getRawSql() 0 29 15
A setSql() 0 9 2
A setRawSql() 0 9 2
A getSql() 0 3 1
A addForeignKey() 0 5 1
A upsert() 0 5 1
A bindPendingParams() 0 6 2
A renameTable() 0 5 1
A queryAll() 0 3 1
A dropCommentFromColumn() 0 5 1
A checkIntegrity() 0 5 1
A dropForeignKey() 0 5 1
A addDefaultValue() 0 5 1
A executeResetSequence() 0 3 1
A getCacheKey() 0 12 1
A cancel() 0 3 1
A requireTransaction() 0 4 1
A batchInsert() 0 14 1
A bindParam() 0 17 4
B prepare() 0 32 10
A query() 0 3 1
A addCheck() 0 5 1
A dropDefaultValue() 0 5 1
A bindValues() 0 22 5
A alterColumn() 0 5 1
A dropView() 0 5 1
A addPrimaryKey() 0 5 1
A update() 0 5 1
A queryColumn() 0 3 1
A dropColumn() 0 5 1
A queryOne() 0 3 1
A execute() 0 25 6
A dropCheck() 0 5 1
A setRetryHandler() 0 4 1
A createView() 0 5 1
A dropUnique() 0 5 1
A dropTable() 0 5 1
A delete() 0 5 1
C queryInternal() 0 47 12
A addUnique() 0 5 1
A logQuery() 0 11 5
A renameColumn() 0 5 1
A createIndex() 0 5 1
A dropPrimaryKey() 0 5 1
A requireTableSchemaRefresh() 0 4 1
A dropCommentFromTable() 0 5 1
A addColumn() 0 5 1
A queryScalar() 0 8 3
A addCommentOnTable() 0 5 1
A reset() 0 8 1
A createTable() 0 5 1
A resetSequence() 0 5 1
A addCommentOnColumn() 0 5 1
A refreshTableSchema() 0 4 2
A truncateTable() 0 5 1
B internalExecute() 0 22 9
A insert() 0 6 1
A bindValue() 0 9 2
A dropIndex() 0 5 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.

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
     * @var Connection the DB connection that this command is associated with
61
     */
62
    public $db;
63
    /**
64
     * @var \PDOStatement the PDOStatement object that this command is associated with
65
     */
66
    public $pdoStatement;
67
    /**
68
     * @var int the default fetch mode for this command.
69
     * @see https://secure.php.net/manual/en/pdostatement.setfetchmode.php
70
     */
71
    public $fetchMode = \PDO::FETCH_ASSOC;
72
    /**
73
     * @var array the parameters (name => value) that are bound to the current PDO statement.
74
     * This property is maintained by methods such as [[bindValue()]]. It is mainly provided for logging purpose
75
     * and is used to generate [[rawSql]]. Do not modify it directly.
76
     */
77
    public $params = [];
78
    /**
79
     * @var int the default number of seconds that query results can remain valid in cache.
80
     * Use 0 to indicate that the cached data will never expire. And use a negative number to indicate
81
     * query cache should not be used.
82
     * @see cache()
83
     */
84
    public $queryCacheDuration;
85
    /**
86
     * @var \yii\caching\Dependency the dependency to be associated with the cached query result for this command
87
     * @see cache()
88
     */
89
    public $queryCacheDependency;
90
91
    /**
92
     * @var array pending parameters to be bound to the current PDO statement.
93
     * @since 2.0.33
94
     */
95
    protected $pendingParams = [];
96
97
    /**
98
     * @var string the SQL statement that this command represents
99
     */
100
    private $_sql;
101
    /**
102
     * @var string name of the table, which schema, should be refreshed after command execution.
103
     */
104
    private $_refreshTableName;
105
    /**
106
     * @var string|false|null the isolation level to use for this transaction.
107
     * See [[Transaction::begin()]] for details.
108
     */
109
    private $_isolationLevel = false;
110
    /**
111
     * @var callable a callable (e.g. anonymous function) that is called when [[\yii\db\Exception]] is thrown
112
     * when executing the command.
113
     */
114
    private $_retryHandler;
115
116
117
    /**
118
     * Enables query cache for this command.
119
     * @param int $duration the number of seconds that query result of this command can remain valid in the cache.
120
     * If this is not set, the value of [[Connection::queryCacheDuration]] will be used instead.
121
     * Use 0 to indicate that the cached data will never expire.
122
     * @param \yii\caching\Dependency $dependency the cache dependency associated with the cached query result.
123
     * @return $this the command object itself
124
     */
125 6
    public function cache($duration = null, $dependency = null)
126
    {
127 6
        $this->queryCacheDuration = $duration === null ? $this->db->queryCacheDuration : $duration;
128 6
        $this->queryCacheDependency = $dependency;
129 6
        return $this;
130
    }
131
132
    /**
133
     * Disables query cache for this command.
134
     * @return $this the command object itself
135
     */
136 3
    public function noCache()
137
    {
138 3
        $this->queryCacheDuration = -1;
139 3
        return $this;
140
    }
141
142
    /**
143
     * Returns the SQL statement for this command.
144
     * @return string the SQL statement to be executed
145
     */
146 1576
    public function getSql()
147
    {
148 1576
        return $this->_sql;
149
    }
150
151
    /**
152
     * Specifies the SQL statement to be executed. The SQL statement will be quoted using [[Connection::quoteSql()]].
153
     * The previous SQL (if any) will be discarded, and [[params]] will be cleared as well. See [[reset()]]
154
     * for details.
155
     *
156
     * @param string $sql the SQL statement to be set.
157
     * @return $this this command instance
158
     * @see reset()
159
     * @see cancel()
160
     */
161 1603
    public function setSql($sql)
162
    {
163 1603
        if ($sql !== $this->_sql) {
164 1603
            $this->cancel();
165 1603
            $this->reset();
166 1603
            $this->_sql = $this->db->quoteSql($sql);
167
        }
168
169 1603
        return $this;
170
    }
171
172
    /**
173
     * Specifies the SQL statement to be executed. The SQL statement will not be modified in any way.
174
     * The previous SQL (if any) will be discarded, and [[params]] will be cleared as well. See [[reset()]]
175
     * for details.
176
     *
177
     * @param string $sql the SQL statement to be set.
178
     * @return $this this command instance
179
     * @since 2.0.13
180
     * @see reset()
181
     * @see cancel()
182
     */
183 31
    public function setRawSql($sql)
184
    {
185 31
        if ($sql !== $this->_sql) {
186 31
            $this->cancel();
187 31
            $this->reset();
188 31
            $this->_sql = $sql;
189
        }
190
191 31
        return $this;
192
    }
193
194
    /**
195
     * Returns the raw SQL by inserting parameter values into the corresponding placeholders in [[sql]].
196
     * Note that the return value of this method should mainly be used for logging purpose.
197
     * It is likely that this method returns an invalid SQL due to improper replacement of parameter placeholders.
198
     * @return string the raw SQL with parameter values inserted into the corresponding placeholders in [[sql]].
199
     */
200 1582
    public function getRawSql()
201
    {
202 1582
        if (empty($this->params)) {
203 1396
            return $this->_sql;
204
        }
205 1134
        $params = [];
206 1134
        foreach ($this->params as $name => $value) {
207 1134
            if (is_string($name) && strncmp(':', $name, 1)) {
208 15
                $name = ':' . $name;
209
            }
210 1134
            if (is_string($value) || $value instanceof Expression) {
211 890
                $params[$name] = $this->db->quoteValue((string)$value);
212 887
            } elseif (is_bool($value)) {
213 25
                $params[$name] = ($value ? 'TRUE' : 'FALSE');
214 880
            } elseif ($value === null) {
215 329
                $params[$name] = 'NULL';
216 823
            } elseif (!is_object($value) && !is_resource($value)) {
217 1134
                $params[$name] = $value;
218
            }
219
        }
220 1134
        if (!isset($params[1])) {
221 1134
            return strtr($this->_sql, $params);
222
        }
223
        $sql = '';
224
        foreach (explode('?', $this->_sql) as $i => $part) {
225
            $sql .= (isset($params[$i]) ? $params[$i] : '') . $part;
226
        }
227
228
        return $sql;
229
    }
230
231
    /**
232
     * Prepares the SQL statement to be executed.
233
     * For complex SQL statement that is to be executed multiple times,
234
     * this may improve performance.
235
     * For SQL statement with binding parameters, this method is invoked
236
     * automatically.
237
     * @param bool $forRead whether this method is called for a read query. If null, it means
238
     * the SQL statement should be used to determine whether it is for read or write.
239
     * @throws Exception if there is any DB error
240
     */
241 1564
    public function prepare($forRead = null)
242
    {
243 1564
        if ($this->pdoStatement) {
244 60
            $this->bindPendingParams();
245 60
            return;
246
        }
247
248 1564
        $sql = $this->getSql();
249 1564
        if ($sql === '') {
250 3
            return;
251
        }
252
253 1564
        if ($this->db->getTransaction()) {
254
            // master is in a transaction. use the same connection.
255 21
            $forRead = false;
256
        }
257 1564
        if ($forRead || $forRead === null && $this->db->getSchema()->isReadQuery($sql)) {
258 1514
            $pdo = $this->db->getSlavePdo();
259
        } else {
260 717
            $pdo = $this->db->getMasterPdo();
261
        }
262
263
        try {
264 1564
            $this->pdoStatement = $pdo->prepare($sql);
0 ignored issues
show
Documentation Bug introduced by
It seems like $pdo->prepare($sql) can also be of type boolean. However, the property $pdoStatement is declared as type PDOStatement. Maybe add an additional type check?

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

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

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

class Id
{
    public $id;

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

}

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

$account_id = false;

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

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

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

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