Command.php 51 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318
  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 https://secure.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 https://secure.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 https://secure.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](https://secure.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](https://secure.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](https://secure.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. $rawSql = $rawSql ?: $this->getRawSql();
  1029. $cacheKey = $this->getCacheKey($method, $fetchMode, $rawSql);
  1030. $result = $cache->get($cacheKey);
  1031. if (is_array($result) && isset($result[0])) {
  1032. Yii::debug('Query result served from cache', 'yii\db\Command::query');
  1033. return $result[0];
  1034. }
  1035. }
  1036. }
  1037. $this->prepare(true);
  1038. try {
  1039. $profile and Yii::beginProfile($rawSql, 'yii\db\Command::query');
  1040. $this->internalExecute($rawSql);
  1041. if ($method === '') {
  1042. $result = new DataReader($this);
  1043. } else {
  1044. if ($fetchMode === null) {
  1045. $fetchMode = $this->fetchMode;
  1046. }
  1047. $result = call_user_func_array([$this->pdoStatement, $method], (array) $fetchMode);
  1048. $this->pdoStatement->closeCursor();
  1049. }
  1050. $profile and Yii::endProfile($rawSql, 'yii\db\Command::query');
  1051. } catch (Exception $e) {
  1052. $profile and Yii::endProfile($rawSql, 'yii\db\Command::query');
  1053. throw $e;
  1054. }
  1055. if (isset($cache, $cacheKey, $info)) {
  1056. $cache->set($cacheKey, [$result], $info[1], $info[2]);
  1057. Yii::debug('Saved query result in cache', 'yii\db\Command::query');
  1058. }
  1059. return $result;
  1060. }
  1061. /**
  1062. * Returns the cache key for the query.
  1063. *
  1064. * @param string $method method of PDOStatement to be called
  1065. * @param int $fetchMode the result fetch mode. Please refer to [PHP manual](https://secure.php.net/manual/en/function.PDOStatement-setFetchMode.php)
  1066. * for valid fetch modes.
  1067. * @param string $rawSql the raw SQL with parameter values inserted into the corresponding placeholders
  1068. * @return array the cache key
  1069. * @since 2.0.16
  1070. */
  1071. protected function getCacheKey($method, $fetchMode, $rawSql)
  1072. {
  1073. return [
  1074. __CLASS__,
  1075. $method,
  1076. $fetchMode,
  1077. $this->db->dsn,
  1078. $this->db->username,
  1079. $rawSql,
  1080. ];
  1081. }
  1082. /**
  1083. * Marks a specified table schema to be refreshed after command execution.
  1084. * @param string $name name of the table, which schema should be refreshed.
  1085. * @return $this this command instance
  1086. * @since 2.0.6
  1087. */
  1088. protected function requireTableSchemaRefresh($name)
  1089. {
  1090. $this->_refreshTableName = $name;
  1091. return $this;
  1092. }
  1093. /**
  1094. * Refreshes table schema, which was marked by [[requireTableSchemaRefresh()]].
  1095. * @since 2.0.6
  1096. */
  1097. protected function refreshTableSchema()
  1098. {
  1099. if ($this->_refreshTableName !== null) {
  1100. $this->db->getSchema()->refreshTableSchema($this->_refreshTableName);
  1101. }
  1102. }
  1103. /**
  1104. * Marks the command to be executed in transaction.
  1105. * @param string|null $isolationLevel The isolation level to use for this transaction.
  1106. * See [[Transaction::begin()]] for details.
  1107. * @return $this this command instance.
  1108. * @since 2.0.14
  1109. */
  1110. protected function requireTransaction($isolationLevel = null)
  1111. {
  1112. $this->_isolationLevel = $isolationLevel;
  1113. return $this;
  1114. }
  1115. /**
  1116. * Sets a callable (e.g. anonymous function) that is called when [[Exception]] is thrown
  1117. * when executing the command. The signature of the callable should be:
  1118. *
  1119. * ```php
  1120. * function (\yii\db\Exception $e, $attempt)
  1121. * {
  1122. * // return true or false (whether to retry the command or rethrow $e)
  1123. * }
  1124. * ```
  1125. *
  1126. * The callable will recieve a database exception thrown and a current attempt
  1127. * (to execute the command) number starting from 1.
  1128. *
  1129. * @param callable $handler a PHP callback to handle database exceptions.
  1130. * @return $this this command instance.
  1131. * @since 2.0.14
  1132. */
  1133. protected function setRetryHandler(callable $handler)
  1134. {
  1135. $this->_retryHandler = $handler;
  1136. return $this;
  1137. }
  1138. /**
  1139. * Executes a prepared statement.
  1140. *
  1141. * It's a wrapper around [[\PDOStatement::execute()]] to support transactions
  1142. * and retry handlers.
  1143. *
  1144. * @param string|null $rawSql the rawSql if it has been created.
  1145. * @throws Exception if execution failed.
  1146. * @since 2.0.14
  1147. */
  1148. protected function internalExecute($rawSql)
  1149. {
  1150. $attempt = 0;
  1151. while (true) {
  1152. try {
  1153. if (
  1154. ++$attempt === 1
  1155. && $this->_isolationLevel !== false
  1156. && $this->db->getTransaction() === null
  1157. ) {
  1158. $this->db->transaction(function () use ($rawSql) {
  1159. $this->internalExecute($rawSql);
  1160. }, $this->_isolationLevel);
  1161. } else {
  1162. $this->pdoStatement->execute();
  1163. }
  1164. break;
  1165. } catch (\Exception $e) {
  1166. $rawSql = $rawSql ?: $this->getRawSql();
  1167. $e = $this->db->getSchema()->convertException($e, $rawSql);
  1168. if ($this->_retryHandler === null || !call_user_func($this->_retryHandler, $e, $attempt)) {
  1169. throw $e;
  1170. }
  1171. }
  1172. }
  1173. }
  1174. /**
  1175. * Resets command properties to their initial state.
  1176. *
  1177. * @since 2.0.13
  1178. */
  1179. protected function reset()
  1180. {
  1181. $this->_sql = null;
  1182. $this->_pendingParams = [];
  1183. $this->params = [];
  1184. $this->_refreshTableName = null;
  1185. $this->_isolationLevel = false;
  1186. $this->_retryHandler = null;
  1187. }
  1188. }