Completed
Pull Request — master (#15415)
by Sergey
31:47 queued 28:06
created

Command::requireTransaction()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 5
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 3
CRAP Score 1

Importance

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