Command.php 51 KB

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