949 lines
37KB

  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 integer the default fetch mode for this command.
  66. * @see http://www.php.net/manual/en/function.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 integer 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 integer $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 boolean $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|integer $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 integer $dataType SQL data type of the parameter. If null, the type is determined by the PHP type of the value.
  233. * @param integer $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|integer $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 integer $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 integer $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 integer $fetchMode the result fetch mode. Please refer to [PHP manual](http://www.php.net/manual/en/function.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 $columns the column data (name => value) to be inserted into the table.
  393. * @return $this the command object itself
  394. */
  395. public function insert($table, $columns)
  396. {
  397. $params = [];
  398. $sql = $this->db->getQueryBuilder()->insert($table, $columns, $params);
  399. return $this->setSql($sql)->bindValues($params);
  400. }
  401. /**
  402. * Creates a batch INSERT command.
  403. * For example,
  404. *
  405. * ```php
  406. * $connection->createCommand()->batchInsert('user', ['name', 'age'], [
  407. * ['Tom', 30],
  408. * ['Jane', 20],
  409. * ['Linda', 25],
  410. * ])->execute();
  411. * ```
  412. *
  413. * The method will properly escape the column names, and quote the values to be inserted.
  414. *
  415. * Note that the values in each row must match the corresponding column names.
  416. *
  417. * Also note that the created command is not executed until [[execute()]] is called.
  418. *
  419. * @param string $table the table that new rows will be inserted into.
  420. * @param array $columns the column names
  421. * @param array $rows the rows to be batch inserted into the table
  422. * @return $this the command object itself
  423. */
  424. public function batchInsert($table, $columns, $rows)
  425. {
  426. $sql = $this->db->getQueryBuilder()->batchInsert($table, $columns, $rows);
  427. return $this->setSql($sql);
  428. }
  429. /**
  430. * Creates an UPDATE command.
  431. * For example,
  432. *
  433. * ```php
  434. * $connection->createCommand()->update('user', ['status' => 1], 'age > 30')->execute();
  435. * ```
  436. *
  437. * The method will properly escape the column names and bind the values to be updated.
  438. *
  439. * Note that the created command is not executed until [[execute()]] is called.
  440. *
  441. * @param string $table the table to be updated.
  442. * @param array $columns the column data (name => value) to be updated.
  443. * @param string|array $condition the condition that will be put in the WHERE part. Please
  444. * refer to [[Query::where()]] on how to specify condition.
  445. * @param array $params the parameters to be bound to the command
  446. * @return $this the command object itself
  447. */
  448. public function update($table, $columns, $condition = '', $params = [])
  449. {
  450. $sql = $this->db->getQueryBuilder()->update($table, $columns, $condition, $params);
  451. return $this->setSql($sql)->bindValues($params);
  452. }
  453. /**
  454. * Creates a DELETE command.
  455. * For example,
  456. *
  457. * ```php
  458. * $connection->createCommand()->delete('user', 'status = 0')->execute();
  459. * ```
  460. *
  461. * The method will properly escape the table and column names.
  462. *
  463. * Note that the created command is not executed until [[execute()]] is called.
  464. *
  465. * @param string $table the table where the data will be deleted from.
  466. * @param string|array $condition the condition that will be put in the WHERE part. Please
  467. * refer to [[Query::where()]] on how to specify condition.
  468. * @param array $params the parameters to be bound to the command
  469. * @return $this the command object itself
  470. */
  471. public function delete($table, $condition = '', $params = [])
  472. {
  473. $sql = $this->db->getQueryBuilder()->delete($table, $condition, $params);
  474. return $this->setSql($sql)->bindValues($params);
  475. }
  476. /**
  477. * Creates a SQL command for creating a new DB table.
  478. *
  479. * The columns in the new table should be specified as name-definition pairs (e.g. 'name' => 'string'),
  480. * where name stands for a column name which will be properly quoted by the method, and definition
  481. * stands for the column type which can contain an abstract DB type.
  482. * The method [[QueryBuilder::getColumnType()]] will be called
  483. * to convert the abstract column types to physical ones. For example, `string` will be converted
  484. * as `varchar(255)`, and `string not null` becomes `varchar(255) not null`.
  485. *
  486. * If a column is specified with definition only (e.g. 'PRIMARY KEY (name, type)'), it will be directly
  487. * inserted into the generated SQL.
  488. *
  489. * @param string $table the name of the table to be created. The name will be properly quoted by the method.
  490. * @param array $columns the columns (name => definition) in the new table.
  491. * @param string $options additional SQL fragment that will be appended to the generated SQL.
  492. * @return $this the command object itself
  493. */
  494. public function createTable($table, $columns, $options = null)
  495. {
  496. $sql = $this->db->getQueryBuilder()->createTable($table, $columns, $options);
  497. return $this->setSql($sql);
  498. }
  499. /**
  500. * Creates a SQL command for renaming a DB table.
  501. * @param string $table the table to be renamed. The name will be properly quoted by the method.
  502. * @param string $newName the new table name. The name will be properly quoted by the method.
  503. * @return $this the command object itself
  504. */
  505. public function renameTable($table, $newName)
  506. {
  507. $sql = $this->db->getQueryBuilder()->renameTable($table, $newName);
  508. return $this->setSql($sql)->requireTableSchemaRefresh($table);
  509. }
  510. /**
  511. * Creates a SQL command for dropping a DB table.
  512. * @param string $table the table to be dropped. The name will be properly quoted by the method.
  513. * @return $this the command object itself
  514. */
  515. public function dropTable($table)
  516. {
  517. $sql = $this->db->getQueryBuilder()->dropTable($table);
  518. return $this->setSql($sql)->requireTableSchemaRefresh($table);
  519. }
  520. /**
  521. * Creates a SQL command for truncating a DB table.
  522. * @param string $table the table to be truncated. The name will be properly quoted by the method.
  523. * @return $this the command object itself
  524. */
  525. public function truncateTable($table)
  526. {
  527. $sql = $this->db->getQueryBuilder()->truncateTable($table);
  528. return $this->setSql($sql);
  529. }
  530. /**
  531. * Creates a SQL command for adding a new DB column.
  532. * @param string $table the table that the new column will be added to. The table name will be properly quoted by the method.
  533. * @param string $column the name of the new column. The name will be properly quoted by the method.
  534. * @param string $type the column type. [[\yii\db\QueryBuilder::getColumnType()]] will be called
  535. * to convert the give column type to the physical one. For example, `string` will be converted
  536. * as `varchar(255)`, and `string not null` becomes `varchar(255) not null`.
  537. * @return $this the command object itself
  538. */
  539. public function addColumn($table, $column, $type)
  540. {
  541. $sql = $this->db->getQueryBuilder()->addColumn($table, $column, $type);
  542. return $this->setSql($sql)->requireTableSchemaRefresh($table);
  543. }
  544. /**
  545. * Creates a SQL command for dropping a DB column.
  546. * @param string $table the table whose column is to be dropped. The name will be properly quoted by the method.
  547. * @param string $column the name of the column to be dropped. The name will be properly quoted by the method.
  548. * @return $this the command object itself
  549. */
  550. public function dropColumn($table, $column)
  551. {
  552. $sql = $this->db->getQueryBuilder()->dropColumn($table, $column);
  553. return $this->setSql($sql)->requireTableSchemaRefresh($table);
  554. }
  555. /**
  556. * Creates a SQL command for renaming a column.
  557. * @param string $table the table whose column is to be renamed. The name will be properly quoted by the method.
  558. * @param string $oldName the old name of the column. The name will be properly quoted by the method.
  559. * @param string $newName the new name of the column. The name will be properly quoted by the method.
  560. * @return $this the command object itself
  561. */
  562. public function renameColumn($table, $oldName, $newName)
  563. {
  564. $sql = $this->db->getQueryBuilder()->renameColumn($table, $oldName, $newName);
  565. return $this->setSql($sql)->requireTableSchemaRefresh($table);
  566. }
  567. /**
  568. * Creates a SQL command for changing the definition of a column.
  569. * @param string $table the table whose column is to be changed. The table name will be properly quoted by the method.
  570. * @param string $column the name of the column to be changed. The name will be properly quoted by the method.
  571. * @param string $type the column type. [[\yii\db\QueryBuilder::getColumnType()]] will be called
  572. * to convert the give column type to the physical one. For example, `string` will be converted
  573. * as `varchar(255)`, and `string not null` becomes `varchar(255) not null`.
  574. * @return $this the command object itself
  575. */
  576. public function alterColumn($table, $column, $type)
  577. {
  578. $sql = $this->db->getQueryBuilder()->alterColumn($table, $column, $type);
  579. return $this->setSql($sql)->requireTableSchemaRefresh($table);
  580. }
  581. /**
  582. * Creates a SQL command for adding a primary key constraint to an existing table.
  583. * The method will properly quote the table and column names.
  584. * @param string $name the name of the primary key constraint.
  585. * @param string $table the table that the primary key constraint will be added to.
  586. * @param string|array $columns comma separated string or array of columns that the primary key will consist of.
  587. * @return $this the command object itself.
  588. */
  589. public function addPrimaryKey($name, $table, $columns)
  590. {
  591. $sql = $this->db->getQueryBuilder()->addPrimaryKey($name, $table, $columns);
  592. return $this->setSql($sql)->requireTableSchemaRefresh($table);
  593. }
  594. /**
  595. * Creates a SQL command for removing a primary key constraint to an existing table.
  596. * @param string $name the name of the primary key constraint to be removed.
  597. * @param string $table the table that the primary key constraint will be removed from.
  598. * @return $this the command object itself
  599. */
  600. public function dropPrimaryKey($name, $table)
  601. {
  602. $sql = $this->db->getQueryBuilder()->dropPrimaryKey($name, $table);
  603. return $this->setSql($sql)->requireTableSchemaRefresh($table);
  604. }
  605. /**
  606. * Creates a SQL command for adding a foreign key constraint to an existing table.
  607. * The method will properly quote the table and column names.
  608. * @param string $name the name of the foreign key constraint.
  609. * @param string $table the table that the foreign key constraint will be added to.
  610. * @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.
  611. * @param string $refTable the table that the foreign key references to.
  612. * @param string|array $refColumns the name of the column that the foreign key references to. If there are multiple columns, separate them with commas.
  613. * @param string $delete the ON DELETE option. Most DBMS support these options: RESTRICT, CASCADE, NO ACTION, SET DEFAULT, SET NULL
  614. * @param string $update the ON UPDATE option. Most DBMS support these options: RESTRICT, CASCADE, NO ACTION, SET DEFAULT, SET NULL
  615. * @return $this the command object itself
  616. */
  617. public function addForeignKey($name, $table, $columns, $refTable, $refColumns, $delete = null, $update = null)
  618. {
  619. $sql = $this->db->getQueryBuilder()->addForeignKey($name, $table, $columns, $refTable, $refColumns, $delete, $update);
  620. return $this->setSql($sql);
  621. }
  622. /**
  623. * Creates a SQL command for dropping a foreign key constraint.
  624. * @param string $name the name of the foreign key constraint to be dropped. The name will be properly quoted by the method.
  625. * @param string $table the table whose foreign is to be dropped. The name will be properly quoted by the method.
  626. * @return $this the command object itself
  627. */
  628. public function dropForeignKey($name, $table)
  629. {
  630. $sql = $this->db->getQueryBuilder()->dropForeignKey($name, $table);
  631. return $this->setSql($sql);
  632. }
  633. /**
  634. * Creates a SQL command for creating a new index.
  635. * @param string $name the name of the index. The name will be properly quoted by the method.
  636. * @param string $table the table that the new index will be created for. The table name will be properly quoted by the method.
  637. * @param string|array $columns the column(s) that should be included in the index. If there are multiple columns, please separate them
  638. * by commas. The column names will be properly quoted by the method.
  639. * @param boolean $unique whether to add UNIQUE constraint on the created index.
  640. * @return $this the command object itself
  641. */
  642. public function createIndex($name, $table, $columns, $unique = false)
  643. {
  644. $sql = $this->db->getQueryBuilder()->createIndex($name, $table, $columns, $unique);
  645. return $this->setSql($sql);
  646. }
  647. /**
  648. * Creates a SQL command for dropping an index.
  649. * @param string $name the name of the index to be dropped. The name will be properly quoted by the method.
  650. * @param string $table the table whose index is to be dropped. The name will be properly quoted by the method.
  651. * @return $this the command object itself
  652. */
  653. public function dropIndex($name, $table)
  654. {
  655. $sql = $this->db->getQueryBuilder()->dropIndex($name, $table);
  656. return $this->setSql($sql);
  657. }
  658. /**
  659. * Creates a SQL command for resetting the sequence value of a table's primary key.
  660. * The sequence will be reset such that the primary key of the next new row inserted
  661. * will have the specified value or 1.
  662. * @param string $table the name of the table whose primary key sequence will be reset
  663. * @param mixed $value the value for the primary key of the next new row inserted. If this is not set,
  664. * the next new row's primary key will have a value 1.
  665. * @return $this the command object itself
  666. * @throws NotSupportedException if this is not supported by the underlying DBMS
  667. */
  668. public function resetSequence($table, $value = null)
  669. {
  670. $sql = $this->db->getQueryBuilder()->resetSequence($table, $value);
  671. return $this->setSql($sql);
  672. }
  673. /**
  674. * Builds a SQL command for enabling or disabling integrity check.
  675. * @param boolean $check whether to turn on or off the integrity check.
  676. * @param string $schema the schema name of the tables. Defaults to empty string, meaning the current
  677. * or default schema.
  678. * @param string $table the table name.
  679. * @return $this the command object itself
  680. * @throws NotSupportedException if this is not supported by the underlying DBMS
  681. */
  682. public function checkIntegrity($check = true, $schema = '', $table = '')
  683. {
  684. $sql = $this->db->getQueryBuilder()->checkIntegrity($check, $schema, $table);
  685. return $this->setSql($sql);
  686. }
  687. /**
  688. * Builds a SQL command for adding comment to column
  689. *
  690. * @param string $table the table whose column is to be commented. The table name will be properly quoted by the method.
  691. * @param string $column the name of the column to be commented. The column name will be properly quoted by the method.
  692. * @param string $comment the text of the comment to be added. The comment will be properly quoted by the method.
  693. * @return $this the command object itself
  694. * @since 2.0.8
  695. */
  696. public function addCommentOnColumn($table, $column, $comment)
  697. {
  698. $sql = $this->db->getQueryBuilder()->addCommentOnColumn($table, $column, $comment);
  699. return $this->setSql($sql);
  700. }
  701. /**
  702. * Builds a SQL command for adding comment to table
  703. *
  704. * @param string $table the table whose column is to be commented. The table name will be properly quoted by the method.
  705. * @param string $comment the text of the comment to be added. The comment will be properly quoted by the method.
  706. * @return $this the command object itself
  707. * @since 2.0.8
  708. */
  709. public function addCommentOnTable($table, $comment)
  710. {
  711. $sql = $this->db->getQueryBuilder()->addCommentOnTable($table, $comment);
  712. return $this->setSql($sql);
  713. }
  714. /**
  715. * Builds a SQL command for dropping comment from column
  716. *
  717. * @param string $table the table whose column is to be commented. The table name will be properly quoted by the method.
  718. * @param string $column the name of the column to be commented. The column name will be properly quoted by the method.
  719. * @return $this the command object itself
  720. * @since 2.0.8
  721. */
  722. public function dropCommentFromColumn($table, $column)
  723. {
  724. $sql = $this->db->getQueryBuilder()->dropCommentFromColumn($table, $column);
  725. return $this->setSql($sql);
  726. }
  727. /**
  728. * Builds a SQL command for dropping comment from table
  729. *
  730. * @param string $table the table whose column is to be commented. The table name will be properly quoted by the method.
  731. * @return $this the command object itself
  732. * @since 2.0.8
  733. */
  734. public function dropCommentFromTable($table)
  735. {
  736. $sql = $this->db->getQueryBuilder()->dropCommentFromTable($table);
  737. return $this->setSql($sql);
  738. }
  739. /**
  740. * Executes the SQL statement.
  741. * This method should only be used for executing non-query SQL statement, such as `INSERT`, `DELETE`, `UPDATE` SQLs.
  742. * No result set will be returned.
  743. * @return integer number of rows affected by the execution.
  744. * @throws Exception execution failed
  745. */
  746. public function execute()
  747. {
  748. $sql = $this->getSql();
  749. $rawSql = $this->getRawSql();
  750. Yii::info($rawSql, __METHOD__);
  751. if ($sql == '') {
  752. return 0;
  753. }
  754. $this->prepare(false);
  755. $token = $rawSql;
  756. try {
  757. Yii::beginProfile($token, __METHOD__);
  758. $this->pdoStatement->execute();
  759. $n = $this->pdoStatement->rowCount();
  760. Yii::endProfile($token, __METHOD__);
  761. $this->refreshTableSchema();
  762. return $n;
  763. } catch (\Exception $e) {
  764. Yii::endProfile($token, __METHOD__);
  765. throw $this->db->getSchema()->convertException($e, $rawSql);
  766. }
  767. }
  768. /**
  769. * Performs the actual DB query of a SQL statement.
  770. * @param string $method method of PDOStatement to be called
  771. * @param integer $fetchMode the result fetch mode. Please refer to [PHP manual](http://www.php.net/manual/en/function.PDOStatement-setFetchMode.php)
  772. * for valid fetch modes. If this parameter is null, the value set in [[fetchMode]] will be used.
  773. * @return mixed the method execution result
  774. * @throws Exception if the query causes any problem
  775. * @since 2.0.1 this method is protected (was private before).
  776. */
  777. protected function queryInternal($method, $fetchMode = null)
  778. {
  779. $rawSql = $this->getRawSql();
  780. Yii::info($rawSql, 'yii\db\Command::query');
  781. if ($method !== '') {
  782. $info = $this->db->getQueryCacheInfo($this->queryCacheDuration, $this->queryCacheDependency);
  783. if (is_array($info)) {
  784. /* @var $cache \yii\caching\Cache */
  785. $cache = $info[0];
  786. $cacheKey = [
  787. __CLASS__,
  788. $method,
  789. $fetchMode,
  790. $this->db->dsn,
  791. $this->db->username,
  792. $rawSql,
  793. ];
  794. $result = $cache->get($cacheKey);
  795. if (is_array($result) && isset($result[0])) {
  796. Yii::trace('Query result served from cache', 'yii\db\Command::query');
  797. return $result[0];
  798. }
  799. }
  800. }
  801. $this->prepare(true);
  802. $token = $rawSql;
  803. try {
  804. Yii::beginProfile($token, 'yii\db\Command::query');
  805. $this->pdoStatement->execute();
  806. if ($method === '') {
  807. $result = new DataReader($this);
  808. } else {
  809. if ($fetchMode === null) {
  810. $fetchMode = $this->fetchMode;
  811. }
  812. $result = call_user_func_array([$this->pdoStatement, $method], (array) $fetchMode);
  813. $this->pdoStatement->closeCursor();
  814. }
  815. Yii::endProfile($token, 'yii\db\Command::query');
  816. } catch (\Exception $e) {
  817. Yii::endProfile($token, 'yii\db\Command::query');
  818. throw $this->db->getSchema()->convertException($e, $rawSql);
  819. }
  820. if (isset($cache, $cacheKey, $info)) {
  821. $cache->set($cacheKey, [$result], $info[1], $info[2]);
  822. Yii::trace('Saved query result in cache', 'yii\db\Command::query');
  823. }
  824. return $result;
  825. }
  826. /**
  827. * Marks a specified table schema to be refreshed after command execution.
  828. * @param string $name name of the table, which schema should be refreshed.
  829. * @return $this this command instance
  830. * @since 2.0.6
  831. */
  832. protected function requireTableSchemaRefresh($name)
  833. {
  834. $this->_refreshTableName = $name;
  835. return $this;
  836. }
  837. /**
  838. * Refreshes table schema, which was marked by [[requireTableSchemaRefresh()]]
  839. * @since 2.0.6
  840. */
  841. protected function refreshTableSchema()
  842. {
  843. if ($this->_refreshTableName !== null) {
  844. $this->db->getSchema()->refreshTableSchema($this->_refreshTableName);
  845. }
  846. }
  847. }