Completed
Push — master ( e65451...7e7fae )
by Dmitry
52:36 queued 49:19
created

Command::setRawSql()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 10
Code Lines 6

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 6
CRAP Score 2

Importance

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