Connection.php 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535
  1. <?php
  2. /**
  3. * PHP Version 5.4
  4. *
  5. * CakePHP(tm) : Rapid Development Framework (http://cakephp.org)
  6. * Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
  7. *
  8. * Licensed under The MIT License
  9. * For full copyright and license information, please see the LICENSE.txt
  10. * Redistributions of files must retain the above copyright notice.
  11. *
  12. * @copyright Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
  13. * @link http://cakephp.org CakePHP(tm) Project
  14. * @since CakePHP(tm) v 3.0.0
  15. * @license MIT License (http://www.opensource.org/licenses/mit-license.php)
  16. */
  17. namespace Cake\Database;
  18. use Cake\Database\Exception\MissingConnectionException;
  19. use Cake\Database\Exception\MissingDriverException;
  20. use Cake\Database\Exception\MissingExtensionException;
  21. use Cake\Database\Log\LoggedQuery;
  22. use Cake\Database\Log\LoggingStatement;
  23. use Cake\Database\Log\QueryLogger;
  24. use Cake\Database\Query;
  25. /**
  26. * Represents a connection with a database server
  27. */
  28. class Connection {
  29. use TypeConverterTrait;
  30. /**
  31. * Contains the configuration params for this connection
  32. *
  33. * @var array
  34. */
  35. protected $_config;
  36. /**
  37. * Driver object, responsible for creating the real connection
  38. * and provide specific SQL dialect
  39. *
  40. * @var \Cake\Database\Driver
  41. */
  42. protected $_driver;
  43. /**
  44. * Contains how many nested transactions have been started
  45. *
  46. * @var int
  47. */
  48. protected $_transactionLevel = 0;
  49. /**
  50. * Whether a transaction is active in this connection
  51. *
  52. * @var int
  53. */
  54. protected $_transactionStarted = false;
  55. /**
  56. * Whether this connection can and should use savepoints for nested
  57. * transactions
  58. *
  59. * @var boolean
  60. */
  61. protected $_useSavePoints = false;
  62. /**
  63. * Whether to log queries generated during this connection
  64. *
  65. * @var boolean
  66. */
  67. protected $_logQueries = false;
  68. /**
  69. * Logger object instance
  70. *
  71. * @var QueryLogger
  72. */
  73. protected $_logger = null;
  74. /**
  75. * Constructor
  76. *
  77. * @param array $config configuration for connecting to database
  78. * @return self
  79. */
  80. public function __construct($config) {
  81. $this->_config = $config;
  82. if (!empty($config['datasource'])) {
  83. $this->driver($config['datasource'], $config);
  84. }
  85. if (!empty($config['log'])) {
  86. $this->logQueries($config['log']);
  87. }
  88. }
  89. /**
  90. * Destructor
  91. *
  92. * Disconnects the driver to release the connection.
  93. *
  94. * @return void
  95. */
  96. public function __destruct() {
  97. unset($this->_driver);
  98. }
  99. /**
  100. * Get the configuration data used to create the connection.
  101. *
  102. * @return array
  103. */
  104. public function config() {
  105. return $this->_config;
  106. }
  107. /**
  108. * Get the configuration name for this connection.
  109. *
  110. * @return string
  111. */
  112. public function configName() {
  113. if (empty($this->_config['name'])) {
  114. return null;
  115. }
  116. return $this->_config['name'];
  117. }
  118. /**
  119. * Sets the driver instance. If an string is passed it will be treated
  120. * as a class name and will be instantiated.
  121. *
  122. * If no params are passed it will return the current driver instance
  123. *
  124. * @param string|Driver $driver
  125. * @param array|null $config Either config for a new driver or null.
  126. * @throws Cake\Database\Exception\MissingDriverException When a driver class is missing.
  127. * @throws Cake\Database\Exception\MissingExtensionException When a driver's PHP extension is missing.
  128. * @return Driver
  129. */
  130. public function driver($driver = null, $config = null) {
  131. if ($driver === null) {
  132. return $this->_driver;
  133. }
  134. if (is_string($driver)) {
  135. if (!class_exists($driver)) {
  136. throw new MissingDriverException(['driver' => $driver]);
  137. }
  138. $driver = new $driver($config);
  139. }
  140. if (!$driver->enabled()) {
  141. throw new MissingExtensionException(['driver' => get_class($driver)]);
  142. }
  143. return $this->_driver = $driver;
  144. }
  145. /**
  146. * Connects to the configured database
  147. *
  148. * @throws Cake\Database\Exception\MissingConnectionException if credentials are invalid
  149. * @return boolean true on success or false if already connected.
  150. */
  151. public function connect() {
  152. try {
  153. $this->_driver->connect();
  154. return true;
  155. } catch(\Exception $e) {
  156. throw new MissingConnectionException(['reason' => $e->getMessage()]);
  157. }
  158. }
  159. /**
  160. * Disconnects from database server
  161. *
  162. * @return void
  163. */
  164. public function disconnect() {
  165. $this->_driver->disconnect();
  166. }
  167. /**
  168. * Returns whether connection to database server was already stablished
  169. *
  170. * @return boolean
  171. */
  172. public function isConnected() {
  173. return $this->_driver->isConnected();
  174. }
  175. /**
  176. * Prepares a sql statement to be executed
  177. *
  178. * @param string $sql
  179. * @return \Cake\Database\Statement
  180. */
  181. public function prepare($sql) {
  182. $statement = $this->_driver->prepare($sql);
  183. if ($this->_logQueries) {
  184. $statement = $this->_newLogger($statement);
  185. }
  186. return $statement;
  187. }
  188. /**
  189. * Executes a query using $params for interpolating values and $types as a hint for each
  190. * those params
  191. *
  192. * @param string $query SQL to be executed and interpolated with $params
  193. * @param array $params list or associative array of params to be interpolated in $query as values
  194. * @param array $types list or associative array of types to be used for casting values in query
  195. * @return \Cake\Database\Statement executed statement
  196. */
  197. public function execute($query, array $params = [], array $types = []) {
  198. if ($params) {
  199. $statement = $this->prepare($query);
  200. $statement->bind($params, $types);
  201. $statement->execute();
  202. } else {
  203. $statement = $this->query($query);
  204. }
  205. return $statement;
  206. }
  207. /**
  208. * Executes a SQL statement and returns the Statement object as result
  209. *
  210. * @param string $sql
  211. * @return \Cake\Database\Statement
  212. */
  213. public function query($sql) {
  214. $statement = $this->prepare($sql);
  215. $statement->execute();
  216. return $statement;
  217. }
  218. /**
  219. * Create a new Query instance for this connection.
  220. *
  221. * @return Query
  222. */
  223. public function newQuery() {
  224. return new Query($this);
  225. }
  226. /**
  227. * Get a Schema\Collection object for this connection.
  228. *
  229. * @return Cake\Database\Schema\Collection
  230. */
  231. public function schemaCollection() {
  232. return new \Cake\Database\Schema\Collection($this);
  233. }
  234. /**
  235. * Executes an INSERT query on the specified table
  236. *
  237. * @param string $table the table to update values in
  238. * @param array $data values to be inserted
  239. * @param array $types list of associative array containing the types to be used for casting
  240. * @return \Cake\Database\Statement
  241. */
  242. public function insert($table, array $data, array $types = []) {
  243. $columns = array_keys($data);
  244. return $this->newQuery()->insert($table, $columns, $types)
  245. ->values($data)
  246. ->execute();
  247. }
  248. /**
  249. * Executes an UPDATE statement on the specified table
  250. *
  251. * @param string $table the table to delete rows from
  252. * @param array $data values to be updated
  253. * @param array $conditions conditions to be set for update statement
  254. * @param array $types list of associative array containing the types to be used for casting
  255. * @return \Cake\Database\Statement
  256. */
  257. public function update($table, array $data, array $conditions = [], $types = []) {
  258. $columns = array_keys($data);
  259. return $this->newQuery()->update($table)
  260. ->set($data, $types)
  261. ->where($conditions, $types)
  262. ->execute();
  263. }
  264. /**
  265. * Executes a DELETE statement on the specified table
  266. *
  267. * @param string $table the table to delete rows from
  268. * @param array $conditions conditions to be set for delete statement
  269. * @param array $types list of associative array containing the types to be used for casting
  270. * @return \Cake\Database\Statement
  271. */
  272. public function delete($table, $conditions = [], $types = []) {
  273. return $this->newQuery()->delete($table)
  274. ->where($conditions, $types)
  275. ->execute();
  276. }
  277. /**
  278. * Starts a new transaction
  279. *
  280. * @return void
  281. */
  282. public function begin() {
  283. if (!$this->_transactionStarted) {
  284. if ($this->_logQueries) {
  285. $this->log('BEGIN');
  286. }
  287. $this->_driver->beginTransaction();
  288. $this->_transactionLevel = 0;
  289. $this->_transactionStarted = true;
  290. return;
  291. }
  292. $this->_transactionLevel++;
  293. if ($this->useSavePoints()) {
  294. $this->createSavePoint($this->_transactionLevel);
  295. }
  296. }
  297. /**
  298. * Commits current transaction
  299. *
  300. * @return boolean true on success, false otherwise
  301. */
  302. public function commit() {
  303. if (!$this->_transactionStarted) {
  304. return false;
  305. }
  306. if ($this->_transactionLevel === 0) {
  307. $this->_transactionStarted = false;
  308. if ($this->_logQueries) {
  309. $this->log('COMMIT');
  310. }
  311. return $this->_driver->commitTransaction();
  312. }
  313. if ($this->useSavePoints()) {
  314. $this->releaseSavePoint($this->_transactionLevel);
  315. }
  316. $this->_transactionLevel--;
  317. return true;
  318. }
  319. /**
  320. * Rollback current transaction
  321. *
  322. * @return boolean
  323. */
  324. public function rollback() {
  325. if (!$this->_transactionStarted) {
  326. return false;
  327. }
  328. $useSavePoint = $this->useSavePoints();
  329. if ($this->_transactionLevel === 0 || !$useSavePoint) {
  330. $this->_transactionLevel = 0;
  331. $this->_transactionStarted = false;
  332. if ($this->_logQueries) {
  333. $this->log('ROLLBACK');
  334. }
  335. $this->_driver->rollbackTransaction();
  336. return true;
  337. }
  338. if ($useSavePoint) {
  339. $this->rollbackSavepoint($this->_transactionLevel--);
  340. }
  341. return true;
  342. }
  343. /**
  344. * Returns whether this connection is using savepoints for nested transactions
  345. * If a boolean is passed as argument it will enable/disable the usage of savepoints
  346. * only if driver the allows it.
  347. *
  348. * If you are trying to enable this feature, make sure you check the return value of this
  349. * function to verify it was enabled successfully
  350. *
  351. * ## Example:
  352. *
  353. * `$connection->useSavePoints(true)` Returns true if drivers supports save points, false otherwise
  354. * `$connection->useSavePoints(false)` Disables usage of savepoints and returns false
  355. * `$connection->useSavePoints()` Returns current status
  356. *
  357. * @param boolean|null $enable
  358. * @return boolean true if enabled, false otherwise
  359. */
  360. public function useSavePoints($enable = null) {
  361. if ($enable === null) {
  362. return $this->_useSavePoints;
  363. }
  364. if ($enable === false) {
  365. return $this->_useSavePoints = false;
  366. }
  367. return $this->_useSavePoints = $this->_driver->supportsSavePoints();
  368. }
  369. /**
  370. * Creates a new save point for nested transactions
  371. *
  372. * @param string $name
  373. * @return void
  374. */
  375. public function createSavePoint($name) {
  376. $this->execute($this->_driver->savePointSQL($name));
  377. }
  378. /**
  379. * Releases a save point by its name
  380. *
  381. * @param string $name
  382. * @return void
  383. */
  384. public function releaseSavePoint($name) {
  385. $this->execute($this->_driver->releaseSavePointSQL($name));
  386. }
  387. /**
  388. * Rollback a save point by its name
  389. *
  390. * @param string $name
  391. * @return void
  392. */
  393. public function rollbackSavepoint($name) {
  394. $this->execute($this->_driver->rollbackSavePointSQL($name));
  395. }
  396. /**
  397. * Quotes value to be used safely in database query
  398. *
  399. * @param mixed $value
  400. * @param string $type Type to be used for determining kind of quoting to perform
  401. * @return mixed quoted value
  402. */
  403. public function quote($value, $type = null) {
  404. list($value, $type) = $this->cast($value, $type);
  405. return $this->_driver->quote($value, $type);
  406. }
  407. /**
  408. * Checks if the driver supports quoting
  409. *
  410. * @return boolean
  411. */
  412. public function supportsQuoting() {
  413. return $this->_driver->supportsQuoting();
  414. }
  415. /**
  416. * Quotes a database identifier (a column name, table name, etc..) to
  417. * be used safely in queries without the risk of using reserver words
  418. *
  419. * @param string $identifier
  420. * @return string
  421. */
  422. public function quoteIdentifier($identifier) {
  423. return $this->_driver->quoteIdentifier($identifier);
  424. }
  425. /**
  426. * Returns last id generated for a table or sequence in database
  427. *
  428. * @param string $table table name or sequence to get last insert value from
  429. * @return string|integer
  430. */
  431. public function lastInsertId($table) {
  432. return $this->_driver->lastInsertId($table);
  433. }
  434. /**
  435. * Enables or disables query logging for this connection.
  436. *
  437. * @param boolean $enable whether to turn logging on or disable it
  438. * @return void
  439. */
  440. public function logQueries($enable) {
  441. $this->_logQueries = $enable;
  442. }
  443. /**
  444. * Sets the logger object instance. When called with no arguments
  445. * it returns the currently setup logger instance
  446. *
  447. * @param object $instance logger object instance
  448. * @return object logger instance
  449. */
  450. public function logger($instance = null) {
  451. if ($instance === null) {
  452. if ($this->_logger === null) {
  453. $this->_logger = new QueryLogger;
  454. }
  455. return $this->_logger;
  456. }
  457. $this->_logger = $instance;
  458. }
  459. /**
  460. * Logs a Query string using the configured logger object
  461. *
  462. * @param string $sql string to be logged
  463. * @return void
  464. */
  465. public function log($sql) {
  466. $query = new LoggedQuery;
  467. $query->query = $sql;
  468. $this->logger()->log($query);
  469. }
  470. /**
  471. * Returns a new statement object that will log the activity
  472. * for the passed original statement instance.
  473. *
  474. * @param Statement $statement the instance to be decorated
  475. * @return Statement
  476. */
  477. protected function _newLogger($statement) {
  478. $log = new LoggingStatement($statement, $this->driver());
  479. $log->logger($this->logger());
  480. return $log;
  481. }
  482. }