Connection.php 20 KB

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