Completed
Push — remove-intl-polyfills ( 129df4...a6e727 )
by Alexander
16:22 queued 12:49
created

Command::logQuery()   A

Complexity

Conditions 3
Paths 4

Size

Total Lines 12
Code Lines 7

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 7
CRAP Score 3

Importance

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

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

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

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

Loading history...
1065
1066 679
        if ($sql == '') {
1067 6
            return 0;
1068
        }
1069
1070 676
        $this->prepare(false);
1071
1072
        try {
1073 676
            $profile and Yii::beginProfile($rawSql, __METHOD__);
1074
1075 676
            $this->internalExecute($rawSql);
1076 673
            $n = $this->pdoStatement->rowCount();
1077
1078 673
            $profile and Yii::endProfile($rawSql, __METHOD__);
1079
1080 673
            $this->refreshTableSchema();
1081
1082 673
            return $n;
1083 13
        } catch (Exception $e) {
1084 13
            $profile and Yii::endProfile($rawSql, __METHOD__);
1085 13
            throw $e;
1086
        }
1087
    }
1088
1089
    /**
1090
     * Logs the current database query if query logging is enabled and returns
1091
     * the profiling token if profiling is enabled.
1092
     * @param string $category the log category.
1093
     * @return array array of two elements, the first is boolean of whether profiling is enabled or not.
1094
     * The second is the rawSql if it has been created.
1095
     */
1096 1359
    private function logQuery($category)
1097
    {
1098 1359
        if ($this->db->enableLogging) {
1099 1359
            $rawSql = $this->getRawSql();
1100 1359
            Yii::info($rawSql, $category);
1101
        }
1102 1359
        if (!$this->db->enableProfiling) {
1103 7
            return [false, $rawSql ?? null];
1104
        }
1105
1106 1359
        return [true, $rawSql ?? $this->getRawSql()];
1107
    }
1108
1109
    /**
1110
     * Performs the actual DB query of a SQL statement.
1111
     * @param string $method method of PDOStatement to be called
1112
     * @param int $fetchMode the result fetch mode. Please refer to [PHP manual](http://www.php.net/manual/en/function.PDOStatement-setFetchMode.php)
1113
     * for valid fetch modes. If this parameter is null, the value set in [[fetchMode]] will be used.
1114
     * @return mixed the method execution result
1115
     * @throws Exception if the query causes any problem
1116
     * @since 2.0.1 this method is protected (was private before).
1117
     */
1118 1313
    protected function queryInternal($method, $fetchMode = null)
1119
    {
1120 1313
        [$profile, $rawSql] = $this->logQuery('yii\db\Command::query');
0 ignored issues
show
Bug introduced by
The variable $profile does not exist. Did you forget to declare it?

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

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

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

Let’s take a look at a simple example:

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

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

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

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

Loading history...
1121
1122 1313
        if ($method !== '') {
1123 1310
            $info = $this->db->getQueryCacheInfo($this->queryCacheDuration, $this->queryCacheDependency);
1124 1310
            if (is_array($info)) {
1125
                /* @var $cache \yii\caching\CacheInterface */
1126 6
                $cache = $info[0];
1127
                $cacheKey = [
1128 6
                    __CLASS__,
1129 6
                    $method,
1130 6
                    $fetchMode,
1131 6
                    $this->db->dsn,
1132 6
                    $this->db->username,
1133 6
                    $rawSql ?: $rawSql = $this->getRawSql(),
0 ignored issues
show
Bug introduced by
The variable $rawSql seems only to be defined at a later point. Did you maybe move this code here without moving the variable definition?

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

Let’s take a look at a simple example:

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

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

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

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

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

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

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

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

function acceptsInteger($int) { }

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

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
1136 6
                if (is_array($result) && isset($result[0])) {
1137 6
                    Yii::debug('Query result served from cache', 'yii\db\Command::query');
1138 6
                    return $result[0];
1139
                }
1140
            }
1141
        }
1142
1143 1313
        $this->prepare(true);
1144
1145
        try {
1146 1312
            $profile and Yii::beginProfile($rawSql, 'yii\db\Command::query');
0 ignored issues
show
Bug introduced by
The variable $rawSql does not seem to be defined for all execution paths leading up to this point.

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

Let’s take a look at an example:

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

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

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

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

Available Fixes

  1. Check for existence of the variable explicitly:

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

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

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
    
            // We add support for the missing case.
            default:
                $x = '';
                break;
        }
    
        echo $x;
    }
    
Loading history...
1147
1148 1312
            $this->internalExecute($rawSql);
1149
1150 1309
            if ($method === '') {
1151 9
                $result = new DataReader($this);
1152
            } else {
1153 1306
                if ($fetchMode === null) {
1154 1203
                    $fetchMode = $this->fetchMode;
1155
                }
1156 1306
                $result = call_user_func_array([$this->pdoStatement, $method], (array) $fetchMode);
1157 1306
                $this->pdoStatement->closeCursor();
1158
            }
1159
1160 1309
            $profile and Yii::endProfile($rawSql, 'yii\db\Command::query');
1161 22
        } catch (Exception $e) {
1162 22
            $profile and Yii::endProfile($rawSql, 'yii\db\Command::query');
1163 22
            throw $e;
1164
        }
1165
1166 1309
        if (isset($cache, $cacheKey, $info)) {
1167 6
            $cache->set($cacheKey, [$result], $info[1], $info[2]);
1168 6
            Yii::debug('Saved query result in cache', 'yii\db\Command::query');
1169
        }
1170
1171 1309
        return $result;
1172
    }
1173
1174
    /**
1175
     * Marks a specified table schema to be refreshed after command execution.
1176
     * @param string $name name of the table, which schema should be refreshed.
1177
     * @return $this this command instance
1178
     * @since 2.0.6
1179
     */
1180 150
    protected function requireTableSchemaRefresh($name)
1181
    {
1182 150
        $this->_refreshTableName = $name;
1183 150
        return $this;
1184
    }
1185
1186
    /**
1187
     * Refreshes table schema, which was marked by [[requireTableSchemaRefresh()]].
1188
     * @since 2.0.6
1189
     */
1190 673
    protected function refreshTableSchema()
1191
    {
1192 673
        if ($this->_refreshTableName !== null) {
1193 147
            $this->db->getSchema()->refreshTableSchema($this->_refreshTableName);
1194
        }
1195 673
    }
1196
1197
    /**
1198
     * Marks the command to be executed in transaction.
1199
     * @param string|null $isolationLevel The isolation level to use for this transaction.
1200
     * See [[Transaction::begin()]] for details.
1201
     * @return $this this command instance.
1202
     * @since 2.0.14
1203
     */
1204 3
    protected function requireTransaction($isolationLevel = null)
1205
    {
1206 3
        $this->_isolationLevel = $isolationLevel;
1207 3
        return $this;
1208
    }
1209
1210
    /**
1211
     * Sets a callable (e.g. anonymous function) that is called when [[Exception]] is thrown
1212
     * when executing the command. The signature of the callable should be:
1213
     *
1214
     * ```php
1215
     * function (\yii\db\Exception $e, $attempt)
1216
     * {
1217
     *     // return true or false (whether to retry the command or rethrow $e)
1218
     * }
1219
     * ```
1220
     *
1221
     * The callable will recieve a database exception thrown and a current attempt
1222
     * (to execute the command) number starting from 1.
1223
     *
1224
     * @param callable $handler a PHP callback to handle database exceptions.
1225
     * @return $this this command instance.
1226
     * @since 2.0.14
1227
     */
1228 3
    protected function setRetryHandler(callable $handler)
1229
    {
1230 3
        $this->_retryHandler = $handler;
1231 3
        return $this;
1232
    }
1233
1234
    /**
1235
     * Executes a prepared statement.
1236
     *
1237
     * It's a wrapper around [[\PDOStatement::execute()]] to support transactions
1238
     * and retry handlers.
1239
     *
1240
     * @param string|null $rawSql the rawSql if it has been created.
1241
     * @throws Exception if execution failed.
1242
     * @since 2.0.14
1243
     */
1244 1358
    protected function internalExecute($rawSql)
1245
    {
1246 1358
        $attempt = 0;
1247 1358
        while (true) {
1248
            try {
1249
                if (
1250 1358
                    ++$attempt === 1
1251 1358
                    && $this->_isolationLevel !== false
1252 1358
                    && $this->db->getTransaction() === null
1253
                ) {
1254 3
                    $this->db->transaction(function () use ($rawSql) {
1255 3
                        $this->internalExecute($rawSql);
1256 3
                    }, $this->_isolationLevel);
1257
                } else {
1258 1358
                    $this->pdoStatement->execute();
1259
                }
1260 1355
                break;
1261 32
            } catch (\Exception $e) {
1262 32
                $rawSql = $rawSql ?: $this->getRawSql();
1263 32
                $e = $this->db->getSchema()->convertException($e, $rawSql);
1264 32
                if ($this->_retryHandler === null || !call_user_func($this->_retryHandler, $e, $attempt)) {
1265 32
                    throw $e;
1266
                }
1267
            }
1268
        }
1269 1355
    }
1270
1271
    /**
1272
     * Resets command properties to their initial state.
1273
     *
1274
     * @since 2.0.13
1275
     */
1276 1398
    protected function reset()
1277
    {
1278 1398
        $this->_sql = null;
1279 1398
        $this->_pendingParams = [];
1280 1398
        $this->params = [];
1281 1398
        $this->_refreshTableName = null;
1282 1398
        $this->_isolationLevel = false;
1283 1398
        $this->_retryHandler = null;
1284 1398
    }
1285
}
1286