Command.php 50 KB

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