Passed
Push — fix-master ( d14f05 )
by Alexander
77:57 queued 70:24
created

Command::batchInsert()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 14
Code Lines 9

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 9
CRAP Score 1

Importance

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

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