Command.php 38 KB

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