PageRenderTime 35ms CodeModel.GetById 15ms RepoModel.GetById 0ms app.codeStats 0ms

/web/api/lib/Cake/Model/Datasource/DboSource.php

https://github.com/dwija/ZoneMinder
PHP | 3544 lines | 2226 code | 378 blank | 940 comment | 550 complexity | f00b6053077554321772de44305a869c MD5 | raw file
Possible License(s): GPL-2.0
  1. <?php
  2. /**
  3. * Dbo Source
  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. * @package Cake.Model.Datasource
  15. * @since CakePHP(tm) v 0.10.0.1076
  16. * @license http://www.opensource.org/licenses/mit-license.php MIT License
  17. */
  18. App::uses('DataSource', 'Model/Datasource');
  19. App::uses('String', 'Utility');
  20. App::uses('View', 'View');
  21. /**
  22. * DboSource
  23. *
  24. * Creates DBO-descendant objects from a given db connection configuration
  25. *
  26. * @package Cake.Model.Datasource
  27. */
  28. class DboSource extends DataSource {
  29. /**
  30. * Description string for this Database Data Source.
  31. *
  32. * @var string
  33. */
  34. public $description = "Database Data Source";
  35. /**
  36. * index definition, standard cake, primary, index, unique
  37. *
  38. * @var array
  39. */
  40. public $index = array('PRI' => 'primary', 'MUL' => 'index', 'UNI' => 'unique');
  41. /**
  42. * Database keyword used to assign aliases to identifiers.
  43. *
  44. * @var string
  45. */
  46. public $alias = 'AS ';
  47. /**
  48. * Caches result from query parsing operations. Cached results for both DboSource::name() and
  49. * DboSource::conditions() will be stored here. Method caching uses `md5()`. If you have
  50. * problems with collisions, set DboSource::$cacheMethods to false.
  51. *
  52. * @var array
  53. */
  54. public static $methodCache = array();
  55. /**
  56. * Whether or not to cache the results of DboSource::name() and DboSource::conditions()
  57. * into the memory cache. Set to false to disable the use of the memory cache.
  58. *
  59. * @var boolean
  60. */
  61. public $cacheMethods = true;
  62. /**
  63. * Flag to support nested transactions. If it is set to false, you will be able to use
  64. * the transaction methods (begin/commit/rollback), but just the global transaction will
  65. * be executed.
  66. *
  67. * @var boolean
  68. */
  69. public $useNestedTransactions = false;
  70. /**
  71. * Print full query debug info?
  72. *
  73. * @var boolean
  74. */
  75. public $fullDebug = false;
  76. /**
  77. * String to hold how many rows were affected by the last SQL operation.
  78. *
  79. * @var string
  80. */
  81. public $affected = null;
  82. /**
  83. * Number of rows in current resultset
  84. *
  85. * @var integer
  86. */
  87. public $numRows = null;
  88. /**
  89. * Time the last query took
  90. *
  91. * @var integer
  92. */
  93. public $took = null;
  94. /**
  95. * Result
  96. *
  97. * @var array
  98. */
  99. protected $_result = null;
  100. /**
  101. * Queries count.
  102. *
  103. * @var integer
  104. */
  105. protected $_queriesCnt = 0;
  106. /**
  107. * Total duration of all queries.
  108. *
  109. * @var integer
  110. */
  111. protected $_queriesTime = null;
  112. /**
  113. * Log of queries executed by this DataSource
  114. *
  115. * @var array
  116. */
  117. protected $_queriesLog = array();
  118. /**
  119. * Maximum number of items in query log
  120. *
  121. * This is to prevent query log taking over too much memory.
  122. *
  123. * @var integer Maximum number of queries in the queries log.
  124. */
  125. protected $_queriesLogMax = 200;
  126. /**
  127. * Caches serialized results of executed queries
  128. *
  129. * @var array Cache of results from executed sql queries.
  130. */
  131. protected $_queryCache = array();
  132. /**
  133. * A reference to the physical connection of this DataSource
  134. *
  135. * @var array
  136. */
  137. protected $_connection = null;
  138. /**
  139. * The DataSource configuration key name
  140. *
  141. * @var string
  142. */
  143. public $configKeyName = null;
  144. /**
  145. * The starting character that this DataSource uses for quoted identifiers.
  146. *
  147. * @var string
  148. */
  149. public $startQuote = null;
  150. /**
  151. * The ending character that this DataSource uses for quoted identifiers.
  152. *
  153. * @var string
  154. */
  155. public $endQuote = null;
  156. /**
  157. * The set of valid SQL operations usable in a WHERE statement
  158. *
  159. * @var array
  160. */
  161. protected $_sqlOps = array('like', 'ilike', 'or', 'not', 'in', 'between', 'regexp', 'similar to');
  162. /**
  163. * Indicates the level of nested transactions
  164. *
  165. * @var integer
  166. */
  167. protected $_transactionNesting = 0;
  168. /**
  169. * Default fields that are used by the DBO
  170. *
  171. * @var array
  172. */
  173. protected $_queryDefaults = array(
  174. 'conditions' => array(),
  175. 'fields' => null,
  176. 'table' => null,
  177. 'alias' => null,
  178. 'order' => null,
  179. 'limit' => null,
  180. 'joins' => array(),
  181. 'group' => null,
  182. 'offset' => null
  183. );
  184. /**
  185. * Separator string for virtualField composition
  186. *
  187. * @var string
  188. */
  189. public $virtualFieldSeparator = '__';
  190. /**
  191. * List of table engine specific parameters used on table creating
  192. *
  193. * @var array
  194. */
  195. public $tableParameters = array();
  196. /**
  197. * List of engine specific additional field parameters used on table creating
  198. *
  199. * @var array
  200. */
  201. public $fieldParameters = array();
  202. /**
  203. * Indicates whether there was a change on the cached results on the methods of this class
  204. * This will be used for storing in a more persistent cache
  205. *
  206. * @var boolean
  207. */
  208. protected $_methodCacheChange = false;
  209. /**
  210. * Constructor
  211. *
  212. * @param array $config Array of configuration information for the Datasource.
  213. * @param boolean $autoConnect Whether or not the datasource should automatically connect.
  214. * @throws MissingConnectionException when a connection cannot be made.
  215. */
  216. public function __construct($config = null, $autoConnect = true) {
  217. if (!isset($config['prefix'])) {
  218. $config['prefix'] = '';
  219. }
  220. parent::__construct($config);
  221. $this->fullDebug = Configure::read('debug') > 1;
  222. if (!$this->enabled()) {
  223. throw new MissingConnectionException(array(
  224. 'class' => get_class($this),
  225. 'message' => __d('cake_dev', 'Selected driver is not enabled'),
  226. 'enabled' => false
  227. ));
  228. }
  229. if ($autoConnect) {
  230. $this->connect();
  231. }
  232. }
  233. /**
  234. * Reconnects to database server with optional new settings
  235. *
  236. * @param array $config An array defining the new configuration settings
  237. * @return boolean True on success, false on failure
  238. */
  239. public function reconnect($config = array()) {
  240. $this->disconnect();
  241. $this->setConfig($config);
  242. $this->_sources = null;
  243. return $this->connect();
  244. }
  245. /**
  246. * Disconnects from database.
  247. *
  248. * @return boolean Always true
  249. */
  250. public function disconnect() {
  251. if ($this->_result instanceof PDOStatement) {
  252. $this->_result->closeCursor();
  253. }
  254. unset($this->_connection);
  255. $this->connected = false;
  256. return true;
  257. }
  258. /**
  259. * Get the underlying connection object.
  260. *
  261. * @return PDO
  262. */
  263. public function getConnection() {
  264. return $this->_connection;
  265. }
  266. /**
  267. * Gets the version string of the database server
  268. *
  269. * @return string The database version
  270. */
  271. public function getVersion() {
  272. return $this->_connection->getAttribute(PDO::ATTR_SERVER_VERSION);
  273. }
  274. /**
  275. * Returns a quoted and escaped string of $data for use in an SQL statement.
  276. *
  277. * @param string $data String to be prepared for use in an SQL statement
  278. * @param string $column The column datatype into which this data will be inserted.
  279. * @return string Quoted and escaped data
  280. */
  281. public function value($data, $column = null) {
  282. if (is_array($data) && !empty($data)) {
  283. return array_map(
  284. array(&$this, 'value'),
  285. $data, array_fill(0, count($data), $column)
  286. );
  287. } elseif (is_object($data) && isset($data->type, $data->value)) {
  288. if ($data->type === 'identifier') {
  289. return $this->name($data->value);
  290. } elseif ($data->type === 'expression') {
  291. return $data->value;
  292. }
  293. } elseif (in_array($data, array('{$__cakeID__$}', '{$__cakeForeignKey__$}'), true)) {
  294. return $data;
  295. }
  296. if ($data === null || (is_array($data) && empty($data))) {
  297. return 'NULL';
  298. }
  299. if (empty($column)) {
  300. $column = $this->introspectType($data);
  301. }
  302. switch ($column) {
  303. case 'binary':
  304. return $this->_connection->quote($data, PDO::PARAM_LOB);
  305. case 'boolean':
  306. return $this->_connection->quote($this->boolean($data, true), PDO::PARAM_BOOL);
  307. case 'string':
  308. case 'text':
  309. return $this->_connection->quote($data, PDO::PARAM_STR);
  310. default:
  311. if ($data === '') {
  312. return 'NULL';
  313. }
  314. if (is_float($data)) {
  315. return str_replace(',', '.', strval($data));
  316. }
  317. if ((is_int($data) || $data === '0') || (
  318. is_numeric($data) && strpos($data, ',') === false &&
  319. $data[0] != '0' && strpos($data, 'e') === false)
  320. ) {
  321. return $data;
  322. }
  323. return $this->_connection->quote($data);
  324. }
  325. }
  326. /**
  327. * Returns an object to represent a database identifier in a query. Expression objects
  328. * are not sanitized or escaped.
  329. *
  330. * @param string $identifier A SQL expression to be used as an identifier
  331. * @return stdClass An object representing a database identifier to be used in a query
  332. */
  333. public function identifier($identifier) {
  334. $obj = new stdClass();
  335. $obj->type = 'identifier';
  336. $obj->value = $identifier;
  337. return $obj;
  338. }
  339. /**
  340. * Returns an object to represent a database expression in a query. Expression objects
  341. * are not sanitized or escaped.
  342. *
  343. * @param string $expression An arbitrary SQL expression to be inserted into a query.
  344. * @return stdClass An object representing a database expression to be used in a query
  345. */
  346. public function expression($expression) {
  347. $obj = new stdClass();
  348. $obj->type = 'expression';
  349. $obj->value = $expression;
  350. return $obj;
  351. }
  352. /**
  353. * Executes given SQL statement.
  354. *
  355. * @param string $sql SQL statement
  356. * @param array $params Additional options for the query.
  357. * @return boolean
  358. */
  359. public function rawQuery($sql, $params = array()) {
  360. $this->took = $this->numRows = false;
  361. return $this->execute($sql, $params);
  362. }
  363. /**
  364. * Queries the database with given SQL statement, and obtains some metadata about the result
  365. * (rows affected, timing, any errors, number of rows in resultset). The query is also logged.
  366. * If Configure::read('debug') is set, the log is shown all the time, else it is only shown on errors.
  367. *
  368. * ### Options
  369. *
  370. * - log - Whether or not the query should be logged to the memory log.
  371. *
  372. * @param string $sql SQL statement
  373. * @param array $options
  374. * @param array $params values to be bound to the query
  375. * @return mixed Resource or object representing the result set, or false on failure
  376. */
  377. public function execute($sql, $options = array(), $params = array()) {
  378. $options += array('log' => $this->fullDebug);
  379. $t = microtime(true);
  380. $this->_result = $this->_execute($sql, $params);
  381. if ($options['log']) {
  382. $this->took = round((microtime(true) - $t) * 1000, 0);
  383. $this->numRows = $this->affected = $this->lastAffected();
  384. $this->logQuery($sql, $params);
  385. }
  386. return $this->_result;
  387. }
  388. /**
  389. * Executes given SQL statement.
  390. *
  391. * @param string $sql SQL statement
  392. * @param array $params list of params to be bound to query
  393. * @param array $prepareOptions Options to be used in the prepare statement
  394. * @return mixed PDOStatement if query executes with no problem, true as the result of a successful, false on error
  395. * query returning no rows, such as a CREATE statement, false otherwise
  396. * @throws PDOException
  397. */
  398. protected function _execute($sql, $params = array(), $prepareOptions = array()) {
  399. $sql = trim($sql);
  400. if (preg_match('/^(?:CREATE|ALTER|DROP)\s+(?:TABLE|INDEX)/i', $sql)) {
  401. $statements = array_filter(explode(';', $sql));
  402. if (count($statements) > 1) {
  403. $result = array_map(array($this, '_execute'), $statements);
  404. return array_search(false, $result) === false;
  405. }
  406. }
  407. try {
  408. $query = $this->_connection->prepare($sql, $prepareOptions);
  409. $query->setFetchMode(PDO::FETCH_LAZY);
  410. if (!$query->execute($params)) {
  411. $this->_results = $query;
  412. $query->closeCursor();
  413. return false;
  414. }
  415. if (!$query->columnCount()) {
  416. $query->closeCursor();
  417. if (!$query->rowCount()) {
  418. return true;
  419. }
  420. }
  421. return $query;
  422. } catch (PDOException $e) {
  423. if (isset($query->queryString)) {
  424. $e->queryString = $query->queryString;
  425. } else {
  426. $e->queryString = $sql;
  427. }
  428. throw $e;
  429. }
  430. }
  431. /**
  432. * Returns a formatted error message from previous database operation.
  433. *
  434. * @param PDOStatement $query the query to extract the error from if any
  435. * @return string Error message with error number
  436. */
  437. public function lastError(PDOStatement $query = null) {
  438. if ($query) {
  439. $error = $query->errorInfo();
  440. } else {
  441. $error = $this->_connection->errorInfo();
  442. }
  443. if (empty($error[2])) {
  444. return null;
  445. }
  446. return $error[1] . ': ' . $error[2];
  447. }
  448. /**
  449. * Returns number of affected rows in previous database operation. If no previous operation exists,
  450. * this returns false.
  451. *
  452. * @param mixed $source
  453. * @return integer Number of affected rows
  454. */
  455. public function lastAffected($source = null) {
  456. if ($this->hasResult()) {
  457. return $this->_result->rowCount();
  458. }
  459. return 0;
  460. }
  461. /**
  462. * Returns number of rows in previous resultset. If no previous resultset exists,
  463. * this returns false.
  464. *
  465. * @param mixed $source Not used
  466. * @return integer Number of rows in resultset
  467. */
  468. public function lastNumRows($source = null) {
  469. return $this->lastAffected();
  470. }
  471. /**
  472. * DataSource Query abstraction
  473. *
  474. * @return resource Result resource identifier.
  475. */
  476. public function query() {
  477. $args = func_get_args();
  478. $fields = null;
  479. $order = null;
  480. $limit = null;
  481. $page = null;
  482. $recursive = null;
  483. if (count($args) === 1) {
  484. return $this->fetchAll($args[0]);
  485. } elseif (count($args) > 1 && (strpos($args[0], 'findBy') === 0 || strpos($args[0], 'findAllBy') === 0)) {
  486. $params = $args[1];
  487. if (substr($args[0], 0, 6) === 'findBy') {
  488. $all = false;
  489. $field = Inflector::underscore(substr($args[0], 6));
  490. } else {
  491. $all = true;
  492. $field = Inflector::underscore(substr($args[0], 9));
  493. }
  494. $or = (strpos($field, '_or_') !== false);
  495. if ($or) {
  496. $field = explode('_or_', $field);
  497. } else {
  498. $field = explode('_and_', $field);
  499. }
  500. $off = count($field) - 1;
  501. if (isset($params[1 + $off])) {
  502. $fields = $params[1 + $off];
  503. }
  504. if (isset($params[2 + $off])) {
  505. $order = $params[2 + $off];
  506. }
  507. if (!array_key_exists(0, $params)) {
  508. return false;
  509. }
  510. $c = 0;
  511. $conditions = array();
  512. foreach ($field as $f) {
  513. $conditions[$args[2]->alias . '.' . $f] = $params[$c++];
  514. }
  515. if ($or) {
  516. $conditions = array('OR' => $conditions);
  517. }
  518. if ($all) {
  519. if (isset($params[3 + $off])) {
  520. $limit = $params[3 + $off];
  521. }
  522. if (isset($params[4 + $off])) {
  523. $page = $params[4 + $off];
  524. }
  525. if (isset($params[5 + $off])) {
  526. $recursive = $params[5 + $off];
  527. }
  528. return $args[2]->find('all', compact('conditions', 'fields', 'order', 'limit', 'page', 'recursive'));
  529. }
  530. if (isset($params[3 + $off])) {
  531. $recursive = $params[3 + $off];
  532. }
  533. return $args[2]->find('first', compact('conditions', 'fields', 'order', 'recursive'));
  534. }
  535. if (isset($args[1]) && $args[1] === true) {
  536. return $this->fetchAll($args[0], true);
  537. } elseif (isset($args[1]) && !is_array($args[1])) {
  538. return $this->fetchAll($args[0], false);
  539. } elseif (isset($args[1]) && is_array($args[1])) {
  540. if (isset($args[2])) {
  541. $cache = $args[2];
  542. } else {
  543. $cache = true;
  544. }
  545. return $this->fetchAll($args[0], $args[1], array('cache' => $cache));
  546. }
  547. }
  548. /**
  549. * Returns a row from current resultset as an array
  550. *
  551. * @param string $sql Some SQL to be executed.
  552. * @return array The fetched row as an array
  553. */
  554. public function fetchRow($sql = null) {
  555. if (is_string($sql) && strlen($sql) > 5 && !$this->execute($sql)) {
  556. return null;
  557. }
  558. if ($this->hasResult()) {
  559. $this->resultSet($this->_result);
  560. $resultRow = $this->fetchResult();
  561. if (isset($resultRow[0])) {
  562. $this->fetchVirtualField($resultRow);
  563. }
  564. return $resultRow;
  565. }
  566. return null;
  567. }
  568. /**
  569. * Returns an array of all result rows for a given SQL query.
  570. *
  571. * Returns false if no rows matched.
  572. *
  573. * ### Options
  574. *
  575. * - `cache` - Returns the cached version of the query, if exists and stores the result in cache.
  576. * This is a non-persistent cache, and only lasts for a single request. This option
  577. * defaults to true. If you are directly calling this method, you can disable caching
  578. * by setting $options to `false`
  579. *
  580. * @param string $sql SQL statement
  581. * @param array|boolean $params Either parameters to be bound as values for the SQL statement,
  582. * or a boolean to control query caching.
  583. * @param array $options additional options for the query.
  584. * @return boolean|array Array of resultset rows, or false if no rows matched
  585. */
  586. public function fetchAll($sql, $params = array(), $options = array()) {
  587. if (is_string($options)) {
  588. $options = array('modelName' => $options);
  589. }
  590. if (is_bool($params)) {
  591. $options['cache'] = $params;
  592. $params = array();
  593. }
  594. $options += array('cache' => true);
  595. $cache = $options['cache'];
  596. if ($cache && ($cached = $this->getQueryCache($sql, $params)) !== false) {
  597. return $cached;
  598. }
  599. $result = $this->execute($sql, array(), $params);
  600. if ($result) {
  601. $out = array();
  602. if ($this->hasResult()) {
  603. $first = $this->fetchRow();
  604. if ($first) {
  605. $out[] = $first;
  606. }
  607. while ($item = $this->fetchResult()) {
  608. if (isset($item[0])) {
  609. $this->fetchVirtualField($item);
  610. }
  611. $out[] = $item;
  612. }
  613. }
  614. if (!is_bool($result) && $cache) {
  615. $this->_writeQueryCache($sql, $out, $params);
  616. }
  617. if (empty($out) && is_bool($this->_result)) {
  618. return $this->_result;
  619. }
  620. return $out;
  621. }
  622. return false;
  623. }
  624. /**
  625. * Fetches the next row from the current result set
  626. *
  627. * @return boolean
  628. */
  629. public function fetchResult() {
  630. return false;
  631. }
  632. /**
  633. * Modifies $result array to place virtual fields in model entry where they belongs to
  634. *
  635. * @param array $result Reference to the fetched row
  636. * @return void
  637. */
  638. public function fetchVirtualField(&$result) {
  639. if (isset($result[0]) && is_array($result[0])) {
  640. foreach ($result[0] as $field => $value) {
  641. if (strpos($field, $this->virtualFieldSeparator) === false) {
  642. continue;
  643. }
  644. list($alias, $virtual) = explode($this->virtualFieldSeparator, $field);
  645. if (!ClassRegistry::isKeySet($alias)) {
  646. return;
  647. }
  648. $Model = ClassRegistry::getObject($alias);
  649. if ($Model->isVirtualField($virtual)) {
  650. $result[$alias][$virtual] = $value;
  651. unset($result[0][$field]);
  652. }
  653. }
  654. if (empty($result[0])) {
  655. unset($result[0]);
  656. }
  657. }
  658. }
  659. /**
  660. * Returns a single field of the first of query results for a given SQL query, or false if empty.
  661. *
  662. * @param string $name Name of the field
  663. * @param string $sql SQL query
  664. * @return mixed Value of field read.
  665. */
  666. public function field($name, $sql) {
  667. $data = $this->fetchRow($sql);
  668. if (empty($data[$name])) {
  669. return false;
  670. }
  671. return $data[$name];
  672. }
  673. /**
  674. * Empties the method caches.
  675. * These caches are used by DboSource::name() and DboSource::conditions()
  676. *
  677. * @return void
  678. */
  679. public function flushMethodCache() {
  680. $this->_methodCacheChange = true;
  681. self::$methodCache = array();
  682. }
  683. /**
  684. * Cache a value into the methodCaches. Will respect the value of DboSource::$cacheMethods.
  685. * Will retrieve a value from the cache if $value is null.
  686. *
  687. * If caching is disabled and a write is attempted, the $value will be returned.
  688. * A read will either return the value or null.
  689. *
  690. * @param string $method Name of the method being cached.
  691. * @param string $key The key name for the cache operation.
  692. * @param mixed $value The value to cache into memory.
  693. * @return mixed Either null on failure, or the value if its set.
  694. */
  695. public function cacheMethod($method, $key, $value = null) {
  696. if ($this->cacheMethods === false) {
  697. return $value;
  698. }
  699. if (!$this->_methodCacheChange && empty(self::$methodCache)) {
  700. self::$methodCache = Cache::read('method_cache', '_cake_core_');
  701. }
  702. if ($value === null) {
  703. return (isset(self::$methodCache[$method][$key])) ? self::$methodCache[$method][$key] : null;
  704. }
  705. $this->_methodCacheChange = true;
  706. return self::$methodCache[$method][$key] = $value;
  707. }
  708. /**
  709. * Returns a quoted name of $data for use in an SQL statement.
  710. * Strips fields out of SQL functions before quoting.
  711. *
  712. * Results of this method are stored in a memory cache. This improves performance, but
  713. * because the method uses a hashing algorithm it can have collisions.
  714. * Setting DboSource::$cacheMethods to false will disable the memory cache.
  715. *
  716. * @param mixed $data Either a string with a column to quote. An array of columns to quote or an
  717. * object from DboSource::expression() or DboSource::identifier()
  718. * @return string SQL field
  719. */
  720. public function name($data) {
  721. if (is_object($data) && isset($data->type)) {
  722. return $data->value;
  723. }
  724. if ($data === '*') {
  725. return '*';
  726. }
  727. if (is_array($data)) {
  728. foreach ($data as $i => $dataItem) {
  729. $data[$i] = $this->name($dataItem);
  730. }
  731. return $data;
  732. }
  733. $cacheKey = md5($this->startQuote . $data . $this->endQuote);
  734. if ($return = $this->cacheMethod(__FUNCTION__, $cacheKey)) {
  735. return $return;
  736. }
  737. $data = trim($data);
  738. if (preg_match('/^[\w-]+(?:\.[^ \*]*)*$/', $data)) { // string, string.string
  739. if (strpos($data, '.') === false) { // string
  740. return $this->cacheMethod(__FUNCTION__, $cacheKey, $this->startQuote . $data . $this->endQuote);
  741. }
  742. $items = explode('.', $data);
  743. return $this->cacheMethod(__FUNCTION__, $cacheKey,
  744. $this->startQuote . implode($this->endQuote . '.' . $this->startQuote, $items) . $this->endQuote
  745. );
  746. }
  747. if (preg_match('/^[\w-]+\.\*$/', $data)) { // string.*
  748. return $this->cacheMethod(__FUNCTION__, $cacheKey,
  749. $this->startQuote . str_replace('.*', $this->endQuote . '.*', $data)
  750. );
  751. }
  752. if (preg_match('/^([\w-]+)\((.*)\)$/', $data, $matches)) { // Functions
  753. return $this->cacheMethod(__FUNCTION__, $cacheKey,
  754. $matches[1] . '(' . $this->name($matches[2]) . ')'
  755. );
  756. }
  757. if (
  758. preg_match('/^([\w-]+(\.[\w-]+|\(.*\))*)\s+' . preg_quote($this->alias) . '\s*([\w-]+)$/i', $data, $matches
  759. )) {
  760. return $this->cacheMethod(
  761. __FUNCTION__, $cacheKey,
  762. preg_replace(
  763. '/\s{2,}/', ' ', $this->name($matches[1]) . ' ' . $this->alias . ' ' . $this->name($matches[3])
  764. )
  765. );
  766. }
  767. if (preg_match('/^[\w-_\s]*[\w-_]+/', $data)) {
  768. return $this->cacheMethod(__FUNCTION__, $cacheKey, $this->startQuote . $data . $this->endQuote);
  769. }
  770. return $this->cacheMethod(__FUNCTION__, $cacheKey, $data);
  771. }
  772. /**
  773. * Checks if the source is connected to the database.
  774. *
  775. * @return boolean True if the database is connected, else false
  776. */
  777. public function isConnected() {
  778. return $this->connected;
  779. }
  780. /**
  781. * Checks if the result is valid
  782. *
  783. * @return boolean True if the result is valid else false
  784. */
  785. public function hasResult() {
  786. return $this->_result instanceof PDOStatement;
  787. }
  788. /**
  789. * Get the query log as an array.
  790. *
  791. * @param boolean $sorted Get the queries sorted by time taken, defaults to false.
  792. * @param boolean $clear If True the existing log will cleared.
  793. * @return array Array of queries run as an array
  794. */
  795. public function getLog($sorted = false, $clear = true) {
  796. if ($sorted) {
  797. $log = sortByKey($this->_queriesLog, 'took', 'desc', SORT_NUMERIC);
  798. } else {
  799. $log = $this->_queriesLog;
  800. }
  801. if ($clear) {
  802. $this->_queriesLog = array();
  803. }
  804. return array('log' => $log, 'count' => $this->_queriesCnt, 'time' => $this->_queriesTime);
  805. }
  806. /**
  807. * Outputs the contents of the queries log. If in a non-CLI environment the sql_log element
  808. * will be rendered and output. If in a CLI environment, a plain text log is generated.
  809. *
  810. * @param boolean $sorted Get the queries sorted by time taken, defaults to false.
  811. * @return void
  812. */
  813. public function showLog($sorted = false) {
  814. $log = $this->getLog($sorted, false);
  815. if (empty($log['log'])) {
  816. return;
  817. }
  818. if (PHP_SAPI !== 'cli') {
  819. $controller = null;
  820. $View = new View($controller, false);
  821. $View->set('sqlLogs', array($this->configKeyName => $log));
  822. echo $View->element('sql_dump', array('_forced_from_dbo_' => true));
  823. } else {
  824. foreach ($log['log'] as $k => $i) {
  825. print (($k + 1) . ". {$i['query']}\n");
  826. }
  827. }
  828. }
  829. /**
  830. * Log given SQL query.
  831. *
  832. * @param string $sql SQL statement
  833. * @param array $params Values binded to the query (prepared statements)
  834. * @return void
  835. */
  836. public function logQuery($sql, $params = array()) {
  837. $this->_queriesCnt++;
  838. $this->_queriesTime += $this->took;
  839. $this->_queriesLog[] = array(
  840. 'query' => $sql,
  841. 'params' => $params,
  842. 'affected' => $this->affected,
  843. 'numRows' => $this->numRows,
  844. 'took' => $this->took
  845. );
  846. if (count($this->_queriesLog) > $this->_queriesLogMax) {
  847. array_shift($this->_queriesLog);
  848. }
  849. }
  850. /**
  851. * Gets full table name including prefix
  852. *
  853. * @param Model|string $model Either a Model object or a string table name.
  854. * @param boolean $quote Whether you want the table name quoted.
  855. * @param boolean $schema Whether you want the schema name included.
  856. * @return string Full quoted table name
  857. */
  858. public function fullTableName($model, $quote = true, $schema = true) {
  859. if (is_object($model)) {
  860. $schemaName = $model->schemaName;
  861. $table = $model->tablePrefix . $model->table;
  862. } elseif (!empty($this->config['prefix']) && strpos($model, $this->config['prefix']) !== 0) {
  863. $table = $this->config['prefix'] . strval($model);
  864. } else {
  865. $table = strval($model);
  866. }
  867. if ($schema && !isset($schemaName)) {
  868. $schemaName = $this->getSchemaName();
  869. }
  870. if ($quote) {
  871. if ($schema && !empty($schemaName)) {
  872. if (strstr($table, '.') === false) {
  873. return $this->name($schemaName) . '.' . $this->name($table);
  874. }
  875. }
  876. return $this->name($table);
  877. }
  878. if ($schema && !empty($schemaName)) {
  879. if (strstr($table, '.') === false) {
  880. return $schemaName . '.' . $table;
  881. }
  882. }
  883. return $table;
  884. }
  885. /**
  886. * The "C" in CRUD
  887. *
  888. * Creates new records in the database.
  889. *
  890. * @param Model $Model Model object that the record is for.
  891. * @param array $fields An array of field names to insert. If null, $Model->data will be
  892. * used to generate field names.
  893. * @param array $values An array of values with keys matching the fields. If null, $Model->data will
  894. * be used to generate values.
  895. * @return boolean Success
  896. */
  897. public function create(Model $Model, $fields = null, $values = null) {
  898. $id = null;
  899. if (!$fields) {
  900. unset($fields, $values);
  901. $fields = array_keys($Model->data);
  902. $values = array_values($Model->data);
  903. }
  904. $count = count($fields);
  905. for ($i = 0; $i < $count; $i++) {
  906. $valueInsert[] = $this->value($values[$i], $Model->getColumnType($fields[$i]));
  907. $fieldInsert[] = $this->name($fields[$i]);
  908. if ($fields[$i] == $Model->primaryKey) {
  909. $id = $values[$i];
  910. }
  911. }
  912. $query = array(
  913. 'table' => $this->fullTableName($Model),
  914. 'fields' => implode(', ', $fieldInsert),
  915. 'values' => implode(', ', $valueInsert)
  916. );
  917. if ($this->execute($this->renderStatement('create', $query))) {
  918. if (empty($id)) {
  919. $id = $this->lastInsertId($this->fullTableName($Model, false, false), $Model->primaryKey);
  920. }
  921. $Model->setInsertID($id);
  922. $Model->id = $id;
  923. return true;
  924. }
  925. $Model->onError();
  926. return false;
  927. }
  928. /**
  929. * The "R" in CRUD
  930. *
  931. * Reads record(s) from the database.
  932. *
  933. * @param Model $Model A Model object that the query is for.
  934. * @param array $queryData An array of queryData information containing keys similar to Model::find().
  935. * @param integer $recursive Number of levels of association
  936. * @return mixed boolean false on error/failure. An array of results on success.
  937. */
  938. public function read(Model $Model, $queryData = array(), $recursive = null) {
  939. $queryData = $this->_scrubQueryData($queryData);
  940. $array = array('callbacks' => $queryData['callbacks']);
  941. if ($recursive === null && isset($queryData['recursive'])) {
  942. $recursive = $queryData['recursive'];
  943. }
  944. if ($recursive !== null) {
  945. $modelRecursive = $Model->recursive;
  946. $Model->recursive = $recursive;
  947. }
  948. if (!empty($queryData['fields'])) {
  949. $noAssocFields = true;
  950. $queryData['fields'] = $this->fields($Model, null, $queryData['fields']);
  951. } else {
  952. $noAssocFields = false;
  953. $queryData['fields'] = $this->fields($Model);
  954. }
  955. if ($Model->recursive === -1) {
  956. // Primary model data only, no joins.
  957. $associations = array();
  958. } else {
  959. $associations = $Model->associations();
  960. if ($Model->recursive === 0) {
  961. // Primary model data and its domain.
  962. unset($associations[2], $associations[3]);
  963. }
  964. }
  965. $originalJoins = $queryData['joins'];
  966. $queryData['joins'] = array();
  967. // Generate hasOne and belongsTo associations inside $queryData
  968. $linkedModels = array();
  969. foreach ($associations as $type) {
  970. if ($type !== 'hasOne' && $type !== 'belongsTo') {
  971. continue;
  972. }
  973. foreach ($Model->{$type} as $assoc => $assocData) {
  974. $LinkModel = $Model->{$assoc};
  975. if ($Model->useDbConfig !== $LinkModel->useDbConfig) {
  976. continue;
  977. }
  978. if ($noAssocFields) {
  979. $assocData['fields'] = false;
  980. }
  981. $external = isset($assocData['external']);
  982. if ($this->generateAssociationQuery($Model, $LinkModel, $type, $assoc, $assocData, $queryData, $external) === true) {
  983. $linkedModels[$type . '/' . $assoc] = true;
  984. }
  985. }
  986. }
  987. if (!empty($originalJoins)) {
  988. $queryData['joins'] = array_merge($queryData['joins'], $originalJoins);
  989. }
  990. // Build SQL statement with the primary model, plus hasOne and belongsTo associations
  991. $query = $this->buildAssociationQuery($Model, $queryData);
  992. $resultSet = $this->fetchAll($query, $Model->cacheQueries);
  993. unset($query);
  994. if ($resultSet === false) {
  995. $Model->onError();
  996. return false;
  997. }
  998. $filtered = array();
  999. // Filter hasOne and belongsTo associations
  1000. if ($queryData['callbacks'] === true || $queryData['callbacks'] === 'after') {
  1001. $filtered = $this->_filterResults($resultSet, $Model);
  1002. }
  1003. // Deep associations
  1004. if ($Model->recursive > -1) {
  1005. $joined = array();
  1006. if (isset($queryData['joins'][0]['alias'])) {
  1007. $joined[$Model->alias] = (array)Hash::extract($queryData['joins'], '{n}.alias');
  1008. }
  1009. foreach ($associations as $type) {
  1010. foreach ($Model->{$type} as $assoc => $assocData) {
  1011. $LinkModel = $Model->{$assoc};
  1012. if (!isset($linkedModels[$type . '/' . $assoc])) {
  1013. $db = $Model->useDbConfig === $LinkModel->useDbConfig ? $this : $LinkModel->getDataSource();
  1014. } elseif ($Model->recursive > 1) {
  1015. $db = $this;
  1016. }
  1017. if (isset($db) && method_exists($db, 'queryAssociation')) {
  1018. $stack = array($assoc);
  1019. $stack['_joined'] = $joined;
  1020. $db->queryAssociation($Model, $LinkModel, $type, $assoc, $assocData, $array, true, $resultSet, $Model->recursive - 1, $stack);
  1021. if ($type === 'hasMany' || $type === 'hasAndBelongsToMany') {
  1022. $filtered[] = $assoc;
  1023. }
  1024. }
  1025. }
  1026. }
  1027. if ($queryData['callbacks'] === true || $queryData['callbacks'] === 'after') {
  1028. $this->_filterResults($resultSet, $Model, $filtered);
  1029. }
  1030. }
  1031. if ($recursive !== null) {
  1032. $Model->recursive = $modelRecursive;
  1033. }
  1034. return $resultSet;
  1035. }
  1036. /**
  1037. * Passes association results through afterFind filters of the corresponding model.
  1038. *
  1039. * The primary model is always excluded, because the filtering is later done by Model::_filterResults().
  1040. *
  1041. * @param array $resultSet Reference of resultset to be filtered.
  1042. * @param Model $Model Instance of model to operate against.
  1043. * @param array $filtered List of classes already filtered, to be skipped.
  1044. * @return array Array of results that have been filtered through $Model->afterFind.
  1045. */
  1046. protected function _filterResults(&$resultSet, Model $Model, $filtered = array()) {
  1047. if (!is_array($resultSet)) {
  1048. return array();
  1049. }
  1050. $current = reset($resultSet);
  1051. if (!is_array($current)) {
  1052. return array();
  1053. }
  1054. $keys = array_diff(array_keys($current), $filtered, array($Model->alias));
  1055. $filtering = array();
  1056. foreach ($keys as $className) {
  1057. if (!isset($Model->{$className}) || !is_object($Model->{$className})) {
  1058. continue;
  1059. }
  1060. $LinkedModel = $Model->{$className};
  1061. $filtering[] = $className;
  1062. foreach ($resultSet as $key => &$result) {
  1063. $data = $LinkedModel->afterFind(array(array($className => $result[$className])), false);
  1064. if (isset($data[0][$className])) {
  1065. $result[$className] = $data[0][$className];
  1066. } else {
  1067. unset($resultSet[$key]);
  1068. }
  1069. }
  1070. }
  1071. return $filtering;
  1072. }
  1073. /**
  1074. * Queries associations.
  1075. *
  1076. * Used to fetch results on recursive models.
  1077. *
  1078. * - 'hasMany' associations with no limit set:
  1079. * Fetch, filter and merge is done recursively for every level.
  1080. *
  1081. * - 'hasAndBelongsToMany' associations:
  1082. * Fetch and filter is done unaffected by the (recursive) level set.
  1083. *
  1084. * @param Model $Model Primary Model object.
  1085. * @param Model $LinkModel Linked model object.
  1086. * @param string $type Association type, one of the model association types ie. hasMany.
  1087. * @param string $association Association name.
  1088. * @param array $assocData Association data.
  1089. * @param array $queryData An array of queryData information containing keys similar to Model::find().
  1090. * @param boolean $external Whether or not the association query is on an external datasource.
  1091. * @param array $resultSet Existing results.
  1092. * @param integer $recursive Number of levels of association.
  1093. * @param array $stack
  1094. * @return mixed
  1095. * @throws CakeException when results cannot be created.
  1096. */
  1097. public function queryAssociation(Model $Model, Model $LinkModel, $type, $association, $assocData, &$queryData, $external, &$resultSet, $recursive, $stack) {
  1098. if (isset($stack['_joined'])) {
  1099. $joined = $stack['_joined'];
  1100. unset($stack['_joined']);
  1101. }
  1102. $queryTemplate = $this->generateAssociationQuery($Model, $LinkModel, $type, $association, $assocData, $queryData, $external);
  1103. if (empty($queryTemplate)) {
  1104. return;
  1105. }
  1106. if (!is_array($resultSet)) {
  1107. throw new CakeException(__d('cake_dev', 'Error in Model %s', get_class($Model)));
  1108. }
  1109. if ($type === 'hasMany' && empty($assocData['limit']) && !empty($assocData['foreignKey'])) {
  1110. // 'hasMany' associations with no limit set.
  1111. $assocIds = array();
  1112. foreach ($resultSet as $result) {
  1113. $assocIds[] = $this->insertQueryData('{$__cakeID__$}', $result, $association, $Model, $stack);
  1114. }
  1115. $assocIds = array_filter($assocIds);
  1116. // Fetch
  1117. $assocResultSet = array();
  1118. if (!empty($assocIds)) {
  1119. $assocResultSet = $this->_fetchHasMany($Model, $queryTemplate, $assocIds);
  1120. }
  1121. // Recursively query associations
  1122. if ($recursive > 0 && !empty($assocResultSet) && is_array($assocResultSet)) {
  1123. foreach ($LinkModel->associations() as $type1) {
  1124. foreach ($LinkModel->{$type1} as $assoc1 => $assocData1) {
  1125. $DeepModel = $LinkModel->{$assoc1};
  1126. $tmpStack = $stack;
  1127. $tmpStack[] = $assoc1;
  1128. $db = $LinkModel->useDbConfig === $DeepModel->useDbConfig ? $this : $DeepModel->getDataSource();
  1129. $db->queryAssociation($LinkModel, $DeepModel, $type1, $assoc1, $assocData1, $queryData, true, $assocResultSet, $recursive - 1, $tmpStack);
  1130. }
  1131. }
  1132. }
  1133. // Filter
  1134. if ($queryData['callbacks'] === true || $queryData['callbacks'] === 'after') {
  1135. $this->_filterResults($assocResultSet, $Model);
  1136. }
  1137. // Merge
  1138. return $this->_mergeHasMany($resultSet, $assocResultSet, $association, $Model);
  1139. } elseif ($type === 'hasAndBelongsToMany') {
  1140. // 'hasAndBelongsToMany' associations.
  1141. $assocIds = array();
  1142. foreach ($resultSet as $result) {
  1143. $assocIds[] = $this->insertQueryData('{$__cakeID__$}', $result, $association, $Model, $stack);
  1144. }
  1145. $assocIds = array_filter($assocIds);
  1146. // Fetch
  1147. $assocResultSet = array();
  1148. if (!empty($assocIds)) {
  1149. $assocResultSet = $this->_fetchHasAndBelongsToMany($Model, $queryTemplate, $assocIds, $association);
  1150. }
  1151. $habtmAssocData = $Model->hasAndBelongsToMany[$association];
  1152. $foreignKey = $habtmAssocData['foreignKey'];
  1153. $joinKeys = array($foreignKey, $habtmAssocData['associationForeignKey']);
  1154. list($with, $habtmFields) = $Model->joinModel($habtmAssocData['with'], $joinKeys);
  1155. $habtmFieldsCount = count($habtmFields);
  1156. // Filter
  1157. if ($queryData['callbacks'] === true || $queryData['callbacks'] === 'after') {
  1158. $this->_filterResults($assocResultSet, $Model);
  1159. }
  1160. }
  1161. $modelAlias = $Model->alias;
  1162. $primaryKey = $Model->primaryKey;
  1163. $selfJoin = ($Model->name === $LinkModel->name);
  1164. foreach ($resultSet as &$row) {
  1165. if ($type === 'hasOne' || $type === 'belongsTo' || $type === 'hasMany') {
  1166. $assocResultSet = array();
  1167. if (
  1168. ($type === 'hasOne' || $type === 'belongsTo') &&
  1169. isset($row[$LinkModel->alias], $joined[$Model->alias]) &&
  1170. in_array($LinkModel->alias, $joined[$Model->alias])
  1171. ) {
  1172. $joinedData = Hash::filter($row[$LinkModel->alias]);
  1173. if (!empty($joinedData)) {
  1174. $assocResultSet[0] = array($LinkModel->alias => $row[$LinkModel->alias]);
  1175. }
  1176. } else {
  1177. $query = $this->insertQueryData($queryTemplate, $row, $association, $Model, $stack);
  1178. if ($query !== false) {
  1179. $assocResultSet = $this->fetchAll($query, $Model->cacheQueries);
  1180. }
  1181. }
  1182. }
  1183. if (!empty($assocResultSet) && is_array($assocResultSet)) {
  1184. if ($recursive > 0) {
  1185. foreach ($LinkModel->associations() as $type1) {
  1186. foreach ($LinkModel->{$type1} as $assoc1 => $assocData1) {
  1187. $DeepModel = $LinkModel->{$assoc1};
  1188. if (
  1189. $type1 === 'belongsTo' ||
  1190. ($type === 'belongsTo' && $DeepModel->alias === $modelAlias) ||
  1191. ($DeepModel->alias !== $modelAlias)
  1192. ) {
  1193. $tmpStack = $stack;
  1194. $tmpStack[] = $assoc1;
  1195. $db = $LinkModel->useDbConfig === $DeepModel->useDbConfig ? $this : $DeepModel->getDataSource();
  1196. $db->queryAssociation($LinkModel, $DeepModel, $type1, $assoc1, $assocData1, $queryData, true, $assocResultSet, $recursive - 1, $tmpStack);
  1197. }
  1198. }
  1199. }
  1200. }
  1201. if ($type === 'hasAndBelongsToMany') {
  1202. $merge = array();
  1203. foreach ($assocResultSet as $data) {
  1204. if (isset($data[$with]) && $data[$with][$foreignKey] === $row[$modelAlias][$primaryKey]) {
  1205. if ($habtmFieldsCount <= 2) {
  1206. unset($data[$with]);
  1207. }
  1208. $merge[] = $data;
  1209. }
  1210. }
  1211. if (empty($merge) && !isset($row[$association])) {
  1212. $row[$association] = $merge;
  1213. } else {
  1214. $this->_mergeAssociation($row, $merge, $association, $type);
  1215. }
  1216. } else {
  1217. $this->_mergeAssociation($row, $assocResultSet, $association, $type, $selfJoin);
  1218. }
  1219. if ($type !== 'hasAndBelongsToMany' && isset($row[$association])) {
  1220. $row[$association] = $LinkModel->afterFind($row[$association], false);
  1221. }
  1222. } else {
  1223. $tempArray[0][$association] = false;
  1224. $this->_mergeAssociation($row, $tempArray, $association, $type, $selfJoin);
  1225. }
  1226. }
  1227. }
  1228. /**
  1229. * Fetch 'hasMany' associations.
  1230. *
  1231. * This is just a proxy to maintain BC.
  1232. *
  1233. * @param Model $Model Primary model object.
  1234. * @param string $query Association query template.
  1235. * @param array $ids Array of IDs of associated records.
  1236. * @return array Association results.
  1237. * @see DboSource::_fetchHasMany()
  1238. */
  1239. public function fetchAssociated(Model $Model, $query, $ids) {
  1240. return $this->_fetchHasMany($Model, $query, $ids);
  1241. }
  1242. /**
  1243. * Fetch 'hasMany' associations.
  1244. *
  1245. * @param Model $Model Primary model object.
  1246. * @param string $query Association query template.
  1247. * @param array $ids Array of IDs of associated records.
  1248. * @return array Association results.
  1249. */
  1250. protected function _fetchHasMany(Model $Model, $query, $ids) {
  1251. $ids = array_unique($ids);
  1252. $query = str_replace('{$__cakeID__$}', implode(', ', $ids), $query);
  1253. if (count($ids) > 1) {
  1254. $query = str_replace('= (', 'IN (', $query);
  1255. }
  1256. return $this->fetchAll($query, $Model->cacheQueries);
  1257. }
  1258. /**
  1259. * Fetch 'hasAndBelongsToMany' associations.
  1260. *
  1261. * @param Model $Model Primary model object.
  1262. * @param string $query Association query.
  1263. * @param array $ids Array of IDs of associated records.
  1264. * @param string $association Association name.
  1265. * @return array Association results.
  1266. */
  1267. protected function _fetchHasAndBelongsToMany(Model $Model, $query, $ids, $association) {
  1268. $ids = array_unique($ids);
  1269. if (count($ids) > 1) {
  1270. $query = str_replace('{$__cakeID__$}', '(' . implode(', ', $ids) . ')', $query);
  1271. $query = str_replace('= (', 'IN (', $query);
  1272. } else {
  1273. $query = str_replace('{$__cakeID__$}', $ids[0], $query);
  1274. }
  1275. $query = str_replace(' WHERE 1 = 1', '', $query);
  1276. return $this->fetchAll($query, $Model->cacheQueries);
  1277. }
  1278. /**
  1279. * Merge the results of 'hasMany' associations.
  1280. *
  1281. * Note: this function also deals with the formatting of the data.
  1282. *
  1283. * @param array $resultSet Data to merge into.
  1284. * @param array $assocResultSet Data to merge.
  1285. * @param string $association Name of Model being merged.
  1286. * @param Model $Model Model being merged onto.
  1287. * @return void
  1288. */
  1289. protected function _mergeHasMany(&$resultSet, $assocResultSet, $association, Model $Model) {
  1290. $modelAlias = $Model->alias;
  1291. $primaryKey = $Model->primaryKey;
  1292. $foreignKey = $Model->hasMany[$association]['foreignKey'];
  1293. foreach ($resultSet as &$result) {
  1294. if (!isset($result[$modelAlias])) {
  1295. continue;
  1296. }
  1297. $resultPrimaryKey = $result[$modelAlias][$primaryKey];
  1298. $merged = array();
  1299. foreach ($assocResultSet as $data) {
  1300. if ($resultPrimaryKey !== $data[$association][$foreignKey]) {
  1301. continue;
  1302. }
  1303. if (count($data) > 1) {
  1304. $data = array_merge($data[$association], $data);
  1305. unset($data[$association]);
  1306. foreach ($data as $key => $name) {
  1307. if (is_numeric($key)) {
  1308. $data[$association][] = $name;
  1309. unset($data[$key]);
  1310. }
  1311. }
  1312. $merged[] = $data;
  1313. } else {
  1314. $merged[] = $data[$association];
  1315. }
  1316. }
  1317. $result = Hash::mergeDiff($result, array($association => $merged));
  1318. }
  1319. }
  1320. /**
  1321. * Merge association of merge into data
  1322. *
  1323. * @param array $data
  1324. * @param array $merge
  1325. * @param string $association
  1326. * @param string $type
  1327. * @param boolean $selfJoin
  1328. * @return void
  1329. */
  1330. protected function _mergeAssociation(&$data, &$merge, $association, $type, $selfJoin = false) {
  1331. if (isset($merge[0]) && !isset($merge[0][$association])) {
  1332. $association = Inflector::pluralize($association);
  1333. }
  1334. $dataAssociation =& $data[$association];
  1335. if ($type === 'belongsTo' || $type === 'hasOne') {
  1336. if (isset($merge[$association])) {
  1337. $dataAssociation = $merge[$association][0];
  1338. } else {
  1339. if (!empty($merge[0][$association])) {
  1340. foreach ($merge[0] as $assoc => $data2) {
  1341. if ($assoc !== $association) {
  1342. $merge[0][$association][$assoc] = $data2;
  1343. }
  1344. }
  1345. }
  1346. if (!isset($dataAssociation)) {
  1347. $dataAssociation = array();
  1348. if ($merge[0][$association]) {
  1349. $dataAssociation = $merge[0][$association];
  1350. }
  1351. } else {
  1352. if (is_array($merge[0][$association])) {
  1353. foreach ($dataAssociation as $k => $v) {
  1354. if (!is_array($v)) {
  1355. $dataAssocTmp[$k] = $v;
  1356. }
  1357. }
  1358. foreach ($merge[0][$association] as $k => $v) {
  1359. if (!is_array($v)) {
  1360. $mergeAssocTmp[$k] = $v;
  1361. }
  1362. }
  1363. $dataKeys = array_keys($data);
  1364. $mergeKeys = array_keys($merge[0]);
  1365. if ($mergeKeys[0] === $dataKeys[0] || $mergeKeys === $dataKeys) {
  1366. $dataAssociation[$association] = $merge[0][$association];
  1367. } else {
  1368. $diff = Hash::diff($dataAssocTmp, $mergeAssocTmp);
  1369. $dataAssociation = array_merge($merge[0][$association], $diff);
  1370. }
  1371. } elseif ($selfJoin && array_key_exists($association, $merge[0])) {
  1372. $dataAssociation = array_merge($dataAssociation, array($association => array()));
  1373. }
  1374. }
  1375. }
  1376. } else {
  1377. if (isset($merge[0][$association]) && $merge[0][$association] === false) {
  1378. if (!isset($dataAssociation)) {
  1379. $dataAssociation = array();
  1380. }
  1381. } else {
  1382. foreach ($merge as $row) {
  1383. $insert = array();
  1384. if (count($row) === 1) {
  1385. $insert = $row[$association];
  1386. } elseif (isset($row[$association])) {
  1387. $insert = array_merge($row[$association], $row);
  1388. unset($insert[$association]);
  1389. }
  1390. if (empty($dataAssociation) || (isset($dataAssociation) && !in_array($insert, $dataAssociation, true))) {
  1391. $dataAssociation[] = $insert;
  1392. }
  1393. }
  1394. }
  1395. }
  1396. }
  1397. /**
  1398. * Prepares fields required by an SQL statement.
  1399. *
  1400. * When no fields are set, all the $Model fields are returned.
  1401. *
  1402. * @param Model $Model
  1403. * @param array $queryData An array of queryData information containing keys similar to Model::find().
  1404. * @return array Array containing SQL fields.
  1405. */
  1406. public function prepareFields(Model $Model, $queryData) {
  1407. if (empty($queryData['fields'])) {
  1408. $queryData['fields'] = $this->fields($Model);
  1409. } elseif (!empty($Model->hasMany) && $Model->recursive > -1) {
  1410. // hasMany relationships need the $Model primary key.
  1411. $assocFields = $this->fields($Model, null, "{$Model->alias}.{$Model->primaryKey}");
  1412. $passedFields = $queryData['fields'];
  1413. if (
  1414. count($passedFields) > 1 ||
  1415. (strpos($passedFields[0], $assocFields[0]) === false && !preg_match('/^[a-z]+\(/i', $passedFields[0]))
  1416. ) {
  1417. $queryData['fields'] = array_merge($passedFields, $assocFields);
  1418. }
  1419. }
  1420. return array_unique($queryData['fields']);
  1421. }
  1422. /**
  1423. * Builds an SQL statement.
  1424. *
  1425. * This is merely a convenient wrapper to DboSource::buildStatement().
  1426. *
  1427. * @param Model $Model
  1428. * @param array $queryData An array of queryData information containing keys similar to Model::find().
  1429. * @return string String containing an SQL statement.
  1430. * @see DboSource::buildStatement()
  1431. */
  1432. public function buildAssociationQuery(Model $Model, $queryData) {
  1433. $queryData = $this->_scrubQueryData($queryData);
  1434. return $this->buildStatement(
  1435. array(
  1436. 'fields' => $this->prepareFields($Model, $queryData),
  1437. 'table' => $this->fullTableName($Model),
  1438. 'alias' => $Model->alias,
  1439. 'limit' => $queryData['limit'],
  1440. 'offset' => $queryData['offset'],
  1441. 'joins' => $queryData['joins'],
  1442. 'conditions' => $queryData['conditions'],
  1443. 'order' => $queryData['order'],
  1444. 'group' => $queryData['group']
  1445. ),
  1446. $Model
  1447. );
  1448. }
  1449. /**
  1450. * Generates a query or part of a query from a single model or two associated models.
  1451. *
  1452. * Builds a string containing an SQL statement template.
  1453. *
  1454. * @param Model $Model Primary Model object.
  1455. * @param Model|null $LinkModel Linked model object.
  1456. * @param string $type Association type, one of the model association types ie. hasMany.
  1457. * @param string $association Association name.
  1458. * @param array $assocData Association data.
  1459. * @param array $queryData An array of queryData information containing keys similar to Model::find().
  1460. * @param boolean $external Whether or not the association query is on an external datasource.
  1461. * @return mixed
  1462. * String representing a query.
  1463. * True, when $external is false and association $type is 'hasOne' or 'belongsTo'.
  1464. */
  1465. public function generateAssociationQuery(Model $Model, $LinkModel, $type, $association, $assocData, &$queryData, $external) {
  1466. $assocData = $this->_scrubQueryData($assocData);
  1467. $queryData = $this->_scrubQueryData($queryData);
  1468. if ($LinkModel === null) {
  1469. return $this->buildStatement(
  1470. array(
  1471. 'fields' => array_unique($queryData['fields']),
  1472. 'table' => $this->fullTableName($Model),
  1473. 'alias' => $Model->alias,
  1474. 'limit' => $queryData['limit'],
  1475. 'offset' => $queryData['offset'],
  1476. 'joins' => $queryData['joins'],
  1477. 'conditions' => $queryData['conditions'],
  1478. 'order' => $queryData['order'],
  1479. 'group' => $queryData['group']
  1480. ),
  1481. $Model
  1482. );
  1483. }
  1484. if ($external && !empty($assocData['finderQuery'])) {
  1485. return $assocData['finderQuery'];
  1486. }
  1487. if ($type === 'hasMany' || $type === 'hasAndBelongsToMany') {
  1488. if (empty($assocData['offset']) && !empty($assocData['page'])) {
  1489. $assocData['offset'] = ($assocData['page'] - 1) * $assocData['limit'];
  1490. }
  1491. }
  1492. switch ($type) {
  1493. case 'hasOne':
  1494. case 'belongsTo':
  1495. $conditions = $this->_mergeConditions(
  1496. $assocData['conditions'],
  1497. $this->getConstraint($type, $Model, $LinkModel, $association, array_merge($assocData, compact('external')))
  1498. );
  1499. if ($external) {
  1500. // Not self join
  1501. if ($Model->name !== $LinkModel->name) {
  1502. $modelAlias = $Model->alias;
  1503. foreach ($conditions as $key => $condition) {
  1504. if (is_numeric($key) && strpos($condition, $modelAlias . '.') !== false) {
  1505. unset($conditions[$key]);
  1506. }
  1507. }
  1508. }
  1509. $query = array_merge($assocData, array(
  1510. 'conditions' => $conditions,
  1511. 'table' => $this->fullTableName($LinkModel),
  1512. 'fields' => $this->fields($LinkModel, $association, $assocData['fields']),
  1513. 'alias' => $association,
  1514. 'group' => null
  1515. ));
  1516. } else {
  1517. $join = array(
  1518. 'table' => $LinkModel,
  1519. 'alias' => $association,
  1520. 'type' => isset($assocData['type']) ? $assocData['type'] : 'LEFT',
  1521. 'conditions' => trim($this->conditions($conditions, true, false, $Model))
  1522. );
  1523. $fields = array();
  1524. if ($assocData['fields'] !== false) {
  1525. $fields = $this->fields($LinkModel, $association, $assocData['fields']);
  1526. }
  1527. $queryData['fields'] = array_merge($this->prepareFields($Model, $queryData), $fields);
  1528. if (!empty($assocData['order'])) {
  1529. $queryData['order'][] = $assocData['order'];
  1530. }
  1531. if (!in_array($join, $queryData['joins'], true)) {
  1532. $queryData['joins'][] = $join;
  1533. }
  1534. return true;
  1535. }
  1536. break;
  1537. case 'hasMany':
  1538. $assocData['fields'] = $this->fields($LinkModel, $association, $assocData['fields']);
  1539. if (!empty($assocData['foreignKey'])) {
  1540. $assocData['fields'] = array_merge($assocData['fields'], $this->fields($LinkModel, $association, array("{$association}.{$assocData['foreignKey']}")));
  1541. }
  1542. $query = array(
  1543. 'conditions' => $this->_mergeConditions($this->getConstraint('hasMany', $Model, $LinkModel, $association, $assocData), $assocData['conditions']),
  1544. 'fields' => array_unique($assocData['fields']),
  1545. 'table' => $this->fullTableName($LinkModel),
  1546. 'alias' => $association,
  1547. 'order' => $assocData['order'],
  1548. 'limit' => $assocData['limit'],
  1549. 'offset' => $assocData['offset'],
  1550. 'group' => null
  1551. );
  1552. break;
  1553. case 'hasAndBelongsToMany':
  1554. $joinFields = array();
  1555. $joinAssoc = null;
  1556. if (isset($assocData['with']) && !empty($assocData['with'])) {
  1557. $joinKeys = array($assocData['foreignKey'], $assocData['associationForeignKey']);
  1558. list($with, $joinFields) = $Model->joinModel($assocData['with'], $joinKeys);
  1559. $joinTbl = $Model->{$with};
  1560. $joinAlias = $joinTbl;
  1561. if (is_array($joinFields) && !empty($joinFields)) {
  1562. $joinAssoc = $joinAlias = $joinTbl->alias;
  1563. $joinFields = $this->fields($joinTbl, $joinAlias, $joinFields);
  1564. } else {
  1565. $joinFields = array();
  1566. }
  1567. } else {
  1568. $joinTbl = $assocData['joinTable'];
  1569. $joinAlias = $this->fullTableName($assocData['joinTable']);
  1570. }
  1571. $query = array(
  1572. 'conditions' => $assocData['conditions'],
  1573. 'limit' => $assocData['limit'],
  1574. 'offset' => $assocData['offset'],
  1575. 'table' => $this->fullTableName($LinkModel),
  1576. 'alias' => $association,
  1577. 'fields' => array_merge($this->fields($LinkModel, $association, $assocData['fields']), $joinFields),
  1578. 'order' => $assocData['order'],
  1579. 'group' => null,
  1580. 'joins' => array(array(
  1581. 'table' => $joinTbl,
  1582. 'alias' => $joinAssoc,
  1583. 'conditions' => $this->getConstraint('hasAndBelongsToMany', $Model, $LinkModel, $joinAlias, $assocData, $association)
  1584. ))
  1585. );
  1586. break;
  1587. }
  1588. if (isset($query)) {
  1589. return $this->buildStatement($query, $Model);
  1590. }
  1591. return null;
  1592. }
  1593. /**
  1594. * Returns a conditions array for the constraint between two models.
  1595. *
  1596. * @param string $type Association type.
  1597. * @param Model $Model Primary Model object.
  1598. * @param Model $LinkModel Linked model object.
  1599. * @param string $association Association name.
  1600. * @param array $assocData Association data.
  1601. * @param string $association2 HABTM association name.
  1602. * @return array Conditions array defining the constraint between $Model and $LinkModel.
  1603. */
  1604. public function getConstraint($type, Model $Model, Model $LinkModel, $association, $assocData, $association2 = null) {
  1605. $assocData += array('external' => false);
  1606. if (empty($assocData['foreignKey'])) {
  1607. return array();
  1608. }
  1609. switch ($type) {
  1610. case 'hasOne':
  1611. if ($assocData['external']) {
  1612. return array(
  1613. "{$association}.{$assocData['foreignKey']}" => '{$__cakeID__$}'
  1614. );
  1615. } else {
  1616. return array(
  1617. "{$association}.{$assocData['foreignKey']}" => $this->identifier("{$Model->alias}.{$Model->primaryKey}")
  1618. );
  1619. }
  1620. case 'belongsTo':
  1621. if ($assocData['external']) {
  1622. return array(
  1623. "{$association}.{$LinkModel->primaryKey}" => '{$__cakeForeignKey__$}'
  1624. );
  1625. } else {
  1626. return array(
  1627. "{$Model->alias}.{$assocData['foreignKey']}" => $this->identifier("{$association}.{$LinkModel->primaryKey}")
  1628. );
  1629. }
  1630. case 'hasMany':
  1631. return array("{$association}.{$assocData['foreignKey']}" => array('{$__cakeID__$}'));
  1632. case 'hasAndBelongsToMany':
  1633. return array(
  1634. array(
  1635. "{$association}.{$assocData['foreignKey']}" => '{$__cakeID__$}'
  1636. ),
  1637. array(
  1638. "{$association}.{$assocData['associationForeignKey']}" => $this->identifier("{$association2}.{$LinkModel->primaryKey}")
  1639. )
  1640. );
  1641. }
  1642. return array();
  1643. }
  1644. /**
  1645. * Builds and generates a JOIN condition from an array. Handles final clean-up before conversion.
  1646. *
  1647. * @param array $join An array defining a JOIN condition in a query.
  1648. * @return string An SQL JOIN condition to be used in a query.
  1649. * @see DboSource::renderJoinStatement()
  1650. * @see DboSource::buildStatement()
  1651. */
  1652. public function buildJoinStatement($join) {
  1653. $data = array_merge(array(
  1654. 'type' => null,
  1655. 'alias' => null,
  1656. 'table' => 'join_table',
  1657. 'conditions' => array()
  1658. ), $join);
  1659. if (!empty($data['alias'])) {
  1660. $data['alias'] = $this->alias . $this->name($data['alias']);
  1661. }
  1662. if (!empty($data['conditions'])) {
  1663. $data['conditions'] = trim($this->conditions($data['conditions'], true, false));
  1664. }
  1665. if (!empty($data['table']) && (!is_string($data['table']) || strpos($data['table'], '(') !== 0)) {
  1666. $data['table'] = $this->fullTableName($data['table']);
  1667. }
  1668. return $this->renderJoinStatement($data);
  1669. }
  1670. /**
  1671. * Builds and generates an SQL statement from an array. Handles final clean-up before conversion.
  1672. *
  1673. * @param array $query An array defining an SQL query.
  1674. * @param Model $Model The model object which initiated the query.
  1675. * @return string An executable SQL statement.
  1676. * @see DboSource::renderStatement()
  1677. */
  1678. public function buildStatement($query, Model $Model) {
  1679. $query = array_merge($this->_queryDefaults, $query);
  1680. if (!empty($query['joins'])) {
  1681. $count = count($query['joins']);
  1682. for ($i = 0; $i < $count; $i++) {
  1683. if (is_array($query['joins'][$i])) {
  1684. $query['joins'][$i] = $this->buildJoinStatement($query['joins'][$i]);
  1685. }
  1686. }
  1687. }
  1688. return $this->renderStatement('select', array(
  1689. 'conditions' => $this->conditions($query['conditions'], true, true, $Model),
  1690. 'fields' => implode(', ', $query['fields']),
  1691. 'table' => $query['table'],
  1692. 'alias' => $this->alias . $this->name($query['alias']),
  1693. 'order' => $this->order($query['order'], 'ASC', $Model),
  1694. 'limit' => $this->limit($query['limit'], $query['offset']),
  1695. 'joins' => implode(' ', $query['joins']),
  1696. 'group' => $this->group($query['group'], $Model)
  1697. ));
  1698. }
  1699. /**
  1700. * Renders a final SQL JOIN statement
  1701. *
  1702. * @param array $data
  1703. * @return string
  1704. */
  1705. public function renderJoinStatement($data) {
  1706. if (strtoupper($data['type']) === 'CROSS') {
  1707. return "{$data['type']} JOIN {$data['table']} {$data['alias']}";
  1708. }
  1709. return trim("{$data['type']} JOIN {$data['table']} {$data['alias']} ON ({$data['conditions']})");
  1710. }
  1711. /**
  1712. * Renders a final SQL statement by putting together the component parts in the correct order
  1713. *
  1714. * @param string $type type of query being run. e.g select, create, update, delete, schema, alter.
  1715. * @param array $data Array of data to insert into the query.
  1716. * @return string Rendered SQL expression to be run.
  1717. */
  1718. public function renderStatement($type, $data) {
  1719. extract($data);
  1720. $aliases = null;
  1721. switch (strtolower($type)) {
  1722. case 'select':
  1723. return trim("SELECT {$fields} FROM {$table} {$alias} {$joins} {$conditions} {$group} {$order} {$limit}");
  1724. case 'create':
  1725. return "INSERT INTO {$table} ({$fields}) VALUES ({$values})";
  1726. case 'update':
  1727. if (!empty($alias)) {
  1728. $aliases = "{$this->alias}{$alias} {$joins} ";
  1729. }
  1730. return trim("UPDATE {$table} {$aliases}SET {$fields} {$conditions}");
  1731. case 'delete':
  1732. if (!empty($alias)) {
  1733. $aliases = "{$this->alias}{$alias} {$joins} ";
  1734. }
  1735. return trim("DELETE {$alias} FROM {$table} {$aliases}{$conditions}");
  1736. case 'schema':
  1737. foreach (array('columns', 'indexes', 'tableParameters') as $var) {
  1738. if (is_array(${$var})) {
  1739. ${$var} = "\t" . implode(",\n\t", array_filter(${$var}));
  1740. } else {
  1741. ${$var} = '';
  1742. }
  1743. }
  1744. if (trim($indexes) !== '') {
  1745. $columns .= ',';
  1746. }
  1747. return "CREATE TABLE {$table} (\n{$columns}{$indexes}) {$tableParameters};";
  1748. case 'alter':
  1749. return;
  1750. }
  1751. }
  1752. /**
  1753. * Merges a mixed set of string/array conditions.
  1754. *
  1755. * @param mixed $query
  1756. * @param mixed $assoc
  1757. * @return array
  1758. */
  1759. protected function _mergeConditions($query, $assoc) {
  1760. if (empty($assoc)) {
  1761. return $query;
  1762. }
  1763. if (is_array($query)) {
  1764. return array_merge((array)$assoc, $query);
  1765. }
  1766. if (!empty($query)) {
  1767. $query = array($query);
  1768. if (is_array($assoc)) {
  1769. $query = array_merge($query, $assoc);
  1770. } else {
  1771. $query[] = $assoc;
  1772. }
  1773. return $query;
  1774. }
  1775. return $assoc;
  1776. }
  1777. /**
  1778. * Generates and executes an SQL UPDATE statement for given model, fields, and values.
  1779. * For databases that do not support aliases in UPDATE queries.
  1780. *
  1781. * @param Model $Model
  1782. * @param array $fields
  1783. * @param array $values
  1784. * @param mixed $conditions
  1785. * @return boolean Success
  1786. */
  1787. public function update(Model $Model, $fields = array(), $values = null, $conditions = null) {
  1788. if (!$values) {
  1789. $combined = $fields;
  1790. } else {
  1791. $combined = array_combine($fields, $values);
  1792. }
  1793. $fields = implode(', ', $this->_prepareUpdateFields($Model, $combined, empty($conditions)));
  1794. $alias = $joins = null;
  1795. $table = $this->fullTableName($Model);
  1796. $conditions = $this->_matchRecords($Model, $conditions);
  1797. if ($conditions === false) {
  1798. return false;
  1799. }
  1800. $query = compact('table', 'alias', 'joins', 'fields', 'conditions');
  1801. if (!$this->execute($this->renderStatement('update', $query))) {
  1802. $Model->onError();
  1803. return false;
  1804. }
  1805. return true;
  1806. }
  1807. /**
  1808. * Quotes and prepares fields and values for an SQL UPDATE statement
  1809. *
  1810. * @param Model $Model
  1811. * @param array $fields
  1812. * @param boolean $quoteValues If values should be quoted, or treated as SQL snippets
  1813. * @param boolean $alias Include the model alias in the field name
  1814. * @return array Fields and values, quoted and prepared
  1815. */
  1816. protected function _prepareUpdateFields(Model $Model, $fields, $quoteValues = true, $alias = false) {
  1817. $quotedAlias = $this->startQuote . $Model->alias . $this->endQuote;
  1818. $updates = array();
  1819. foreach ($fields as $field => $value) {
  1820. if ($alias && strpos($field, '.') === false) {
  1821. $quoted = $Model->escapeField($field);
  1822. } elseif (!$alias && strpos($field, '.') !== false) {
  1823. $quoted = $this->name(str_replace($quotedAlias . '.', '', str_replace(
  1824. $Model->alias . '.', '', $field
  1825. )));
  1826. } else {
  1827. $quoted = $this->name($field);
  1828. }
  1829. if ($value === null) {
  1830. $updates[] = $quoted . ' = NULL';
  1831. continue;
  1832. }
  1833. $update = $quoted . ' = ';
  1834. if ($quoteValues) {
  1835. $update .= $this->value($value, $Model->getColumnType($field));
  1836. } elseif ($Model->getColumnType($field) === 'boolean' && (is_int($value) || is_bool($value))) {
  1837. $update .= $this->boolean($value, true);
  1838. } elseif (!$alias) {
  1839. $update .= str_replace($quotedAlias . '.', '', str_replace(
  1840. $Model->alias . '.', '', $value
  1841. ));
  1842. } else {
  1843. $update .= $value;
  1844. }
  1845. $updates[] = $update;
  1846. }
  1847. return $updates;
  1848. }
  1849. /**
  1850. * Generates and executes an SQL DELETE statement.
  1851. * For databases that do not support aliases in UPDATE queries.
  1852. *
  1853. * @param Model $Model
  1854. * @param mixed $conditions
  1855. * @return boolean Success
  1856. */
  1857. public function delete(Model $Model, $conditions = null) {
  1858. $alias = $joins = null;
  1859. $table = $this->fullTableName($Model);
  1860. $conditions = $this->_matchRecords($Model, $conditions);
  1861. if ($conditions === false) {
  1862. return false;
  1863. }
  1864. if ($this->execute($this->renderStatement('delete', compact('alias', 'table', 'joins', 'conditions'))) === false) {
  1865. $Model->onError();
  1866. return false;
  1867. }
  1868. return true;
  1869. }
  1870. /**
  1871. * Gets a list of record IDs for the given conditions. Used for multi-record updates and deletes
  1872. * in databases that do not support aliases in UPDATE/DELETE queries.
  1873. *
  1874. * @param Model $Model
  1875. * @param mixed $conditions
  1876. * @return array List of record IDs
  1877. */
  1878. protected function _matchRecords(Model $Model, $conditions = null) {
  1879. if ($conditions === true) {
  1880. $conditions = $this->conditions(true);
  1881. } elseif ($conditions === null) {
  1882. $conditions = $this->conditions($this->defaultConditions($Model, $conditions, false), true, true, $Model);
  1883. } else {
  1884. $noJoin = true;
  1885. foreach ($conditions as $field => $value) {
  1886. $originalField = $field;
  1887. if (strpos($field, '.') !== false) {
  1888. list(, $field) = explode('.', $field);
  1889. $field = ltrim($field, $this->startQuote);
  1890. $field = rtrim($field, $this->endQuote);
  1891. }
  1892. if (!$Model->hasField($field)) {
  1893. $noJoin = false;
  1894. break;
  1895. }
  1896. if ($field !== $originalField) {
  1897. $conditions[$field] = $value;
  1898. unset($conditions[$originalField]);
  1899. }
  1900. }
  1901. if ($noJoin === true) {
  1902. return $this->conditions($conditions);
  1903. }
  1904. $idList = $Model->find('all', array(
  1905. 'fields' => "{$Model->alias}.{$Model->primaryKey}",
  1906. 'conditions' => $conditions
  1907. ));
  1908. if (empty($idList)) {
  1909. return false;
  1910. }
  1911. $conditions = $this->conditions(array(
  1912. $Model->primaryKey => Hash::extract($idList, "{n}.{$Model->alias}.{$Model->primaryKey}")
  1913. ));
  1914. }
  1915. return $conditions;
  1916. }
  1917. /**
  1918. * Returns an array of SQL JOIN conditions from a model's associations.
  1919. *
  1920. * @param Model $Model
  1921. * @return array
  1922. */
  1923. protected function _getJoins(Model $Model) {
  1924. $join = array();
  1925. $joins = array_merge($Model->getAssociated('hasOne'), $Model->getAssociated('belongsTo'));
  1926. foreach ($joins as $assoc) {
  1927. if (!isset($Model->{$assoc})) {
  1928. continue;
  1929. }
  1930. $LinkModel = $Model->{$assoc};
  1931. if ($Model->useDbConfig !== $LinkModel->useDbConfig) {
  1932. continue;
  1933. }
  1934. $assocData = $Model->getAssociated($assoc);
  1935. $join[] = $this->buildJoinStatement(array(
  1936. 'table' => $LinkModel,
  1937. 'alias' => $assoc,
  1938. 'type' => isset($assocData['type']) ? $assocData['type'] : 'LEFT',
  1939. 'conditions' => trim($this->conditions(
  1940. $this->_mergeConditions($assocData['conditions'], $this->getConstraint($assocData['association'], $Model, $LinkModel, $assoc, $assocData)),
  1941. true,
  1942. false,
  1943. $Model
  1944. ))
  1945. ));
  1946. }
  1947. return $join;
  1948. }
  1949. /**
  1950. * Returns an SQL calculation, i.e. COUNT() or MAX()
  1951. *
  1952. * @param Model $Model
  1953. * @param string $func Lowercase name of SQL function, i.e. 'count' or 'max'
  1954. * @param array $params Function parameters (any values must be quoted manually)
  1955. * @return string An SQL calculation function
  1956. */
  1957. public function calculate(Model $Model, $func, $params = array()) {
  1958. $params = (array)$params;
  1959. switch (strtolower($func)) {
  1960. case 'count':
  1961. if (!isset($params[0])) {
  1962. $params[0] = '*';
  1963. }
  1964. if (!isset($params[1])) {
  1965. $params[1] = 'count';
  1966. }
  1967. if ($Model->isVirtualField($params[0])) {
  1968. $arg = $this->_quoteFields($Model->getVirtualField($params[0]));
  1969. } else {
  1970. $arg = $this->name($params[0]);
  1971. }
  1972. return 'COUNT(' . $arg . ') AS ' . $this->name($params[1]);
  1973. case 'max':
  1974. case 'min':
  1975. if (!isset($params[1])) {
  1976. $params[1] = $params[0];
  1977. }
  1978. if ($Model->isVirtualField($params[0])) {
  1979. $arg = $this->_quoteFields($Model->getVirtualField($params[0]));
  1980. } else {
  1981. $arg = $this->name($params[0]);
  1982. }
  1983. return strtoupper($func) . '(' . $arg . ') AS ' . $this->name($params[1]);
  1984. }
  1985. }
  1986. /**
  1987. * Deletes all the records in a table and resets the count of the auto-incrementing
  1988. * primary key, where applicable.
  1989. *
  1990. * @param Model|string $table A string or model class representing the table to be truncated
  1991. * @return boolean SQL TRUNCATE TABLE statement, false if not applicable.
  1992. */
  1993. public function truncate($table) {
  1994. return $this->execute('TRUNCATE TABLE ' . $this->fullTableName($table));
  1995. }
  1996. /**
  1997. * Check if the server support nested transactions
  1998. *
  1999. * @return boolean
  2000. */
  2001. public function nestedTransactionSupported() {
  2002. return false;
  2003. }
  2004. /**
  2005. * Begin a transaction
  2006. *
  2007. * @return boolean True on success, false on fail
  2008. * (i.e. if the database/model does not support transactions,
  2009. * or a transaction has not started).
  2010. */
  2011. public function begin() {
  2012. if ($this->_transactionStarted) {
  2013. if ($this->nestedTransactionSupported()) {
  2014. return $this->_beginNested();
  2015. }
  2016. $this->_transactionNesting++;
  2017. return $this->_transactionStarted;
  2018. }
  2019. $this->_transactionNesting = 0;
  2020. if ($this->fullDebug) {
  2021. $this->logQuery('BEGIN');
  2022. }
  2023. return $this->_transactionStarted = $this->_connection->beginTransaction();
  2024. }
  2025. /**
  2026. * Begin a nested transaction
  2027. *
  2028. * @return boolean
  2029. */
  2030. protected function _beginNested() {
  2031. $query = 'SAVEPOINT LEVEL' . ++$this->_transactionNesting;
  2032. if ($this->fullDebug) {
  2033. $this->logQuery($query);
  2034. }
  2035. $this->_connection->exec($query);
  2036. return true;
  2037. }
  2038. /**
  2039. * Commit a transaction
  2040. *
  2041. * @return boolean True on success, false on fail
  2042. * (i.e. if the database/model does not support transactions,
  2043. * or a transaction has not started).
  2044. */
  2045. public function commit() {
  2046. if (!$this->_transactionStarted) {
  2047. return false;
  2048. }
  2049. if ($this->_transactionNesting === 0) {
  2050. if ($this->fullDebug) {
  2051. $this->logQuery('COMMIT');
  2052. }
  2053. $this->_transactionStarted = false;
  2054. return $this->_connection->commit();
  2055. }
  2056. if ($this->nestedTransactionSupported()) {
  2057. return $this->_commitNested();
  2058. }
  2059. $this->_transactionNesting--;
  2060. return true;
  2061. }
  2062. /**
  2063. * Commit a nested transaction
  2064. *
  2065. * @return boolean
  2066. */
  2067. protected function _commitNested() {
  2068. $query = 'RELEASE SAVEPOINT LEVEL' . $this->_transactionNesting--;
  2069. if ($this->fullDebug) {
  2070. $this->logQuery($query);
  2071. }
  2072. $this->_connection->exec($query);
  2073. return true;
  2074. }
  2075. /**
  2076. * Rollback a transaction
  2077. *
  2078. * @return boolean True on success, false on fail
  2079. * (i.e. if the database/model does not support transactions,
  2080. * or a transaction has not started).
  2081. */
  2082. public function rollback() {
  2083. if (!$this->_transactionStarted) {
  2084. return false;
  2085. }
  2086. if ($this->_transactionNesting === 0) {
  2087. if ($this->fullDebug) {
  2088. $this->logQuery('ROLLBACK');
  2089. }
  2090. $this->_transactionStarted = false;
  2091. return $this->_connection->rollBack();
  2092. }
  2093. if ($this->nestedTransactionSupported()) {
  2094. return $this->_rollbackNested();
  2095. }
  2096. $this->_transactionNesting--;
  2097. return true;
  2098. }
  2099. /**
  2100. * Rollback a nested transaction
  2101. *
  2102. * @return boolean
  2103. */
  2104. protected function _rollbackNested() {
  2105. $query = 'ROLLBACK TO SAVEPOINT LEVEL' . $this->_transactionNesting--;
  2106. if ($this->fullDebug) {
  2107. $this->logQuery($query);
  2108. }
  2109. $this->_connection->exec($query);
  2110. return true;
  2111. }
  2112. /**
  2113. * Returns the ID generated from the previous INSERT operation.
  2114. *
  2115. * @param mixed $source
  2116. * @return mixed
  2117. */
  2118. public function lastInsertId($source = null) {
  2119. return $this->_connection->lastInsertId();
  2120. }
  2121. /**
  2122. * Creates a default set of conditions from the model if $conditions is null/empty.
  2123. * If conditions are supplied then they will be returned. If a model doesn't exist and no conditions
  2124. * were provided either null or false will be returned based on what was input.
  2125. *
  2126. * @param Model $Model
  2127. * @param string|array|boolean $conditions Array of conditions, conditions string, null or false. If an array of conditions,
  2128. * or string conditions those conditions will be returned. With other values the model's existence will be checked.
  2129. * If the model doesn't exist a null or false will be returned depending on the input value.
  2130. * @param boolean $useAlias Use model aliases rather than table names when generating conditions
  2131. * @return mixed Either null, false, $conditions or an array of default conditions to use.
  2132. * @see DboSource::update()
  2133. * @see DboSource::conditions()
  2134. */
  2135. public function defaultConditions(Model $Model, $conditions, $useAlias = true) {
  2136. if (!empty($conditions)) {
  2137. return $conditions;
  2138. }
  2139. $exists = $Model->exists();
  2140. if (!$exists && $conditions !== null) {
  2141. return false;
  2142. } elseif (!$exists) {
  2143. return null;
  2144. }
  2145. $alias = $Model->alias;
  2146. if (!$useAlias) {
  2147. $alias = $this->fullTableName($Model, false);
  2148. }
  2149. return array("{$alias}.{$Model->primaryKey}" => $Model->getID());
  2150. }
  2151. /**
  2152. * Returns a key formatted like a string Model.fieldname(i.e. Post.title, or Country.name)
  2153. *
  2154. * @param Model $Model
  2155. * @param string $key
  2156. * @param string $assoc
  2157. * @return string
  2158. */
  2159. public function resolveKey(Model $Model, $key, $assoc = null) {
  2160. if (strpos('.', $key) !== false) {
  2161. return $this->name($Model->alias) . '.' . $this->name($key);
  2162. }
  2163. return $key;
  2164. }
  2165. /**
  2166. * Private helper method to remove query metadata in given data array.
  2167. *
  2168. * @param array $data
  2169. * @return array
  2170. */
  2171. protected function _scrubQueryData($data) {
  2172. static $base = null;
  2173. if ($base === null) {
  2174. $base = array_fill_keys(array('conditions', 'fields', 'joins', 'order', 'limit', 'offset', 'group'), array());
  2175. $base['callbacks'] = null;
  2176. }
  2177. return (array)$data + $base;
  2178. }
  2179. /**
  2180. * Converts model virtual fields into sql expressions to be fetched later
  2181. *
  2182. * @param Model $Model
  2183. * @param string $alias Alias table name
  2184. * @param array $fields virtual fields to be used on query
  2185. * @return array
  2186. */
  2187. protected function _constructVirtualFields(Model $Model, $alias, $fields) {
  2188. $virtual = array();
  2189. foreach ($fields as $field) {
  2190. $virtualField = $this->name($alias . $this->virtualFieldSeparator . $field);
  2191. $expression = $this->_quoteFields($Model->getVirtualField($field));
  2192. $virtual[] = '(' . $expression . ") {$this->alias} {$virtualField}";
  2193. }
  2194. return $virtual;
  2195. }
  2196. /**
  2197. * Generates the fields list of an SQL query.
  2198. *
  2199. * @param Model $Model
  2200. * @param string $alias Alias table name
  2201. * @param mixed $fields
  2202. * @param boolean $quote If false, returns fields array unquoted
  2203. * @return array
  2204. */
  2205. public function fields(Model $Model, $alias = null, $fields = array(), $quote = true) {
  2206. if (empty($alias)) {
  2207. $alias = $Model->alias;
  2208. }
  2209. $virtualFields = $Model->getVirtualField();
  2210. $cacheKey = array(
  2211. $alias,
  2212. get_class($Model),
  2213. $Model->alias,
  2214. $virtualFields,
  2215. $fields,
  2216. $quote,
  2217. ConnectionManager::getSourceName($this),
  2218. $Model->schemaName,
  2219. $Model->table
  2220. );
  2221. $cacheKey = md5(serialize($cacheKey));
  2222. if ($return = $this->cacheMethod(__FUNCTION__, $cacheKey)) {
  2223. return $return;
  2224. }
  2225. $allFields = empty($fields);
  2226. if ($allFields) {
  2227. $fields = array_keys($Model->schema());
  2228. } elseif (!is_array($fields)) {
  2229. $fields = String::tokenize($fields);
  2230. }
  2231. $fields = array_values(array_filter($fields));
  2232. $allFields = $allFields || in_array('*', $fields) || in_array($Model->alias . '.*', $fields);
  2233. $virtual = array();
  2234. if (!empty($virtualFields)) {
  2235. $virtualKeys = array_keys($virtualFields);
  2236. foreach ($virtualKeys as $field) {
  2237. $virtualKeys[] = $Model->alias . '.' . $field;
  2238. }
  2239. $virtual = ($allFields) ? $virtualKeys : array_intersect($virtualKeys, $fields);
  2240. foreach ($virtual as $i => $field) {
  2241. if (strpos($field, '.') !== false) {
  2242. $virtual[$i] = str_replace($Model->alias . '.', '', $field);
  2243. }
  2244. $fields = array_diff($fields, array($field));
  2245. }
  2246. $fields = array_values($fields);
  2247. }
  2248. if (!$quote) {
  2249. if (!empty($virtual)) {
  2250. $fields = array_merge($fields, $this->_constructVirtualFields($Model, $alias, $virtual));
  2251. }
  2252. return $fields;
  2253. }
  2254. $count = count($fields);
  2255. if ($count >= 1 && !in_array($fields[0], array('*', 'COUNT(*)'))) {
  2256. for ($i = 0; $i < $count; $i++) {
  2257. if (is_string($fields[$i]) && in_array($fields[$i], $virtual)) {
  2258. unset($fields[$i]);
  2259. continue;
  2260. }
  2261. if (is_object($fields[$i]) && isset($fields[$i]->type) && $fields[$i]->type === 'expression') {
  2262. $fields[$i] = $fields[$i]->value;
  2263. } elseif (preg_match('/^\(.*\)\s' . $this->alias . '.*/i', $fields[$i])) {
  2264. continue;
  2265. } elseif (!preg_match('/^.+\\(.*\\)/', $fields[$i])) {
  2266. $prepend = '';
  2267. if (strpos($fields[$i], 'DISTINCT') !== false) {
  2268. $prepend = 'DISTINCT ';
  2269. $fields[$i] = trim(str_replace('DISTINCT', '', $fields[$i]));
  2270. }
  2271. $dot = strpos($fields[$i], '.');
  2272. if ($dot === false) {
  2273. $prefix = !(
  2274. strpos($fields[$i], ' ') !== false ||
  2275. strpos($fields[$i], '(') !== false
  2276. );
  2277. $fields[$i] = $this->name(($prefix ? $alias . '.' : '') . $fields[$i]);
  2278. } else {
  2279. if (strpos($fields[$i], ',') === false) {
  2280. $build = explode('.', $fields[$i]);
  2281. if (!Hash::numeric($build)) {
  2282. $fields[$i] = $this->name(implode('.', $build));
  2283. }
  2284. }
  2285. }
  2286. $fields[$i] = $prepend . $fields[$i];
  2287. } elseif (preg_match('/\(([\.\w]+)\)/', $fields[$i], $field)) {
  2288. if (isset($field[1])) {
  2289. if (strpos($field[1], '.') === false) {
  2290. $field[1] = $this->name($alias . '.' . $field[1]);
  2291. } else {
  2292. $field[0] = explode('.', $field[1]);
  2293. if (!Hash::numeric($field[0])) {
  2294. $field[0] = implode('.', array_map(array(&$this, 'name'), $field[0]));
  2295. $fields[$i] = preg_replace('/\(' . $field[1] . '\)/', '(' . $field[0] . ')', $fields[$i], 1);
  2296. }
  2297. }
  2298. }
  2299. }
  2300. }
  2301. }
  2302. if (!empty($virtual)) {
  2303. $fields = array_merge($fields, $this->_constructVirtualFields($Model, $alias, $virtual));
  2304. }
  2305. return $this->cacheMethod(__FUNCTION__, $cacheKey, array_unique($fields));
  2306. }
  2307. /**
  2308. * Creates a WHERE clause by parsing given conditions data. If an array or string
  2309. * conditions are provided those conditions will be parsed and quoted. If a boolean
  2310. * is given it will be integer cast as condition. Null will return 1 = 1.
  2311. *
  2312. * Results of this method are stored in a memory cache. This improves performance, but
  2313. * because the method uses a hashing algorithm it can have collisions.
  2314. * Setting DboSource::$cacheMethods to false will disable the memory cache.
  2315. *
  2316. * @param mixed $conditions Array or string of conditions, or any value.
  2317. * @param boolean $quoteValues If true, values should be quoted
  2318. * @param boolean $where If true, "WHERE " will be prepended to the return value
  2319. * @param Model $Model A reference to the Model instance making the query
  2320. * @return string SQL fragment
  2321. */
  2322. public function conditions($conditions, $quoteValues = true, $where = true, Model $Model = null) {
  2323. $clause = $out = '';
  2324. if ($where) {
  2325. $clause = ' WHERE ';
  2326. }
  2327. if (is_array($conditions) && !empty($conditions)) {
  2328. $out = $this->conditionKeysToString($conditions, $quoteValues, $Model);
  2329. if (empty($out)) {
  2330. return $clause . ' 1 = 1';
  2331. }
  2332. return $clause . implode(' AND ', $out);
  2333. }
  2334. if (is_bool($conditions)) {
  2335. return $clause . (int)$conditions . ' = 1';
  2336. }
  2337. if (empty($conditions) || trim($conditions) === '') {
  2338. return $clause . '1 = 1';
  2339. }
  2340. $clauses = '/^WHERE\\x20|^GROUP\\x20BY\\x20|^HAVING\\x20|^ORDER\\x20BY\\x20/i';
  2341. if (preg_match($clauses, $conditions)) {
  2342. $clause = '';
  2343. }
  2344. $conditions = $this->_quoteFields($conditions);
  2345. return $clause . $conditions;
  2346. }
  2347. /**
  2348. * Creates a WHERE clause by parsing given conditions array. Used by DboSource::conditions().
  2349. *
  2350. * @param array $conditions Array or string of conditions
  2351. * @param boolean $quoteValues If true, values should be quoted
  2352. * @param Model $Model A reference to the Model instance making the query
  2353. * @return string SQL fragment
  2354. */
  2355. public function conditionKeysToString($conditions, $quoteValues = true, Model $Model = null) {
  2356. $out = array();
  2357. $data = $columnType = null;
  2358. $bool = array('and', 'or', 'not', 'and not', 'or not', 'xor', '||', '&&');
  2359. foreach ($conditions as $key => $value) {
  2360. $join = ' AND ';
  2361. $not = null;
  2362. if (is_array($value)) {
  2363. $valueInsert = (
  2364. !empty($value) &&
  2365. (substr_count($key, '?') === count($value) || substr_count($key, ':') === count($value))
  2366. );
  2367. }
  2368. if (is_numeric($key) && empty($value)) {
  2369. continue;
  2370. } elseif (is_numeric($key) && is_string($value)) {
  2371. $out[] = $this->_quoteFields($value);
  2372. } elseif ((is_numeric($key) && is_array($value)) || in_array(strtolower(trim($key)), $bool)) {
  2373. if (in_array(strtolower(trim($key)), $bool)) {
  2374. $join = ' ' . strtoupper($key) . ' ';
  2375. } else {
  2376. $key = $join;
  2377. }
  2378. $value = $this->conditionKeysToString($value, $quoteValues, $Model);
  2379. if (strpos($join, 'NOT') !== false) {
  2380. if (strtoupper(trim($key)) === 'NOT') {
  2381. $key = 'AND ' . trim($key);
  2382. }
  2383. $not = 'NOT ';
  2384. }
  2385. if (empty($value)) {
  2386. continue;
  2387. }
  2388. if (empty($value[1])) {
  2389. if ($not) {
  2390. $out[] = $not . '(' . $value[0] . ')';
  2391. } else {
  2392. $out[] = $value[0];
  2393. }
  2394. } else {
  2395. $out[] = '(' . $not . '(' . implode(') ' . strtoupper($key) . ' (', $value) . '))';
  2396. }
  2397. } else {
  2398. if (is_object($value) && isset($value->type)) {
  2399. if ($value->type === 'identifier') {
  2400. $data .= $this->name($key) . ' = ' . $this->name($value->value);
  2401. } elseif ($value->type === 'expression') {
  2402. if (is_numeric($key)) {
  2403. $data .= $value->value;
  2404. } else {
  2405. $data .= $this->name($key) . ' = ' . $value->value;
  2406. }
  2407. }
  2408. } elseif (is_array($value) && !empty($value) && !$valueInsert) {
  2409. $keys = array_keys($value);
  2410. if ($keys === array_values($keys)) {
  2411. $count = count($value);
  2412. if ($count === 1 && !preg_match('/\s+(?:NOT|\!=)$/', $key)) {
  2413. $data = $this->_quoteFields($key) . ' = (';
  2414. if ($quoteValues) {
  2415. if ($Model !== null) {
  2416. $columnType = $Model->getColumnType($key);
  2417. }
  2418. $data .= implode(', ', $this->value($value, $columnType));
  2419. }
  2420. $data .= ')';
  2421. } else {
  2422. $data = $this->_parseKey($key, $value, $Model);
  2423. }
  2424. } else {
  2425. $ret = $this->conditionKeysToString($value, $quoteValues, $Model);
  2426. if (count($ret) > 1) {
  2427. $data = '(' . implode(') AND (', $ret) . ')';
  2428. } elseif (isset($ret[0])) {
  2429. $data = $ret[0];
  2430. }
  2431. }
  2432. } elseif (is_numeric($key) && !empty($value)) {
  2433. $data = $this->_quoteFields($value);
  2434. } else {
  2435. $data = $this->_parseKey(trim($key), $value, $Model);
  2436. }
  2437. if ($data) {
  2438. $out[] = $data;
  2439. $data = null;
  2440. }
  2441. }
  2442. }
  2443. return $out;
  2444. }
  2445. /**
  2446. * Extracts a Model.field identifier and an SQL condition operator from a string, formats
  2447. * and inserts values, and composes them into an SQL snippet.
  2448. *
  2449. * @param string $key An SQL key snippet containing a field and optional SQL operator
  2450. * @param mixed $value The value(s) to be inserted in the string
  2451. * @param Model $Model Model object initiating the query
  2452. * @return string
  2453. */
  2454. protected function _parseKey($key, $value, Model $Model = null) {
  2455. $operatorMatch = '/^(((' . implode(')|(', $this->_sqlOps);
  2456. $operatorMatch .= ')\\x20?)|<[>=]?(?![^>]+>)\\x20?|[>=!]{1,3}(?!<)\\x20?)/is';
  2457. $bound = (strpos($key, '?') !== false || (is_array($value) && strpos($key, ':') !== false));
  2458. if (strpos($key, ' ') === false) {
  2459. $operator = '=';
  2460. } else {
  2461. list($key, $operator) = explode(' ', trim($key), 2);
  2462. if (!preg_match($operatorMatch, trim($operator)) && strpos($operator, ' ') !== false) {
  2463. $key = $key . ' ' . $operator;
  2464. $split = strrpos($key, ' ');
  2465. $operator = substr($key, $split);
  2466. $key = substr($key, 0, $split);
  2467. }
  2468. }
  2469. $virtual = false;
  2470. $type = null;
  2471. if ($Model !== null) {
  2472. if ($Model->isVirtualField($key)) {
  2473. $key = $this->_quoteFields($Model->getVirtualField($key));
  2474. $virtual = true;
  2475. }
  2476. $type = $Model->getColumnType($key);
  2477. }
  2478. $null = $value === null || (is_array($value) && empty($value));
  2479. if (strtolower($operator) === 'not') {
  2480. $data = $this->conditionKeysToString(
  2481. array($operator => array($key => $value)), true, $Model
  2482. );
  2483. return $data[0];
  2484. }
  2485. $value = $this->value($value, $type);
  2486. if (!$virtual && $key !== '?') {
  2487. $isKey = (
  2488. strpos($key, '(') !== false ||
  2489. strpos($key, ')') !== false ||
  2490. strpos($key, '|') !== false
  2491. );
  2492. $key = $isKey ? $this->_quoteFields($key) : $this->name($key);
  2493. }
  2494. if ($bound) {
  2495. return String::insert($key . ' ' . trim($operator), $value);
  2496. }
  2497. if (!preg_match($operatorMatch, trim($operator))) {
  2498. $operator .= is_array($value) ? ' IN' : ' =';
  2499. }
  2500. $operator = trim($operator);
  2501. if (is_array($value)) {
  2502. $value = implode(', ', $value);
  2503. switch ($operator) {
  2504. case '=':
  2505. $operator = 'IN';
  2506. break;
  2507. case '!=':
  2508. case '<>':
  2509. $operator = 'NOT IN';
  2510. break;
  2511. }
  2512. $value = "({$value})";
  2513. } elseif ($null || $value === 'NULL') {
  2514. switch ($operator) {
  2515. case '=':
  2516. $operator = 'IS';
  2517. break;
  2518. case '!=':
  2519. case '<>':
  2520. $operator = 'IS NOT';
  2521. break;
  2522. }
  2523. }
  2524. if ($virtual) {
  2525. return "({$key}) {$operator} {$value}";
  2526. }
  2527. return "{$key} {$operator} {$value}";
  2528. }
  2529. /**
  2530. * Quotes Model.fields
  2531. *
  2532. * @param string $conditions
  2533. * @return string or false if no match
  2534. */
  2535. protected function _quoteFields($conditions) {
  2536. $start = $end = null;
  2537. $original = $conditions;
  2538. if (!empty($this->startQuote)) {
  2539. $start = preg_quote($this->startQuote);
  2540. }
  2541. if (!empty($this->endQuote)) {
  2542. $end = preg_quote($this->endQuote);
  2543. }
  2544. $conditions = str_replace(array($start, $end), '', $conditions);
  2545. $conditions = preg_replace_callback(
  2546. '/(?:[\'\"][^\'\"\\\]*(?:\\\.[^\'\"\\\]*)*[\'\"])|([a-z0-9_][a-z0-9\\-_]*\\.[a-z0-9_][a-z0-9_\\-]*)/i',
  2547. array(&$this, '_quoteMatchedField'),
  2548. $conditions
  2549. );
  2550. if ($conditions !== null) {
  2551. return $conditions;
  2552. }
  2553. return $original;
  2554. }
  2555. /**
  2556. * Auxiliary function to quote matches `Model.fields` from a preg_replace_callback call
  2557. *
  2558. * @param string $match matched string
  2559. * @return string quoted string
  2560. */
  2561. protected function _quoteMatchedField($match) {
  2562. if (is_numeric($match[0])) {
  2563. return $match[0];
  2564. }
  2565. return $this->name($match[0]);
  2566. }
  2567. /**
  2568. * Returns a limit statement in the correct format for the particular database.
  2569. *
  2570. * @param integer $limit Limit of results returned
  2571. * @param integer $offset Offset from which to start results
  2572. * @return string SQL limit/offset statement
  2573. */
  2574. public function limit($limit, $offset = null) {
  2575. if ($limit) {
  2576. $rt = ' LIMIT';
  2577. if ($offset) {
  2578. $rt .= sprintf(' %u,', $offset);
  2579. }
  2580. $rt .= sprintf(' %u', $limit);
  2581. return $rt;
  2582. }
  2583. return null;
  2584. }
  2585. /**
  2586. * Returns an ORDER BY clause as a string.
  2587. *
  2588. * @param array|string $keys Field reference, as a key (i.e. Post.title)
  2589. * @param string $direction Direction (ASC or DESC)
  2590. * @param Model $Model Model reference (used to look for virtual field)
  2591. * @return string ORDER BY clause
  2592. */
  2593. public function order($keys, $direction = 'ASC', Model $Model = null) {
  2594. if (!is_array($keys)) {
  2595. $keys = array($keys);
  2596. }
  2597. $keys = array_filter($keys);
  2598. $result = array();
  2599. while (!empty($keys)) {
  2600. list($key, $dir) = each($keys);
  2601. array_shift($keys);
  2602. if (is_numeric($key)) {
  2603. $key = $dir;
  2604. $dir = $direction;
  2605. }
  2606. if (is_string($key) && strpos($key, ',') !== false && !preg_match('/\(.+\,.+\)/', $key)) {
  2607. $key = array_map('trim', explode(',', $key));
  2608. }
  2609. if (is_array($key)) {
  2610. //Flatten the array
  2611. $key = array_reverse($key, true);
  2612. foreach ($key as $k => $v) {
  2613. if (is_numeric($k)) {
  2614. array_unshift($keys, $v);
  2615. } else {
  2616. $keys = array($k => $v) + $keys;
  2617. }
  2618. }
  2619. continue;
  2620. } elseif (is_object($key) && isset($key->type) && $key->type === 'expression') {
  2621. $result[] = $key->value;
  2622. continue;
  2623. }
  2624. if (preg_match('/\\x20(ASC|DESC).*/i', $key, $_dir)) {
  2625. $dir = $_dir[0];
  2626. $key = preg_replace('/\\x20(ASC|DESC).*/i', '', $key);
  2627. }
  2628. $key = trim($key);
  2629. if ($Model !== null) {
  2630. if ($Model->isVirtualField($key)) {
  2631. $key = '(' . $this->_quoteFields($Model->getVirtualField($key)) . ')';
  2632. }
  2633. list($alias) = pluginSplit($key);
  2634. if ($alias !== $Model->alias && is_object($Model->{$alias}) && $Model->{$alias}->isVirtualField($key)) {
  2635. $key = '(' . $this->_quoteFields($Model->{$alias}->getVirtualField($key)) . ')';
  2636. }
  2637. }
  2638. if (strpos($key, '.')) {
  2639. $key = preg_replace_callback('/([a-zA-Z0-9_-]{1,})\\.([a-zA-Z0-9_-]{1,})/', array(&$this, '_quoteMatchedField'), $key);
  2640. }
  2641. if (!preg_match('/\s/', $key) && strpos($key, '.') === false) {
  2642. $key = $this->name($key);
  2643. }
  2644. $key .= ' ' . trim($dir);
  2645. $result[] = $key;
  2646. }
  2647. if (!empty($result)) {
  2648. return ' ORDER BY ' . implode(', ', $result);
  2649. }
  2650. return '';
  2651. }
  2652. /**
  2653. * Create a GROUP BY SQL clause.
  2654. *
  2655. * @param string|array $fields Group By fields
  2656. * @param Model $Model
  2657. * @return string Group By clause or null.
  2658. */
  2659. public function group($fields, Model $Model = null) {
  2660. if (empty($fields)) {
  2661. return null;
  2662. }
  2663. if (!is_array($fields)) {
  2664. $fields = array($fields);
  2665. }
  2666. if ($Model !== null) {
  2667. foreach ($fields as $index => $key) {
  2668. if ($Model->isVirtualField($key)) {
  2669. $fields[$index] = '(' . $Model->getVirtualField($key) . ')';
  2670. }
  2671. }
  2672. }
  2673. $fields = implode(', ', $fields);
  2674. return ' GROUP BY ' . $this->_quoteFields($fields);
  2675. }
  2676. /**
  2677. * Disconnects database, kills the connection and says the connection is closed.
  2678. *
  2679. * @return void
  2680. */
  2681. public function close() {
  2682. $this->disconnect();
  2683. }
  2684. /**
  2685. * Checks if the specified table contains any record matching specified SQL
  2686. *
  2687. * @param Model $Model Model to search
  2688. * @param string $sql SQL WHERE clause (condition only, not the "WHERE" part)
  2689. * @return boolean True if the table has a matching record, else false
  2690. */
  2691. public function hasAny(Model $Model, $sql) {
  2692. $sql = $this->conditions($sql);
  2693. $table = $this->fullTableName($Model);
  2694. $alias = $this->alias . $this->name($Model->alias);
  2695. $where = $sql ? "{$sql}" : ' WHERE 1 = 1';
  2696. $id = $Model->escapeField();
  2697. $out = $this->fetchRow("SELECT COUNT({$id}) {$this->alias}count FROM {$table} {$alias}{$where}");
  2698. if (is_array($out)) {
  2699. return $out[0]['count'];
  2700. }
  2701. return false;
  2702. }
  2703. /**
  2704. * Gets the length of a database-native column description, or null if no length
  2705. *
  2706. * @param string $real Real database-layer column type (i.e. "varchar(255)")
  2707. * @return mixed An integer or string representing the length of the column, or null for unknown length.
  2708. */
  2709. public function length($real) {
  2710. if (!preg_match_all('/([\w\s]+)(?:\((\d+)(?:,(\d+))?\))?(\sunsigned)?(\szerofill)?/', $real, $result)) {
  2711. $col = str_replace(array(')', 'unsigned'), '', $real);
  2712. $limit = null;
  2713. if (strpos($col, '(') !== false) {
  2714. list($col, $limit) = explode('(', $col);
  2715. }
  2716. if ($limit !== null) {
  2717. return intval($limit);
  2718. }
  2719. return null;
  2720. }
  2721. $types = array(
  2722. 'int' => 1, 'tinyint' => 1, 'smallint' => 1, 'mediumint' => 1, 'integer' => 1, 'bigint' => 1
  2723. );
  2724. list($real, $type, $length, $offset, $sign) = $result;
  2725. $typeArr = $type;
  2726. $type = $type[0];
  2727. $length = $length[0];
  2728. $offset = $offset[0];
  2729. $isFloat = in_array($type, array('dec', 'decimal', 'float', 'numeric', 'double'));
  2730. if ($isFloat && $offset) {
  2731. return $length . ',' . $offset;
  2732. }
  2733. if (($real[0] == $type) && (count($real) === 1)) {
  2734. return null;
  2735. }
  2736. if (isset($types[$type])) {
  2737. $length += $types[$type];
  2738. if (!empty($sign)) {
  2739. $length--;
  2740. }
  2741. } elseif (in_array($type, array('enum', 'set'))) {
  2742. $length = 0;
  2743. foreach ($typeArr as $key => $enumValue) {
  2744. if ($key === 0) {
  2745. continue;
  2746. }
  2747. $tmpLength = strlen($enumValue);
  2748. if ($tmpLength > $length) {
  2749. $length = $tmpLength;
  2750. }
  2751. }
  2752. }
  2753. return intval($length);
  2754. }
  2755. /**
  2756. * Translates between PHP boolean values and Database (faked) boolean values
  2757. *
  2758. * @param mixed $data Value to be translated
  2759. * @param boolean $quote
  2760. * @return string|boolean Converted boolean value
  2761. */
  2762. public function boolean($data, $quote = false) {
  2763. if ($quote) {
  2764. return !empty($data) ? '1' : '0';
  2765. }
  2766. return !empty($data);
  2767. }
  2768. /**
  2769. * Inserts multiple values into a table
  2770. *
  2771. * @param string $table The table being inserted into.
  2772. * @param array $fields The array of field/column names being inserted.
  2773. * @param array $values The array of values to insert. The values should
  2774. * be an array of rows. Each row should have values keyed by the column name.
  2775. * Each row must have the values in the same order as $fields.
  2776. * @return boolean
  2777. */
  2778. public function insertMulti($table, $fields, $values) {
  2779. $table = $this->fullTableName($table);
  2780. $holder = implode(',', array_fill(0, count($fields), '?'));
  2781. $fields = implode(', ', array_map(array(&$this, 'name'), $fields));
  2782. $pdoMap = array(
  2783. 'integer' => PDO::PARAM_INT,
  2784. 'float' => PDO::PARAM_STR,
  2785. 'boolean' => PDO::PARAM_BOOL,
  2786. 'string' => PDO::PARAM_STR,
  2787. 'text' => PDO::PARAM_STR
  2788. );
  2789. $columnMap = array();
  2790. $sql = "INSERT INTO {$table} ({$fields}) VALUES ({$holder})";
  2791. $statement = $this->_connection->prepare($sql);
  2792. $this->begin();
  2793. foreach ($values[key($values)] as $key => $val) {
  2794. $type = $this->introspectType($val);
  2795. $columnMap[$key] = $pdoMap[$type];
  2796. }
  2797. foreach ($values as $value) {
  2798. $i = 1;
  2799. foreach ($value as $col => $val) {
  2800. $statement->bindValue($i, $val, $columnMap[$col]);
  2801. $i += 1;
  2802. }
  2803. $statement->execute();
  2804. $statement->closeCursor();
  2805. if ($this->fullDebug) {
  2806. $this->logQuery($sql, $value);
  2807. }
  2808. }
  2809. return $this->commit();
  2810. }
  2811. /**
  2812. * Reset a sequence based on the MAX() value of $column. Useful
  2813. * for resetting sequences after using insertMulti().
  2814. *
  2815. * This method should be implemented by datasources that require sequences to be used.
  2816. *
  2817. * @param string $table The name of the table to update.
  2818. * @param string $column The column to use when resetting the sequence value.
  2819. * @return boolean|void success.
  2820. */
  2821. public function resetSequence($table, $column) {
  2822. }
  2823. /**
  2824. * Returns an array of the indexes in given datasource name.
  2825. *
  2826. * @param string $model Name of model to inspect
  2827. * @return array Fields in table. Keys are column and unique
  2828. */
  2829. public function index($model) {
  2830. return array();
  2831. }
  2832. /**
  2833. * Generate a database-native schema for the given Schema object
  2834. *
  2835. * @param CakeSchema $schema An instance of a subclass of CakeSchema
  2836. * @param string $tableName Optional. If specified only the table name given will be generated.
  2837. * Otherwise, all tables defined in the schema are generated.
  2838. * @return string
  2839. */
  2840. public function createSchema($schema, $tableName = null) {
  2841. if (!$schema instanceof CakeSchema) {
  2842. trigger_error(__d('cake_dev', 'Invalid schema object'), E_USER_WARNING);
  2843. return null;
  2844. }
  2845. $out = '';
  2846. foreach ($schema->tables as $curTable => $columns) {
  2847. if (!$tableName || $tableName == $curTable) {
  2848. $cols = $indexes = $tableParameters = array();
  2849. $primary = null;
  2850. $table = $this->fullTableName($curTable);
  2851. $primaryCount = 0;
  2852. foreach ($columns as $col) {
  2853. if (isset($col['key']) && $col['key'] === 'primary') {
  2854. $primaryCount++;
  2855. }
  2856. }
  2857. foreach ($columns as $name => $col) {
  2858. if (is_string($col)) {
  2859. $col = array('type' => $col);
  2860. }
  2861. $isPrimary = isset($col['key']) && $col['key'] === 'primary';
  2862. // Multi-column primary keys are not supported.
  2863. if ($isPrimary && $primaryCount > 1) {
  2864. unset($col['key']);
  2865. $isPrimary = false;
  2866. }
  2867. if ($isPrimary) {
  2868. $primary = $name;
  2869. }
  2870. if ($name !== 'indexes' && $name !== 'tableParameters') {
  2871. $col['name'] = $name;
  2872. if (!isset($col['type'])) {
  2873. $col['type'] = 'string';
  2874. }
  2875. $cols[] = $this->buildColumn($col);
  2876. } elseif ($name === 'indexes') {
  2877. $indexes = array_merge($indexes, $this->buildIndex($col, $table));
  2878. } elseif ($name === 'tableParameters') {
  2879. $tableParameters = array_merge($tableParameters, $this->buildTableParameters($col, $table));
  2880. }
  2881. }
  2882. if (!isset($columns['indexes']['PRIMARY']) && !empty($primary)) {
  2883. $col = array('PRIMARY' => array('column' => $primary, 'unique' => 1));
  2884. $indexes = array_merge($indexes, $this->buildIndex($col, $table));
  2885. }
  2886. $columns = $cols;
  2887. $out .= $this->renderStatement('schema', compact('table', 'columns', 'indexes', 'tableParameters')) . "\n\n";
  2888. }
  2889. }
  2890. return $out;
  2891. }
  2892. /**
  2893. * Generate a alter syntax from CakeSchema::compare()
  2894. *
  2895. * @param mixed $compare
  2896. * @param string $table
  2897. * @return boolean
  2898. */
  2899. public function alterSchema($compare, $table = null) {
  2900. return false;
  2901. }
  2902. /**
  2903. * Generate a "drop table" statement for the given Schema object
  2904. *
  2905. * @param CakeSchema $schema An instance of a subclass of CakeSchema
  2906. * @param string $table Optional. If specified only the table name given will be generated.
  2907. * Otherwise, all tables defined in the schema are generated.
  2908. * @return string
  2909. */
  2910. public function dropSchema(CakeSchema $schema, $table = null) {
  2911. $out = '';
  2912. if ($table && array_key_exists($table, $schema->tables)) {
  2913. return $this->_dropTable($table) . "\n";
  2914. } elseif ($table) {
  2915. return $out;
  2916. }
  2917. foreach (array_keys($schema->tables) as $curTable) {
  2918. $out .= $this->_dropTable($curTable) . "\n";
  2919. }
  2920. return $out;
  2921. }
  2922. /**
  2923. * Generate a "drop table" statement for a single table
  2924. *
  2925. * @param type $table Name of the table to drop
  2926. * @return string Drop table SQL statement
  2927. */
  2928. protected function _dropTable($table) {
  2929. return 'DROP TABLE ' . $this->fullTableName($table) . ";";
  2930. }
  2931. /**
  2932. * Generate a database-native column schema string
  2933. *
  2934. * @param array $column An array structured like the following: array('name' => 'value', 'type' => 'value'[, options]),
  2935. * where options can be 'default', 'length', or 'key'.
  2936. * @return string
  2937. */
  2938. public function buildColumn($column) {
  2939. $name = $type = null;
  2940. extract(array_merge(array('null' => true), $column));
  2941. if (empty($name) || empty($type)) {
  2942. trigger_error(__d('cake_dev', 'Column name or type not defined in schema'), E_USER_WARNING);
  2943. return null;
  2944. }
  2945. if (!isset($this->columns[$type])) {
  2946. trigger_error(__d('cake_dev', 'Column type %s does not exist', $type), E_USER_WARNING);
  2947. return null;
  2948. }
  2949. $real = $this->columns[$type];
  2950. $out = $this->name($name) . ' ' . $real['name'];
  2951. if (isset($column['length'])) {
  2952. $length = $column['length'];
  2953. } elseif (isset($column['limit'])) {
  2954. $length = $column['limit'];
  2955. } elseif (isset($real['length'])) {
  2956. $length = $real['length'];
  2957. } elseif (isset($real['limit'])) {
  2958. $length = $real['limit'];
  2959. }
  2960. if (isset($length)) {
  2961. $out .= '(' . $length . ')';
  2962. }
  2963. if (($column['type'] === 'integer' || $column['type'] === 'float') && isset($column['default']) && $column['default'] === '') {
  2964. $column['default'] = null;
  2965. }
  2966. $out = $this->_buildFieldParameters($out, $column, 'beforeDefault');
  2967. if (isset($column['key']) && $column['key'] === 'primary' && ($type === 'integer' || $type === 'biginteger')) {
  2968. $out .= ' ' . $this->columns['primary_key']['name'];
  2969. } elseif (isset($column['key']) && $column['key'] === 'primary') {
  2970. $out .= ' NOT NULL';
  2971. } elseif (isset($column['default']) && isset($column['null']) && $column['null'] === false) {
  2972. $out .= ' DEFAULT ' . $this->value($column['default'], $type) . ' NOT NULL';
  2973. } elseif (isset($column['default'])) {
  2974. $out .= ' DEFAULT ' . $this->value($column['default'], $type);
  2975. } elseif ($type !== 'timestamp' && !empty($column['null'])) {
  2976. $out .= ' DEFAULT NULL';
  2977. } elseif ($type === 'timestamp' && !empty($column['null'])) {
  2978. $out .= ' NULL';
  2979. } elseif (isset($column['null']) && $column['null'] === false) {
  2980. $out .= ' NOT NULL';
  2981. }
  2982. if ($type === 'timestamp' && isset($column['default']) && strtolower($column['default']) === 'current_timestamp') {
  2983. $out = str_replace(array("'CURRENT_TIMESTAMP'", "'current_timestamp'"), 'CURRENT_TIMESTAMP', $out);
  2984. }
  2985. return $this->_buildFieldParameters($out, $column, 'afterDefault');
  2986. }
  2987. /**
  2988. * Build the field parameters, in a position
  2989. *
  2990. * @param string $columnString The partially built column string
  2991. * @param array $columnData The array of column data.
  2992. * @param string $position The position type to use. 'beforeDefault' or 'afterDefault' are common
  2993. * @return string a built column with the field parameters added.
  2994. */
  2995. protected function _buildFieldParameters($columnString, $columnData, $position) {
  2996. foreach ($this->fieldParameters as $paramName => $value) {
  2997. if (isset($columnData[$paramName]) && $value['position'] == $position) {
  2998. if (isset($value['options']) && !in_array($columnData[$paramName], $value['options'], true)) {
  2999. continue;
  3000. }
  3001. if (isset($value['types']) && !in_array($columnData['type'], $value['types'], true)) {
  3002. continue;
  3003. }
  3004. $val = $columnData[$paramName];
  3005. if ($value['quote']) {
  3006. $val = $this->value($val);
  3007. }
  3008. $columnString .= ' ' . $value['value'] . (empty($value['noVal']) ? $value['join'] . $val : '');
  3009. }
  3010. }
  3011. return $columnString;
  3012. }
  3013. /**
  3014. * Format indexes for create table.
  3015. *
  3016. * @param array $indexes
  3017. * @param string $table
  3018. * @return array
  3019. */
  3020. public function buildIndex($indexes, $table = null) {
  3021. $join = array();
  3022. foreach ($indexes as $name => $value) {
  3023. $out = '';
  3024. if ($name === 'PRIMARY') {
  3025. $out .= 'PRIMARY ';
  3026. $name = null;
  3027. } else {
  3028. if (!empty($value['unique'])) {
  3029. $out .= 'UNIQUE ';
  3030. }
  3031. $name = $this->startQuote . $name . $this->endQuote;
  3032. }
  3033. if (is_array($value['column'])) {
  3034. $out .= 'KEY ' . $name . ' (' . implode(', ', array_map(array(&$this, 'name'), $value['column'])) . ')';
  3035. } else {
  3036. $out .= 'KEY ' . $name . ' (' . $this->name($value['column']) . ')';
  3037. }
  3038. $join[] = $out;
  3039. }
  3040. return $join;
  3041. }
  3042. /**
  3043. * Read additional table parameters
  3044. *
  3045. * @param string $name
  3046. * @return array
  3047. */
  3048. public function readTableParameters($name) {
  3049. $parameters = array();
  3050. if (method_exists($this, 'listDetailedSources')) {
  3051. $currentTableDetails = $this->listDetailedSources($name);
  3052. foreach ($this->tableParameters as $paramName => $parameter) {
  3053. if (!empty($parameter['column']) && !empty($currentTableDetails[$parameter['column']])) {
  3054. $parameters[$paramName] = $currentTableDetails[$parameter['column']];
  3055. }
  3056. }
  3057. }
  3058. return $parameters;
  3059. }
  3060. /**
  3061. * Format parameters for create table
  3062. *
  3063. * @param array $parameters
  3064. * @param string $table
  3065. * @return array
  3066. */
  3067. public function buildTableParameters($parameters, $table = null) {
  3068. $result = array();
  3069. foreach ($parameters as $name => $value) {
  3070. if (isset($this->tableParameters[$name])) {
  3071. if ($this->tableParameters[$name]['quote']) {
  3072. $value = $this->value($value);
  3073. }
  3074. $result[] = $this->tableParameters[$name]['value'] . $this->tableParameters[$name]['join'] . $value;
  3075. }
  3076. }
  3077. return $result;
  3078. }
  3079. /**
  3080. * Guesses the data type of an array
  3081. *
  3082. * @param string $value
  3083. * @return void
  3084. */
  3085. public function introspectType($value) {
  3086. if (!is_array($value)) {
  3087. if (is_bool($value)) {
  3088. return 'boolean';
  3089. }
  3090. if (is_float($value) && floatval($value) === $value) {
  3091. return 'float';
  3092. }
  3093. if (is_int($value) && intval($value) === $value) {
  3094. return 'integer';
  3095. }
  3096. if (is_string($value) && strlen($value) > 255) {
  3097. return 'text';
  3098. }
  3099. return 'string';
  3100. }
  3101. $isAllFloat = $isAllInt = true;
  3102. $containsInt = $containsString = false;
  3103. foreach ($value as $valElement) {
  3104. $valElement = trim($valElement);
  3105. if (!is_float($valElement) && !preg_match('/^[\d]+\.[\d]+$/', $valElement)) {
  3106. $isAllFloat = false;
  3107. } else {
  3108. continue;
  3109. }
  3110. if (!is_int($valElement) && !preg_match('/^[\d]+$/', $valElement)) {
  3111. $isAllInt = false;
  3112. } else {
  3113. $containsInt = true;
  3114. continue;
  3115. }
  3116. $containsString = true;
  3117. }
  3118. if ($isAllFloat) {
  3119. return 'float';
  3120. }
  3121. if ($isAllInt) {
  3122. return 'integer';
  3123. }
  3124. if ($containsInt && !$containsString) {
  3125. return 'integer';
  3126. }
  3127. return 'string';
  3128. }
  3129. /**
  3130. * Writes a new key for the in memory sql query cache
  3131. *
  3132. * @param string $sql SQL query
  3133. * @param mixed $data result of $sql query
  3134. * @param array $params query params bound as values
  3135. * @return void
  3136. */
  3137. protected function _writeQueryCache($sql, $data, $params = array()) {
  3138. if (preg_match('/^\s*select/i', $sql)) {
  3139. $this->_queryCache[$sql][serialize($params)] = $data;
  3140. }
  3141. }
  3142. /**
  3143. * Returns the result for a sql query if it is already cached
  3144. *
  3145. * @param string $sql SQL query
  3146. * @param array $params query params bound as values
  3147. * @return mixed results for query if it is cached, false otherwise
  3148. */
  3149. public function getQueryCache($sql, $params = array()) {
  3150. if (isset($this->_queryCache[$sql]) && preg_match('/^\s*select/i', $sql)) {
  3151. $serialized = serialize($params);
  3152. if (isset($this->_queryCache[$sql][$serialized])) {
  3153. return $this->_queryCache[$sql][$serialized];
  3154. }
  3155. }
  3156. return false;
  3157. }
  3158. /**
  3159. * Used for storing in cache the results of the in-memory methodCache
  3160. */
  3161. public function __destruct() {
  3162. if ($this->_methodCacheChange) {
  3163. Cache::write('method_cache', self::$methodCache, '_cake_core_');
  3164. }
  3165. }
  3166. }