Connection.php 24 KB

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