Completed
Push — master ( 59e591...a036fa )
by Dmitry
58:51 queued 22:18
created

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