Connection.php 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014
  1. <?php
  2. /**
  3. * CakePHP(tm) : Rapid Development Framework (https://cakephp.org)
  4. * Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org)
  5. *
  6. * Licensed under The MIT License
  7. * For full copyright and license information, please see the LICENSE.txt
  8. * Redistributions of files must retain the above copyright notice.
  9. *
  10. * @copyright Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org)
  11. * @link https://cakephp.org CakePHP(tm) Project
  12. * @since 3.0.0
  13. * @license https://opensource.org/licenses/mit-license.php MIT License
  14. */
  15. namespace Cake\Database;
  16. use Cake\Core\App;
  17. use Cake\Core\Retry\CommandRetry;
  18. use Cake\Database\Exception\MissingConnectionException;
  19. use Cake\Database\Exception\MissingDriverException;
  20. use Cake\Database\Exception\MissingExtensionException;
  21. use Cake\Database\Exception\NestedTransactionRollbackException;
  22. use Cake\Database\Log\LoggedQuery;
  23. use Cake\Database\Log\LoggingStatement;
  24. use Cake\Database\Log\QueryLogger;
  25. use Cake\Database\Retry\ReconnectStrategy;
  26. use Cake\Database\Schema\CachedCollection;
  27. use Cake\Database\Schema\Collection as SchemaCollection;
  28. use Cake\Datasource\ConnectionInterface;
  29. use Cake\Log\Log;
  30. use Exception;
  31. /**
  32. * Represents a connection with a database server.
  33. */
  34. class Connection implements ConnectionInterface
  35. {
  36. use TypeConverterTrait;
  37. /**
  38. * Contains the configuration params for this connection.
  39. *
  40. * @var array
  41. */
  42. protected $_config;
  43. /**
  44. * Driver object, responsible for creating the real connection
  45. * and provide specific SQL dialect.
  46. *
  47. * @var \Cake\Database\Driver
  48. */
  49. protected $_driver;
  50. /**
  51. * Contains how many nested transactions have been started.
  52. *
  53. * @var int
  54. */
  55. protected $_transactionLevel = 0;
  56. /**
  57. * Whether a transaction is active in this connection.
  58. *
  59. * @var bool
  60. */
  61. protected $_transactionStarted = false;
  62. /**
  63. * Whether this connection can and should use savepoints for nested
  64. * transactions.
  65. *
  66. * @var bool
  67. */
  68. protected $_useSavePoints = false;
  69. /**
  70. * Whether to log queries generated during this connection.
  71. *
  72. * @var bool
  73. */
  74. protected $_logQueries = false;
  75. /**
  76. * Logger object instance.
  77. *
  78. * @var \Cake\Database\Log\QueryLogger|null
  79. */
  80. protected $_logger;
  81. /**
  82. * The schema collection object
  83. *
  84. * @var \Cake\Database\Schema\Collection|null
  85. */
  86. protected $_schemaCollection;
  87. /**
  88. * NestedTransactionRollbackException object instance, will be stored if
  89. * the rollback method is called in some nested transaction.
  90. *
  91. * @var \Cake\Database\Exception\NestedTransactionRollbackException|null
  92. */
  93. protected $nestedTransactionRollbackException;
  94. /**
  95. * Constructor.
  96. *
  97. * @param array $config configuration for connecting to database
  98. */
  99. public function __construct($config)
  100. {
  101. $this->_config = $config;
  102. $driver = '';
  103. if (!empty($config['driver'])) {
  104. $driver = $config['driver'];
  105. }
  106. $this->setDriver($driver, $config);
  107. if (!empty($config['log'])) {
  108. $this->enableQueryLogging($config['log']);
  109. }
  110. }
  111. /**
  112. * Destructor
  113. *
  114. * Disconnects the driver to release the connection.
  115. */
  116. public function __destruct()
  117. {
  118. if ($this->_transactionStarted && class_exists('Cake\Log\Log')) {
  119. Log::warning('The connection is going to be closed but there is an active transaction.');
  120. }
  121. }
  122. /**
  123. * {@inheritDoc}
  124. */
  125. public function config()
  126. {
  127. return $this->_config;
  128. }
  129. /**
  130. * {@inheritDoc}
  131. */
  132. public function configName()
  133. {
  134. if (empty($this->_config['name'])) {
  135. return '';
  136. }
  137. return $this->_config['name'];
  138. }
  139. /**
  140. * Sets the driver instance. If a string is passed it will be treated
  141. * as a class name and will be instantiated.
  142. *
  143. * @param \Cake\Database\Driver|string $driver The driver instance to use.
  144. * @param array $config Config for a new driver.
  145. * @throws \Cake\Database\Exception\MissingDriverException When a driver class is missing.
  146. * @throws \Cake\Database\Exception\MissingExtensionException When a driver's PHP extension is missing.
  147. * @return $this
  148. */
  149. public function setDriver($driver, $config = [])
  150. {
  151. if (is_string($driver)) {
  152. $className = App::className($driver, 'Database/Driver');
  153. if (!$className || !class_exists($className)) {
  154. throw new MissingDriverException(['driver' => $driver]);
  155. }
  156. $driver = new $className($config);
  157. }
  158. if (!$driver->enabled()) {
  159. throw new MissingExtensionException(['driver' => get_class($driver)]);
  160. }
  161. $this->_driver = $driver;
  162. return $this;
  163. }
  164. /**
  165. * Get the retry wrapper object that is allows recovery from server disconnects
  166. * while performing certain database actions, such as executing a query.
  167. *
  168. * @return \Cake\Core\Retry\CommandRetry The retry wrapper
  169. */
  170. public function getDisconnectRetry()
  171. {
  172. return new CommandRetry(new ReconnectStrategy($this));
  173. }
  174. /**
  175. * Gets the driver instance.
  176. *
  177. * @return \Cake\Database\Driver
  178. */
  179. public function getDriver()
  180. {
  181. return $this->_driver;
  182. }
  183. /**
  184. * Sets the driver instance. If a string is passed it will be treated
  185. * as a class name and will be instantiated.
  186. *
  187. * If no params are passed it will return the current driver instance.
  188. *
  189. * @deprecated 3.4.0 Use setDriver()/getDriver() instead.
  190. * @param \Cake\Database\Driver|string|null $driver The driver instance to use.
  191. * @param array $config Either config for a new driver or null.
  192. * @throws \Cake\Database\Exception\MissingDriverException When a driver class is missing.
  193. * @throws \Cake\Database\Exception\MissingExtensionException When a driver's PHP extension is missing.
  194. * @return \Cake\Database\Driver
  195. */
  196. public function driver($driver = null, $config = [])
  197. {
  198. deprecationWarning('Connection::driver() is deprecated. Use Connection::setDriver()/getDriver() instead.');
  199. if ($driver !== null) {
  200. $this->setDriver($driver, $config);
  201. }
  202. return $this->getDriver();
  203. }
  204. /**
  205. * Connects to the configured database.
  206. *
  207. * @throws \Cake\Database\Exception\MissingConnectionException if credentials are invalid.
  208. * @return bool true, if the connection was already established or the attempt was successful.
  209. */
  210. public function connect()
  211. {
  212. try {
  213. return $this->_driver->connect();
  214. } catch (Exception $e) {
  215. throw new MissingConnectionException(['reason' => $e->getMessage()], null, $e);
  216. }
  217. }
  218. /**
  219. * Disconnects from database server.
  220. *
  221. * @return void
  222. */
  223. public function disconnect()
  224. {
  225. $this->_driver->disconnect();
  226. }
  227. /**
  228. * Returns whether connection to database server was already established.
  229. *
  230. * @return bool
  231. */
  232. public function isConnected()
  233. {
  234. return $this->_driver->isConnected();
  235. }
  236. /**
  237. * Prepares a SQL statement to be executed.
  238. *
  239. * @param string|\Cake\Database\Query $sql The SQL to convert into a prepared statement.
  240. * @return \Cake\Database\StatementInterface
  241. */
  242. public function prepare($sql)
  243. {
  244. return $this->getDisconnectRetry()->run(function () use ($sql) {
  245. $statement = $this->_driver->prepare($sql);
  246. if ($this->_logQueries) {
  247. $statement = $this->_newLogger($statement);
  248. }
  249. return $statement;
  250. });
  251. }
  252. /**
  253. * Executes a query using $params for interpolating values and $types as a hint for each
  254. * those params.
  255. *
  256. * @param string $query SQL to be executed and interpolated with $params
  257. * @param array $params list or associative array of params to be interpolated in $query as values
  258. * @param array $types list or associative array of types to be used for casting values in query
  259. * @return \Cake\Database\StatementInterface executed statement
  260. */
  261. public function execute($query, array $params = [], array $types = [])
  262. {
  263. return $this->getDisconnectRetry()->run(function () use ($query, $params, $types) {
  264. if (!empty($params)) {
  265. $statement = $this->prepare($query);
  266. $statement->bind($params, $types);
  267. $statement->execute();
  268. } else {
  269. $statement = $this->query($query);
  270. }
  271. return $statement;
  272. });
  273. }
  274. /**
  275. * Compiles a Query object into a SQL string according to the dialect for this
  276. * connection's driver
  277. *
  278. * @param \Cake\Database\Query $query The query to be compiled
  279. * @param \Cake\Database\ValueBinder $generator The placeholder generator to use
  280. * @return string
  281. */
  282. public function compileQuery(Query $query, ValueBinder $generator)
  283. {
  284. return $this->getDriver()->compileQuery($query, $generator)[1];
  285. }
  286. /**
  287. * Executes the provided query after compiling it for the specific driver
  288. * dialect and returns the executed Statement object.
  289. *
  290. * @param \Cake\Database\Query $query The query to be executed
  291. * @return \Cake\Database\StatementInterface executed statement
  292. */
  293. public function run(Query $query)
  294. {
  295. return $this->getDisconnectRetry()->run(function () use ($query) {
  296. $statement = $this->prepare($query);
  297. $query->getValueBinder()->attachTo($statement);
  298. $statement->execute();
  299. return $statement;
  300. });
  301. }
  302. /**
  303. * Executes a SQL statement and returns the Statement object as result.
  304. *
  305. * @param string $sql The SQL query to execute.
  306. * @return \Cake\Database\StatementInterface
  307. */
  308. public function query($sql)
  309. {
  310. return $this->getDisconnectRetry()->run(function () use ($sql) {
  311. $statement = $this->prepare($sql);
  312. $statement->execute();
  313. return $statement;
  314. });
  315. }
  316. /**
  317. * Create a new Query instance for this connection.
  318. *
  319. * @return \Cake\Database\Query
  320. */
  321. public function newQuery()
  322. {
  323. return new Query($this);
  324. }
  325. /**
  326. * Sets a Schema\Collection object for this connection.
  327. *
  328. * @param \Cake\Database\Schema\Collection $collection The schema collection object
  329. * @return $this
  330. */
  331. public function setSchemaCollection(SchemaCollection $collection)
  332. {
  333. $this->_schemaCollection = $collection;
  334. return $this;
  335. }
  336. /**
  337. * Gets a Schema\Collection object for this connection.
  338. *
  339. * @return \Cake\Database\Schema\Collection
  340. */
  341. public function getSchemaCollection()
  342. {
  343. if ($this->_schemaCollection !== null) {
  344. return $this->_schemaCollection;
  345. }
  346. if (!empty($this->_config['cacheMetadata'])) {
  347. return $this->_schemaCollection = new CachedCollection($this, $this->_config['cacheMetadata']);
  348. }
  349. return $this->_schemaCollection = new SchemaCollection($this);
  350. }
  351. /**
  352. * Gets or sets a Schema\Collection object for this connection.
  353. *
  354. * @deprecated 3.4.0 Use setSchemaCollection()/getSchemaCollection()
  355. * @param \Cake\Database\Schema\Collection|null $collection The schema collection object
  356. * @return \Cake\Database\Schema\Collection
  357. */
  358. public function schemaCollection(SchemaCollection $collection = null)
  359. {
  360. deprecationWarning(
  361. 'Connection::schemaCollection() is deprecated. ' .
  362. 'Use Connection::setSchemaCollection()/getSchemaCollection() instead.'
  363. );
  364. if ($collection !== null) {
  365. $this->setSchemaCollection($collection);
  366. }
  367. return $this->getSchemaCollection();
  368. }
  369. /**
  370. * Executes an INSERT query on the specified table.
  371. *
  372. * @param string $table the table to insert values in
  373. * @param array $data values to be inserted
  374. * @param array $types list of associative array containing the types to be used for casting
  375. * @return \Cake\Database\StatementInterface
  376. */
  377. public function insert($table, array $data, array $types = [])
  378. {
  379. return $this->getDisconnectRetry()->run(function () use ($table, $data, $types) {
  380. $columns = array_keys($data);
  381. return $this->newQuery()->insert($columns, $types)
  382. ->into($table)
  383. ->values($data)
  384. ->execute();
  385. });
  386. }
  387. /**
  388. * Executes an UPDATE statement on the specified table.
  389. *
  390. * @param string $table the table to update rows from
  391. * @param array $data values to be updated
  392. * @param array $conditions conditions to be set for update statement
  393. * @param array $types list of associative array containing the types to be used for casting
  394. * @return \Cake\Database\StatementInterface
  395. */
  396. public function update($table, array $data, array $conditions = [], $types = [])
  397. {
  398. return $this->getDisconnectRetry()->run(function () use ($table, $data, $conditions, $types) {
  399. return $this->newQuery()->update($table)
  400. ->set($data, $types)
  401. ->where($conditions, $types)
  402. ->execute();
  403. });
  404. }
  405. /**
  406. * Executes a DELETE statement on the specified table.
  407. *
  408. * @param string $table the table to delete rows from
  409. * @param array $conditions conditions to be set for delete statement
  410. * @param array $types list of associative array containing the types to be used for casting
  411. * @return \Cake\Database\StatementInterface
  412. */
  413. public function delete($table, $conditions = [], $types = [])
  414. {
  415. return $this->getDisconnectRetry()->run(function () use ($table, $conditions, $types) {
  416. return $this->newQuery()->delete($table)
  417. ->where($conditions, $types)
  418. ->execute();
  419. });
  420. }
  421. /**
  422. * Starts a new transaction.
  423. *
  424. * @return void
  425. */
  426. public function begin()
  427. {
  428. if (!$this->_transactionStarted) {
  429. if ($this->_logQueries) {
  430. $this->log('BEGIN');
  431. }
  432. $this->getDisconnectRetry()->run(function () {
  433. $this->_driver->beginTransaction();
  434. });
  435. $this->_transactionLevel = 0;
  436. $this->_transactionStarted = true;
  437. $this->nestedTransactionRollbackException = null;
  438. return;
  439. }
  440. $this->_transactionLevel++;
  441. if ($this->isSavePointsEnabled()) {
  442. $this->createSavePoint((string)$this->_transactionLevel);
  443. }
  444. }
  445. /**
  446. * Commits current transaction.
  447. *
  448. * @return bool true on success, false otherwise
  449. */
  450. public function commit()
  451. {
  452. if (!$this->_transactionStarted) {
  453. return false;
  454. }
  455. if ($this->_transactionLevel === 0) {
  456. if ($this->wasNestedTransactionRolledback()) {
  457. $e = $this->nestedTransactionRollbackException;
  458. $this->nestedTransactionRollbackException = null;
  459. throw $e;
  460. }
  461. $this->_transactionStarted = false;
  462. $this->nestedTransactionRollbackException = null;
  463. if ($this->_logQueries) {
  464. $this->log('COMMIT');
  465. }
  466. return $this->_driver->commitTransaction();
  467. }
  468. if ($this->isSavePointsEnabled()) {
  469. $this->releaseSavePoint((string)$this->_transactionLevel);
  470. }
  471. $this->_transactionLevel--;
  472. return true;
  473. }
  474. /**
  475. * Rollback current transaction.
  476. *
  477. * @param bool|null $toBeginning Whether or not the transaction should be rolled back to the
  478. * beginning of it. Defaults to false if using savepoints, or true if not.
  479. * @return bool
  480. */
  481. public function rollback($toBeginning = null)
  482. {
  483. if (!$this->_transactionStarted) {
  484. return false;
  485. }
  486. $useSavePoint = $this->isSavePointsEnabled();
  487. if ($toBeginning === null) {
  488. $toBeginning = !$useSavePoint;
  489. }
  490. if ($this->_transactionLevel === 0 || $toBeginning) {
  491. $this->_transactionLevel = 0;
  492. $this->_transactionStarted = false;
  493. $this->nestedTransactionRollbackException = null;
  494. if ($this->_logQueries) {
  495. $this->log('ROLLBACK');
  496. }
  497. $this->_driver->rollbackTransaction();
  498. return true;
  499. }
  500. $savePoint = $this->_transactionLevel--;
  501. if ($useSavePoint) {
  502. $this->rollbackSavepoint($savePoint);
  503. } elseif ($this->nestedTransactionRollbackException === null) {
  504. $this->nestedTransactionRollbackException = new NestedTransactionRollbackException();
  505. }
  506. return true;
  507. }
  508. /**
  509. * Enables/disables the usage of savepoints, enables only if driver the allows it.
  510. *
  511. * If you are trying to enable this feature, make sure you check the return value of this
  512. * function to verify it was enabled successfully.
  513. *
  514. * ### Example:
  515. *
  516. * `$connection->enableSavePoints(true)` Returns true if drivers supports save points, false otherwise
  517. * `$connection->enableSavePoints(false)` Disables usage of savepoints and returns false
  518. *
  519. * @param bool $enable Whether or not save points should be used.
  520. * @return $this
  521. */
  522. public function enableSavePoints($enable)
  523. {
  524. if ($enable === false) {
  525. $this->_useSavePoints = false;
  526. } else {
  527. $this->_useSavePoints = $this->_driver->supportsSavePoints();
  528. }
  529. return $this;
  530. }
  531. /**
  532. * Disables the usage of savepoints.
  533. *
  534. * @return $this
  535. */
  536. public function disableSavePoints()
  537. {
  538. $this->_useSavePoints = false;
  539. return $this;
  540. }
  541. /**
  542. * Returns whether this connection is using savepoints for nested transactions
  543. *
  544. * @return bool true if enabled, false otherwise
  545. */
  546. public function isSavePointsEnabled()
  547. {
  548. return $this->_useSavePoints;
  549. }
  550. /**
  551. * Returns whether this connection is using savepoints for nested transactions
  552. * If a boolean is passed as argument it will enable/disable the usage of savepoints
  553. * only if driver the allows it.
  554. *
  555. * If you are trying to enable this feature, make sure you check the return value of this
  556. * function to verify it was enabled successfully.
  557. *
  558. * ### Example:
  559. *
  560. * `$connection->useSavePoints(true)` Returns true if drivers supports save points, false otherwise
  561. * `$connection->useSavePoints(false)` Disables usage of savepoints and returns false
  562. * `$connection->useSavePoints()` Returns current status
  563. *
  564. * @deprecated 3.4.0 Use enableSavePoints()/isSavePointsEnabled() instead.
  565. * @param bool|null $enable Whether or not save points should be used.
  566. * @return bool true if enabled, false otherwise
  567. */
  568. public function useSavePoints($enable = null)
  569. {
  570. deprecationWarning(
  571. 'Connection::useSavePoints() is deprecated. ' .
  572. 'Use Connection::enableSavePoints()/isSavePointsEnabled() instead.'
  573. );
  574. if ($enable !== null) {
  575. $this->enableSavePoints($enable);
  576. }
  577. return $this->isSavePointsEnabled();
  578. }
  579. /**
  580. * Creates a new save point for nested transactions.
  581. *
  582. * @param string $name The save point name.
  583. * @return void
  584. */
  585. public function createSavePoint($name)
  586. {
  587. $this->execute($this->_driver->savePointSQL($name))->closeCursor();
  588. }
  589. /**
  590. * Releases a save point by its name.
  591. *
  592. * @param string $name The save point name.
  593. * @return void
  594. */
  595. public function releaseSavePoint($name)
  596. {
  597. $this->execute($this->_driver->releaseSavePointSQL($name))->closeCursor();
  598. }
  599. /**
  600. * Rollback a save point by its name.
  601. *
  602. * @param string $name The save point name.
  603. * @return void
  604. */
  605. public function rollbackSavepoint($name)
  606. {
  607. $this->execute($this->_driver->rollbackSavePointSQL($name))->closeCursor();
  608. }
  609. /**
  610. * Run driver specific SQL to disable foreign key checks.
  611. *
  612. * @return void
  613. */
  614. public function disableForeignKeys()
  615. {
  616. $this->getDisconnectRetry()->run(function () {
  617. $this->execute($this->_driver->disableForeignKeySQL())->closeCursor();
  618. });
  619. }
  620. /**
  621. * Run driver specific SQL to enable foreign key checks.
  622. *
  623. * @return void
  624. */
  625. public function enableForeignKeys()
  626. {
  627. $this->getDisconnectRetry()->run(function () {
  628. $this->execute($this->_driver->enableForeignKeySQL())->closeCursor();
  629. });
  630. }
  631. /**
  632. * Returns whether the driver supports adding or dropping constraints
  633. * to already created tables.
  634. *
  635. * @return bool true if driver supports dynamic constraints
  636. */
  637. public function supportsDynamicConstraints()
  638. {
  639. return $this->_driver->supportsDynamicConstraints();
  640. }
  641. /**
  642. * {@inheritDoc}
  643. *
  644. * ### Example:
  645. *
  646. * ```
  647. * $connection->transactional(function ($connection) {
  648. * $connection->newQuery()->delete('users')->execute();
  649. * });
  650. * ```
  651. */
  652. public function transactional(callable $callback)
  653. {
  654. $this->begin();
  655. try {
  656. $result = $callback($this);
  657. } catch (Exception $e) {
  658. $this->rollback(false);
  659. throw $e;
  660. }
  661. if ($result === false) {
  662. $this->rollback(false);
  663. return false;
  664. }
  665. try {
  666. $this->commit();
  667. } catch (NestedTransactionRollbackException $e) {
  668. $this->rollback(false);
  669. throw $e;
  670. }
  671. return $result;
  672. }
  673. /**
  674. * Returns whether some nested transaction has been already rolled back.
  675. *
  676. * @return bool
  677. */
  678. protected function wasNestedTransactionRolledback()
  679. {
  680. return $this->nestedTransactionRollbackException instanceof NestedTransactionRollbackException;
  681. }
  682. /**
  683. * {@inheritDoc}
  684. *
  685. * ### Example:
  686. *
  687. * ```
  688. * $connection->disableConstraints(function ($connection) {
  689. * $connection->newQuery()->delete('users')->execute();
  690. * });
  691. * ```
  692. */
  693. public function disableConstraints(callable $callback)
  694. {
  695. return $this->getDisconnectRetry()->run(function () use ($callback) {
  696. $this->disableForeignKeys();
  697. try {
  698. $result = $callback($this);
  699. } catch (Exception $e) {
  700. $this->enableForeignKeys();
  701. throw $e;
  702. }
  703. $this->enableForeignKeys();
  704. return $result;
  705. });
  706. }
  707. /**
  708. * Checks if a transaction is running.
  709. *
  710. * @return bool True if a transaction is running else false.
  711. */
  712. public function inTransaction()
  713. {
  714. return $this->_transactionStarted;
  715. }
  716. /**
  717. * Quotes value to be used safely in database query.
  718. *
  719. * @param mixed $value The value to quote.
  720. * @param string|null $type Type to be used for determining kind of quoting to perform
  721. * @return string Quoted value
  722. */
  723. public function quote($value, $type = null)
  724. {
  725. list($value, $type) = $this->cast($value, $type);
  726. return $this->_driver->quote($value, $type);
  727. }
  728. /**
  729. * Checks if the driver supports quoting.
  730. *
  731. * @return bool
  732. */
  733. public function supportsQuoting()
  734. {
  735. return $this->_driver->supportsQuoting();
  736. }
  737. /**
  738. * Quotes a database identifier (a column name, table name, etc..) to
  739. * be used safely in queries without the risk of using reserved words.
  740. *
  741. * @param string $identifier The identifier to quote.
  742. * @return string
  743. */
  744. public function quoteIdentifier($identifier)
  745. {
  746. return $this->_driver->quoteIdentifier($identifier);
  747. }
  748. /**
  749. * Enables or disables metadata caching for this connection
  750. *
  751. * Changing this setting will not modify existing schema collections objects.
  752. *
  753. * @param bool|string $cache Either boolean false to disable metadata caching, or
  754. * true to use `_cake_model_` or the name of the cache config to use.
  755. * @return void
  756. */
  757. public function cacheMetadata($cache)
  758. {
  759. $this->_schemaCollection = null;
  760. $this->_config['cacheMetadata'] = $cache;
  761. }
  762. /**
  763. * {@inheritDoc}
  764. *
  765. * @deprecated 3.7.0 Use enableQueryLogging() and isQueryLoggingEnabled() instead.
  766. */
  767. public function logQueries($enable = null)
  768. {
  769. deprecationWarning(
  770. 'Connection::logQueries() is deprecated. ' .
  771. 'Use enableQueryLogging() and isQueryLoggingEnabled() instead.'
  772. );
  773. if ($enable === null) {
  774. return $this->_logQueries;
  775. }
  776. $this->_logQueries = $enable;
  777. }
  778. /**
  779. * Enable/disable query logging
  780. *
  781. * @param bool $value Enable/disable query logging
  782. * @return $this
  783. */
  784. public function enableQueryLogging($value)
  785. {
  786. $this->_logQueries = (bool)$value;
  787. return $this;
  788. }
  789. /**
  790. * Disable query logging
  791. *
  792. * @return $this
  793. */
  794. public function disableQueryLogging()
  795. {
  796. $this->_logQueries = false;
  797. return $this;
  798. }
  799. /**
  800. * Check if query logging is enabled.
  801. *
  802. * @return bool
  803. */
  804. public function isQueryLoggingEnabled()
  805. {
  806. return $this->_logQueries;
  807. }
  808. /**
  809. * {@inheritDoc}
  810. *
  811. * @deprecated 3.5.0 Use getLogger() and setLogger() instead.
  812. */
  813. public function logger($instance = null)
  814. {
  815. deprecationWarning(
  816. 'Connection::logger() is deprecated. ' .
  817. 'Use Connection::setLogger()/getLogger() instead.'
  818. );
  819. if ($instance === null) {
  820. return $this->getLogger();
  821. }
  822. $this->setLogger($instance);
  823. }
  824. /**
  825. * Sets a logger
  826. *
  827. * @param \Cake\Database\Log\QueryLogger $logger Logger object
  828. * @return $this
  829. */
  830. public function setLogger($logger)
  831. {
  832. $this->_logger = $logger;
  833. return $this;
  834. }
  835. /**
  836. * Gets the logger object
  837. *
  838. * @return \Cake\Database\Log\QueryLogger logger instance
  839. */
  840. public function getLogger()
  841. {
  842. if ($this->_logger === null) {
  843. $this->_logger = new QueryLogger();
  844. }
  845. return $this->_logger;
  846. }
  847. /**
  848. * Logs a Query string using the configured logger object.
  849. *
  850. * @param string $sql string to be logged
  851. * @return void
  852. */
  853. public function log($sql)
  854. {
  855. $query = new LoggedQuery();
  856. $query->query = $sql;
  857. $this->getLogger()->log($query);
  858. }
  859. /**
  860. * Returns a new statement object that will log the activity
  861. * for the passed original statement instance.
  862. *
  863. * @param \Cake\Database\StatementInterface $statement the instance to be decorated
  864. * @return \Cake\Database\Log\LoggingStatement
  865. */
  866. protected function _newLogger(StatementInterface $statement)
  867. {
  868. $log = new LoggingStatement($statement, $this->_driver);
  869. $log->setLogger($this->getLogger());
  870. return $log;
  871. }
  872. /**
  873. * Returns an array that can be used to describe the internal state of this
  874. * object.
  875. *
  876. * @return array
  877. */
  878. public function __debugInfo()
  879. {
  880. $secrets = [
  881. 'password' => '*****',
  882. 'username' => '*****',
  883. 'host' => '*****',
  884. 'database' => '*****',
  885. 'port' => '*****'
  886. ];
  887. $replace = array_intersect_key($secrets, $this->_config);
  888. $config = $replace + $this->_config;
  889. return [
  890. 'config' => $config,
  891. 'driver' => $this->_driver,
  892. 'transactionLevel' => $this->_transactionLevel,
  893. 'transactionStarted' => $this->_transactionStarted,
  894. 'useSavePoints' => $this->_useSavePoints,
  895. 'logQueries' => $this->_logQueries,
  896. 'logger' => $this->_logger
  897. ];
  898. }
  899. }