Command.php 51 KB

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