Command.php 51 KB

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