Completed
Push — fix-11176 ( 8d8cd1 )
by Carsten
08:17 queued 02:34
created

Command   D

Complexity

Total Complexity 87

Size/Duplication

Total Lines 892
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 8

Test Coverage

Coverage 84.44%

Importance

Changes 1
Bugs 0 Features 0
Metric Value
wmc 87
c 1
b 0
f 0
lcom 1
cbo 8
dl 0
loc 892
ccs 217
cts 257
cp 0.8444
rs 4.4444

44 Methods

Rating   Name   Duplication   Size   Complexity  
A cache() 0 6 2
A noCache() 0 5 1
A getSql() 0 4 1
A setSql() 0 12 2
C getRawSql() 0 30 14
C prepare() 0 28 8
A cancel() 0 4 1
A bindParam() 0 18 4
A bindPendingParams() 0 7 2
A bindValue() 0 10 2
A bindValues() 0 20 4
A query() 0 4 1
A queryAll() 0 4 1
A queryOne() 0 4 1
A queryScalar() 0 9 3
A queryColumn() 0 4 1
A insert() 0 7 1
A batchInsert() 0 6 1
A update() 0 6 1
A delete() 0 6 1
A createTable() 0 6 1
A renameTable() 0 6 1
A dropTable() 0 6 1
A truncateTable() 0 6 1
A addColumn() 0 6 1
A dropColumn() 0 6 1
A renameColumn() 0 6 1
A alterColumn() 0 6 1
A addPrimaryKey() 0 6 1
A dropPrimaryKey() 0 6 1
A addForeignKey() 0 6 1
A dropForeignKey() 0 6 1
A createIndex() 0 6 1
A dropIndex() 0 6 1
A resetSequence() 0 6 1
A checkIntegrity() 0 6 1
A addCommentOnColumn() 0 6 1
A addCommentOnTable() 0 6 1
A dropCommentFromColumn() 0 6 1
A dropCommentFromTable() 0 6 1
B execute() 0 31 3
C queryInternal() 0 58 9
A requireTableSchemaRefresh() 0 5 1
A refreshTableSchema() 0 6 2

How to fix   Complexity   

Complex Class

Complex classes like Command often do a lot of different things. To break such a class down, we need to identify a cohesive component within that class. A common approach to find such a component is to look for fields/methods that share the same prefixes, or suffixes. You can also have a look at the cohesion graph to spot any un-connected, or weakly-connected components.

Once you have determined the fields that belong together, you can apply the Extract Class refactoring. If the component makes sense as a sub-class, Extract Subclass is also a candidate, and is often faster.

While breaking up the class, it is a good idea to analyze how other classes use Command, and based on these observations, apply Extract Interface, too.

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