Command.php 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756
  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. namespace yii\db;
  8. use Yii;
  9. use yii\base\NotSupportedException;
  10. use yii\caching\Cache;
  11. /**
  12. * Command represents a SQL statement to be executed against a database.
  13. *
  14. * A command object is usually created by calling [[Connection::createCommand()]].
  15. * The SQL statement it represents can be set via the [[sql]] property.
  16. *
  17. * To execute a non-query SQL (such as INSERT, DELETE, UPDATE), call [[execute()]].
  18. * To execute a SQL statement that returns result data set (such as SELECT),
  19. * use [[queryAll()]], [[queryOne()]], [[queryColumn()]], [[queryScalar()]], or [[query()]].
  20. * For example,
  21. *
  22. * ~~~
  23. * $users = $connection->createCommand('SELECT * FROM tbl_user')->queryAll();
  24. * ~~~
  25. *
  26. * Command supports SQL statement preparation and parameter binding.
  27. * Call [[bindValue()]] to bind a value to a SQL parameter;
  28. * Call [[bindParam()]] to bind a PHP variable to a SQL parameter.
  29. * When binding a parameter, the SQL statement is automatically prepared.
  30. * You may also call [[prepare()]] explicitly to prepare a SQL statement.
  31. *
  32. * Command also supports building SQL statements by providing methods such as [[insert()]],
  33. * [[update()]], etc. For example,
  34. *
  35. * ~~~
  36. * $connection->createCommand()->insert('tbl_user', [
  37. * 'name' => 'Sam',
  38. * 'age' => 30,
  39. * ])->execute();
  40. * ~~~
  41. *
  42. * To build SELECT SQL statements, please use [[QueryBuilder]] instead.
  43. *
  44. * @property string $rawSql The raw SQL with parameter values inserted into the corresponding placeholders in
  45. * [[sql]]. This property is read-only.
  46. * @property string $sql The SQL statement to be executed.
  47. *
  48. * @author Qiang Xue <[email protected]>
  49. * @since 2.0
  50. */
  51. class Command extends \yii\base\Component
  52. {
  53. /**
  54. * @var Connection the DB connection that this command is associated with
  55. */
  56. public $db;
  57. /**
  58. * @var \PDOStatement the PDOStatement object that this command is associated with
  59. */
  60. public $pdoStatement;
  61. /**
  62. * @var integer the default fetch mode for this command.
  63. * @see http://www.php.net/manual/en/function.PDOStatement-setFetchMode.php
  64. */
  65. public $fetchMode = \PDO::FETCH_ASSOC;
  66. /**
  67. * @var array the parameters (name => value) that are bound to the current PDO statement.
  68. * This property is maintained by methods such as [[bindValue()]].
  69. * Do not modify it directly.
  70. */
  71. public $params = [];
  72. /**
  73. * @var string the SQL statement that this command represents
  74. */
  75. private $_sql;
  76. /**
  77. * Returns the SQL statement for this command.
  78. * @return string the SQL statement to be executed
  79. */
  80. public function getSql()
  81. {
  82. return $this->_sql;
  83. }
  84. /**
  85. * Specifies the SQL statement to be executed.
  86. * The previous SQL execution (if any) will be cancelled, and [[params]] will be cleared as well.
  87. * @param string $sql the SQL statement to be set.
  88. * @return static this command instance
  89. */
  90. public function setSql($sql)
  91. {
  92. if ($sql !== $this->_sql) {
  93. $this->cancel();
  94. $this->_sql = $this->db->quoteSql($sql);
  95. $this->params = [];
  96. }
  97. return $this;
  98. }
  99. /**
  100. * Returns the raw SQL by inserting parameter values into the corresponding placeholders in [[sql]].
  101. * Note that the return value of this method should mainly be used for logging purpose.
  102. * It is likely that this method returns an invalid SQL due to improper replacement of parameter placeholders.
  103. * @return string the raw SQL with parameter values inserted into the corresponding placeholders in [[sql]].
  104. */
  105. public function getRawSql()
  106. {
  107. if (empty($this->params)) {
  108. return $this->_sql;
  109. } else {
  110. $params = [];
  111. foreach ($this->params as $name => $value) {
  112. if (is_string($value)) {
  113. $params[$name] = $this->db->quoteValue($value);
  114. } elseif ($value === null) {
  115. $params[$name] = 'NULL';
  116. } else {
  117. $params[$name] = $value;
  118. }
  119. }
  120. if (isset($params[1])) {
  121. $sql = '';
  122. foreach (explode('?', $this->_sql) as $i => $part) {
  123. $sql .= (isset($params[$i]) ? $params[$i] : '') . $part;
  124. }
  125. return $sql;
  126. } else {
  127. return strtr($this->_sql, $params);
  128. }
  129. }
  130. }
  131. /**
  132. * Prepares the SQL statement to be executed.
  133. * For complex SQL statement that is to be executed multiple times,
  134. * this may improve performance.
  135. * For SQL statement with binding parameters, this method is invoked
  136. * automatically.
  137. * @throws Exception if there is any DB error
  138. */
  139. public function prepare()
  140. {
  141. if ($this->pdoStatement == null) {
  142. $sql = $this->getSql();
  143. try {
  144. $this->pdoStatement = $this->db->pdo->prepare($sql);
  145. } catch (\Exception $e) {
  146. $message = $e->getMessage() . "\nFailed to prepare SQL: $sql";
  147. $errorInfo = $e instanceof \PDOException ? $e->errorInfo : null;
  148. throw new Exception($message, $errorInfo, (int)$e->getCode(), $e);
  149. }
  150. }
  151. }
  152. /**
  153. * Cancels the execution of the SQL statement.
  154. * This method mainly sets [[pdoStatement]] to be null.
  155. */
  156. public function cancel()
  157. {
  158. $this->pdoStatement = null;
  159. }
  160. /**
  161. * Binds a parameter to the SQL statement to be executed.
  162. * @param string|integer $name parameter identifier. For a prepared statement
  163. * using named placeholders, this will be a parameter name of
  164. * the form `:name`. For a prepared statement using question mark
  165. * placeholders, this will be the 1-indexed position of the parameter.
  166. * @param mixed $value Name of the PHP variable to bind to the SQL statement parameter
  167. * @param integer $dataType SQL data type of the parameter. If null, the type is determined by the PHP type of the value.
  168. * @param integer $length length of the data type
  169. * @param mixed $driverOptions the driver-specific options
  170. * @return static the current command being executed
  171. * @see http://www.php.net/manual/en/function.PDOStatement-bindParam.php
  172. */
  173. public function bindParam($name, &$value, $dataType = null, $length = null, $driverOptions = null)
  174. {
  175. $this->prepare();
  176. if ($dataType === null) {
  177. $dataType = $this->db->getSchema()->getPdoType($value);
  178. }
  179. if ($length === null) {
  180. $this->pdoStatement->bindParam($name, $value, $dataType);
  181. } elseif ($driverOptions === null) {
  182. $this->pdoStatement->bindParam($name, $value, $dataType, $length);
  183. } else {
  184. $this->pdoStatement->bindParam($name, $value, $dataType, $length, $driverOptions);
  185. }
  186. $this->params[$name] =& $value;
  187. return $this;
  188. }
  189. /**
  190. * Binds a value to a parameter.
  191. * @param string|integer $name Parameter identifier. For a prepared statement
  192. * using named placeholders, this will be a parameter name of
  193. * the form `:name`. For a prepared statement using question mark
  194. * placeholders, this will be the 1-indexed position of the parameter.
  195. * @param mixed $value The value to bind to the parameter
  196. * @param integer $dataType SQL data type of the parameter. If null, the type is determined by the PHP type of the value.
  197. * @return static the current command being executed
  198. * @see http://www.php.net/manual/en/function.PDOStatement-bindValue.php
  199. */
  200. public function bindValue($name, $value, $dataType = null)
  201. {
  202. $this->prepare();
  203. if ($dataType === null) {
  204. $dataType = $this->db->getSchema()->getPdoType($value);
  205. }
  206. $this->pdoStatement->bindValue($name, $value, $dataType);
  207. $this->params[$name] = $value;
  208. return $this;
  209. }
  210. /**
  211. * Binds a list of values to the corresponding parameters.
  212. * This is similar to [[bindValue()]] except that it binds multiple values at a time.
  213. * Note that the SQL data type of each value is determined by its PHP type.
  214. * @param array $values the values to be bound. This must be given in terms of an associative
  215. * array with array keys being the parameter names, and array values the corresponding parameter values,
  216. * e.g. `[':name' => 'John', ':age' => 25]`. By default, the PDO type of each value is determined
  217. * by its PHP type. You may explicitly specify the PDO type by using an array: `[value, type]`,
  218. * e.g. `[':name' => 'John', ':profile' => [$profile, \PDO::PARAM_LOB]]`.
  219. * @return static the current command being executed
  220. */
  221. public function bindValues($values)
  222. {
  223. if (!empty($values)) {
  224. $this->prepare();
  225. foreach ($values as $name => $value) {
  226. if (is_array($value)) {
  227. $type = $value[1];
  228. $value = $value[0];
  229. } else {
  230. $type = $this->db->getSchema()->getPdoType($value);
  231. }
  232. $this->pdoStatement->bindValue($name, $value, $type);
  233. $this->params[$name] = $value;
  234. }
  235. }
  236. return $this;
  237. }
  238. /**
  239. * Executes the SQL statement.
  240. * This method should only be used for executing non-query SQL statement, such as `INSERT`, `DELETE`, `UPDATE` SQLs.
  241. * No result set will be returned.
  242. * @return integer number of rows affected by the execution.
  243. * @throws Exception execution failed
  244. */
  245. public function execute()
  246. {
  247. $sql = $this->getSql();
  248. $rawSql = $this->getRawSql();
  249. Yii::info($rawSql, __METHOD__);
  250. if ($sql == '') {
  251. return 0;
  252. }
  253. $token = $rawSql;
  254. try {
  255. Yii::beginProfile($token, __METHOD__);
  256. $this->prepare();
  257. $this->pdoStatement->execute();
  258. $n = $this->pdoStatement->rowCount();
  259. Yii::endProfile($token, __METHOD__);
  260. return $n;
  261. } catch (\Exception $e) {
  262. Yii::endProfile($token, __METHOD__);
  263. if ($e instanceof Exception) {
  264. throw $e;
  265. } else {
  266. $message = $e->getMessage() . "\nThe SQL being executed was: $rawSql";
  267. $errorInfo = $e instanceof \PDOException ? $e->errorInfo : null;
  268. throw new Exception($message, $errorInfo, (int)$e->getCode(), $e);
  269. }
  270. }
  271. }
  272. /**
  273. * Executes the SQL statement and returns query result.
  274. * This method is for executing a SQL query that returns result set, such as `SELECT`.
  275. * @return DataReader the reader object for fetching the query result
  276. * @throws Exception execution failed
  277. */
  278. public function query()
  279. {
  280. return $this->queryInternal('');
  281. }
  282. /**
  283. * Executes the SQL statement and returns ALL rows at once.
  284. * @param integer $fetchMode the result fetch mode. Please refer to [PHP manual](http://www.php.net/manual/en/function.PDOStatement-setFetchMode.php)
  285. * for valid fetch modes. If this parameter is null, the value set in [[fetchMode]] will be used.
  286. * @return array all rows of the query result. Each array element is an array representing a row of data.
  287. * An empty array is returned if the query results in nothing.
  288. * @throws Exception execution failed
  289. */
  290. public function queryAll($fetchMode = null)
  291. {
  292. return $this->queryInternal('fetchAll', $fetchMode);
  293. }
  294. /**
  295. * Executes the SQL statement and returns the first row of the result.
  296. * This method is best used when only the first row of result is needed for a query.
  297. * @param integer $fetchMode the result fetch mode. Please refer to [PHP manual](http://www.php.net/manual/en/function.PDOStatement-setFetchMode.php)
  298. * for valid fetch modes. If this parameter is null, the value set in [[fetchMode]] will be used.
  299. * @return array|boolean the first row (in terms of an array) of the query result. False is returned if the query
  300. * results in nothing.
  301. * @throws Exception execution failed
  302. */
  303. public function queryOne($fetchMode = null)
  304. {
  305. return $this->queryInternal('fetch', $fetchMode);
  306. }
  307. /**
  308. * Executes the SQL statement and returns the value of the first column in the first row of data.
  309. * This method is best used when only a single value is needed for a query.
  310. * @return string|boolean the value of the first column in the first row of the query result.
  311. * False is returned if there is no value.
  312. * @throws Exception execution failed
  313. */
  314. public function queryScalar()
  315. {
  316. $result = $this->queryInternal('fetchColumn', 0);
  317. if (is_resource($result) && get_resource_type($result) === 'stream') {
  318. return stream_get_contents($result);
  319. } else {
  320. return $result;
  321. }
  322. }
  323. /**
  324. * Executes the SQL statement and returns the first column of the result.
  325. * This method is best used when only the first column of result (i.e. the first element in each row)
  326. * is needed for a query.
  327. * @return array the first column of the query result. Empty array is returned if the query results in nothing.
  328. * @throws Exception execution failed
  329. */
  330. public function queryColumn()
  331. {
  332. return $this->queryInternal('fetchAll', \PDO::FETCH_COLUMN);
  333. }
  334. /**
  335. * Performs the actual DB query of a SQL statement.
  336. * @param string $method method of PDOStatement to be called
  337. * @param integer $fetchMode the result fetch mode. Please refer to [PHP manual](http://www.php.net/manual/en/function.PDOStatement-setFetchMode.php)
  338. * for valid fetch modes. If this parameter is null, the value set in [[fetchMode]] will be used.
  339. * @return mixed the method execution result
  340. * @throws Exception if the query causes any problem
  341. */
  342. private function queryInternal($method, $fetchMode = null)
  343. {
  344. $db = $this->db;
  345. $rawSql = $this->getRawSql();
  346. Yii::info($rawSql, 'yii\db\Command::query');
  347. /** @var \yii\caching\Cache $cache */
  348. if ($db->enableQueryCache && $method !== '') {
  349. $cache = is_string($db->queryCache) ? Yii::$app->getComponent($db->queryCache) : $db->queryCache;
  350. }
  351. if (isset($cache) && $cache instanceof Cache) {
  352. $cacheKey = [
  353. __CLASS__,
  354. $method,
  355. $db->dsn,
  356. $db->username,
  357. $rawSql,
  358. ];
  359. if (($result = $cache->get($cacheKey)) !== false) {
  360. Yii::trace('Query result served from cache', 'yii\db\Command::query');
  361. return $result;
  362. }
  363. }
  364. $token = $rawSql;
  365. try {
  366. Yii::beginProfile($token, 'yii\db\Command::query');
  367. $this->prepare();
  368. $this->pdoStatement->execute();
  369. if ($method === '') {
  370. $result = new DataReader($this);
  371. } else {
  372. if ($fetchMode === null) {
  373. $fetchMode = $this->fetchMode;
  374. }
  375. $result = call_user_func_array([$this->pdoStatement, $method], (array)$fetchMode);
  376. $this->pdoStatement->closeCursor();
  377. }
  378. Yii::endProfile($token, 'yii\db\Command::query');
  379. if (isset($cache, $cacheKey) && $cache instanceof Cache) {
  380. $cache->set($cacheKey, $result, $db->queryCacheDuration, $db->queryCacheDependency);
  381. Yii::trace('Saved query result in cache', 'yii\db\Command::query');
  382. }
  383. return $result;
  384. } catch (\Exception $e) {
  385. Yii::endProfile($token, 'yii\db\Command::query');
  386. if ($e instanceof Exception) {
  387. throw $e;
  388. } else {
  389. $message = $e->getMessage() . "\nThe SQL being executed was: $rawSql";
  390. $errorInfo = $e instanceof \PDOException ? $e->errorInfo : null;
  391. throw new Exception($message, $errorInfo, (int)$e->getCode(), $e);
  392. }
  393. }
  394. }
  395. /**
  396. * Creates an INSERT command.
  397. * For example,
  398. *
  399. * ~~~
  400. * $connection->createCommand()->insert('tbl_user', [
  401. * 'name' => 'Sam',
  402. * 'age' => 30,
  403. * ])->execute();
  404. * ~~~
  405. *
  406. * The method will properly escape the column names, and bind the values to be inserted.
  407. *
  408. * Note that the created command is not executed until [[execute()]] is called.
  409. *
  410. * @param string $table the table that new rows will be inserted into.
  411. * @param array $columns the column data (name => value) to be inserted into the table.
  412. * @return Command the command object itself
  413. */
  414. public function insert($table, $columns)
  415. {
  416. $params = [];
  417. $sql = $this->db->getQueryBuilder()->insert($table, $columns, $params);
  418. return $this->setSql($sql)->bindValues($params);
  419. }
  420. /**
  421. * Creates a batch INSERT command.
  422. * For example,
  423. *
  424. * ~~~
  425. * $connection->createCommand()->batchInsert('tbl_user', ['name', 'age'], [
  426. * ['Tom', 30],
  427. * ['Jane', 20],
  428. * ['Linda', 25],
  429. * ])->execute();
  430. * ~~~
  431. *
  432. * Note that the values in each row must match the corresponding column names.
  433. *
  434. * @param string $table the table that new rows will be inserted into.
  435. * @param array $columns the column names
  436. * @param array $rows the rows to be batch inserted into the table
  437. * @return Command the command object itself
  438. */
  439. public function batchInsert($table, $columns, $rows)
  440. {
  441. $sql = $this->db->getQueryBuilder()->batchInsert($table, $columns, $rows);
  442. return $this->setSql($sql);
  443. }
  444. /**
  445. * Creates an UPDATE command.
  446. * For example,
  447. *
  448. * ~~~
  449. * $connection->createCommand()->update('tbl_user', ['status' => 1], 'age > 30')->execute();
  450. * ~~~
  451. *
  452. * The method will properly escape the column names and bind the values to be updated.
  453. *
  454. * Note that the created command is not executed until [[execute()]] is called.
  455. *
  456. * @param string $table the table to be updated.
  457. * @param array $columns the column data (name => value) to be updated.
  458. * @param string|array $condition the condition that will be put in the WHERE part. Please
  459. * refer to [[Query::where()]] on how to specify condition.
  460. * @param array $params the parameters to be bound to the command
  461. * @return Command the command object itself
  462. */
  463. public function update($table, $columns, $condition = '', $params = [])
  464. {
  465. $sql = $this->db->getQueryBuilder()->update($table, $columns, $condition, $params);
  466. return $this->setSql($sql)->bindValues($params);
  467. }
  468. /**
  469. * Creates a DELETE command.
  470. * For example,
  471. *
  472. * ~~~
  473. * $connection->createCommand()->delete('tbl_user', 'status = 0')->execute();
  474. * ~~~
  475. *
  476. * The method will properly escape the table and column names.
  477. *
  478. * Note that the created command is not executed until [[execute()]] is called.
  479. *
  480. * @param string $table the table where the data will be deleted from.
  481. * @param string|array $condition the condition that will be put in the WHERE part. Please
  482. * refer to [[Query::where()]] on how to specify condition.
  483. * @param array $params the parameters to be bound to the command
  484. * @return Command the command object itself
  485. */
  486. public function delete($table, $condition = '', $params = [])
  487. {
  488. $sql = $this->db->getQueryBuilder()->delete($table, $condition, $params);
  489. return $this->setSql($sql)->bindValues($params);
  490. }
  491. /**
  492. * Creates a SQL command for creating a new DB table.
  493. *
  494. * The columns in the new table should be specified as name-definition pairs (e.g. 'name' => 'string'),
  495. * where name stands for a column name which will be properly quoted by the method, and definition
  496. * stands for the column type which can contain an abstract DB type.
  497. * The method [[QueryBuilder::getColumnType()]] will be called
  498. * to convert the abstract column types to physical ones. For example, `string` will be converted
  499. * as `varchar(255)`, and `string not null` becomes `varchar(255) not null`.
  500. *
  501. * If a column is specified with definition only (e.g. 'PRIMARY KEY (name, type)'), it will be directly
  502. * inserted into the generated SQL.
  503. *
  504. * @param string $table the name of the table to be created. The name will be properly quoted by the method.
  505. * @param array $columns the columns (name => definition) in the new table.
  506. * @param string $options additional SQL fragment that will be appended to the generated SQL.
  507. * @return Command the command object itself
  508. */
  509. public function createTable($table, $columns, $options = null)
  510. {
  511. $sql = $this->db->getQueryBuilder()->createTable($table, $columns, $options);
  512. return $this->setSql($sql);
  513. }
  514. /**
  515. * Creates a SQL command for renaming a DB table.
  516. * @param string $table the table to be renamed. The name will be properly quoted by the method.
  517. * @param string $newName the new table name. The name will be properly quoted by the method.
  518. * @return Command the command object itself
  519. */
  520. public function renameTable($table, $newName)
  521. {
  522. $sql = $this->db->getQueryBuilder()->renameTable($table, $newName);
  523. return $this->setSql($sql);
  524. }
  525. /**
  526. * Creates a SQL command for dropping a DB table.
  527. * @param string $table the table to be dropped. The name will be properly quoted by the method.
  528. * @return Command the command object itself
  529. */
  530. public function dropTable($table)
  531. {
  532. $sql = $this->db->getQueryBuilder()->dropTable($table);
  533. return $this->setSql($sql);
  534. }
  535. /**
  536. * Creates a SQL command for truncating a DB table.
  537. * @param string $table the table to be truncated. The name will be properly quoted by the method.
  538. * @return Command the command object itself
  539. */
  540. public function truncateTable($table)
  541. {
  542. $sql = $this->db->getQueryBuilder()->truncateTable($table);
  543. return $this->setSql($sql);
  544. }
  545. /**
  546. * Creates a SQL command for adding a new DB column.
  547. * @param string $table the table that the new column will be added to. The table name will be properly quoted by the method.
  548. * @param string $column the name of the new column. The name will be properly quoted by the method.
  549. * @param string $type the column type. [[\yii\db\QueryBuilder::getColumnType()]] will be called
  550. * to convert the give column type to the physical one. For example, `string` will be converted
  551. * as `varchar(255)`, and `string not null` becomes `varchar(255) not null`.
  552. * @return Command the command object itself
  553. */
  554. public function addColumn($table, $column, $type)
  555. {
  556. $sql = $this->db->getQueryBuilder()->addColumn($table, $column, $type);
  557. return $this->setSql($sql);
  558. }
  559. /**
  560. * Creates a SQL command for dropping a DB column.
  561. * @param string $table the table whose column is to be dropped. The name will be properly quoted by the method.
  562. * @param string $column the name of the column to be dropped. The name will be properly quoted by the method.
  563. * @return Command the command object itself
  564. */
  565. public function dropColumn($table, $column)
  566. {
  567. $sql = $this->db->getQueryBuilder()->dropColumn($table, $column);
  568. return $this->setSql($sql);
  569. }
  570. /**
  571. * Creates a SQL command for renaming a column.
  572. * @param string $table the table whose column is to be renamed. The name will be properly quoted by the method.
  573. * @param string $oldName the old name of the column. The name will be properly quoted by the method.
  574. * @param string $newName the new name of the column. The name will be properly quoted by the method.
  575. * @return Command the command object itself
  576. */
  577. public function renameColumn($table, $oldName, $newName)
  578. {
  579. $sql = $this->db->getQueryBuilder()->renameColumn($table, $oldName, $newName);
  580. return $this->setSql($sql);
  581. }
  582. /**
  583. * Creates a SQL command for changing the definition of a column.
  584. * @param string $table the table whose column is to be changed. The table name will be properly quoted by the method.
  585. * @param string $column the name of the column to be changed. The name will be properly quoted by the method.
  586. * @param string $type the column type. [[\yii\db\QueryBuilder::getColumnType()]] will be called
  587. * to convert the give column type to the physical one. For example, `string` will be converted
  588. * as `varchar(255)`, and `string not null` becomes `varchar(255) not null`.
  589. * @return Command the command object itself
  590. */
  591. public function alterColumn($table, $column, $type)
  592. {
  593. $sql = $this->db->getQueryBuilder()->alterColumn($table, $column, $type);
  594. return $this->setSql($sql);
  595. }
  596. /**
  597. * Creates a SQL command for adding a primary key constraint to an existing table.
  598. * The method will properly quote the table and column names.
  599. * @param string $name the name of the primary key constraint.
  600. * @param string $table the table that the primary key constraint will be added to.
  601. * @param string|array $columns comma separated string or array of columns that the primary key will consist of.
  602. * @return Command the command object itself.
  603. */
  604. public function addPrimaryKey($name, $table, $columns)
  605. {
  606. $sql = $this->db->getQueryBuilder()->addPrimaryKey($name, $table, $columns);
  607. return $this->setSql($sql);
  608. }
  609. /**
  610. * Creates a SQL command for removing a primary key constraint to an existing table.
  611. * @param string $name the name of the primary key constraint to be removed.
  612. * @param string $table the table that the primary key constraint will be removed from.
  613. * @return Command the command object itself
  614. */
  615. public function dropPrimaryKey($name, $table)
  616. {
  617. $sql = $this->db->getQueryBuilder()->dropPrimaryKey($name, $table);
  618. return $this->setSql($sql);
  619. }
  620. /**
  621. * Creates a SQL command for adding a foreign key constraint to an existing table.
  622. * The method will properly quote the table and column names.
  623. * @param string $name the name of the foreign key constraint.
  624. * @param string $table the table that the foreign key constraint will be added to.
  625. * @param string $columns the name of the column to that the constraint will be added on. If there are multiple columns, separate them with commas.
  626. * @param string $refTable the table that the foreign key references to.
  627. * @param string $refColumns the name of the column that the foreign key references to. If there are multiple columns, separate them with commas.
  628. * @param string $delete the ON DELETE option. Most DBMS support these options: RESTRICT, CASCADE, NO ACTION, SET DEFAULT, SET NULL
  629. * @param string $update the ON UPDATE option. Most DBMS support these options: RESTRICT, CASCADE, NO ACTION, SET DEFAULT, SET NULL
  630. * @return Command the command object itself
  631. */
  632. public function addForeignKey($name, $table, $columns, $refTable, $refColumns, $delete = null, $update = null)
  633. {
  634. $sql = $this->db->getQueryBuilder()->addForeignKey($name, $table, $columns, $refTable, $refColumns, $delete, $update);
  635. return $this->setSql($sql);
  636. }
  637. /**
  638. * Creates a SQL command for dropping a foreign key constraint.
  639. * @param string $name the name of the foreign key constraint to be dropped. The name will be properly quoted by the method.
  640. * @param string $table the table whose foreign is to be dropped. The name will be properly quoted by the method.
  641. * @return Command the command object itself
  642. */
  643. public function dropForeignKey($name, $table)
  644. {
  645. $sql = $this->db->getQueryBuilder()->dropForeignKey($name, $table);
  646. return $this->setSql($sql);
  647. }
  648. /**
  649. * Creates a SQL command for creating a new index.
  650. * @param string $name the name of the index. The name will be properly quoted by the method.
  651. * @param string $table the table that the new index will be created for. The table name will be properly quoted by the method.
  652. * @param string $columns the column(s) that should be included in the index. If there are multiple columns, please separate them
  653. * by commas. The column names will be properly quoted by the method.
  654. * @param boolean $unique whether to add UNIQUE constraint on the created index.
  655. * @return Command the command object itself
  656. */
  657. public function createIndex($name, $table, $columns, $unique = false)
  658. {
  659. $sql = $this->db->getQueryBuilder()->createIndex($name, $table, $columns, $unique);
  660. return $this->setSql($sql);
  661. }
  662. /**
  663. * Creates a SQL command for dropping an index.
  664. * @param string $name the name of the index to be dropped. The name will be properly quoted by the method.
  665. * @param string $table the table whose index is to be dropped. The name will be properly quoted by the method.
  666. * @return Command the command object itself
  667. */
  668. public function dropIndex($name, $table)
  669. {
  670. $sql = $this->db->getQueryBuilder()->dropIndex($name, $table);
  671. return $this->setSql($sql);
  672. }
  673. /**
  674. * Creates a SQL command for resetting the sequence value of a table's primary key.
  675. * The sequence will be reset such that the primary key of the next new row inserted
  676. * will have the specified value or 1.
  677. * @param string $table the name of the table whose primary key sequence will be reset
  678. * @param mixed $value the value for the primary key of the next new row inserted. If this is not set,
  679. * the next new row's primary key will have a value 1.
  680. * @return Command the command object itself
  681. * @throws NotSupportedException if this is not supported by the underlying DBMS
  682. */
  683. public function resetSequence($table, $value = null)
  684. {
  685. $sql = $this->db->getQueryBuilder()->resetSequence($table, $value);
  686. return $this->setSql($sql);
  687. }
  688. /**
  689. * Builds a SQL command for enabling or disabling integrity check.
  690. * @param boolean $check whether to turn on or off the integrity check.
  691. * @param string $schema the schema name of the tables. Defaults to empty string, meaning the current
  692. * or default schema.
  693. * @param string $table the table name.
  694. * @return Command the command object itself
  695. * @throws NotSupportedException if this is not supported by the underlying DBMS
  696. */
  697. public function checkIntegrity($check = true, $schema = '', $table = '')
  698. {
  699. $sql = $this->db->getQueryBuilder()->checkIntegrity($check, $schema, $table);
  700. return $this->setSql($sql);
  701. }
  702. }