Connection.php 24 KB

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