Connection.php 24 KB

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