PageRenderTime 64ms CodeModel.GetById 21ms RepoModel.GetById 0ms app.codeStats 1ms

/cake/lib/Cake/Model/Datasource/DboSource.php

https://github.com/yasuhiroki/FrameworkBenchmarks
PHP | 3323 lines | 2167 code | 283 blank | 873 comment | 571 complexity | 6c0a60825578d8c722d57a46965212c7 MD5 | raw file
Possible License(s): GPL-2.0, LGPL-2.0, CC0-1.0, BSD-3-Clause, MIT, Apache-2.0

Large files files are truncated, but you can click here to view the full file

  1. <?php
  2. /**
  3. * Dbo Source
  4. *
  5. * PHP 5
  6. *
  7. * CakePHP(tm) : Rapid Development Framework (http://cakephp.org)
  8. * Copyright 2005-2012, Cake Software Foundation, Inc. (http://cakefoundation.org)
  9. *
  10. * Licensed under The MIT License
  11. * Redistributions of files must retain the above copyright notice.
  12. *
  13. * @copyright Copyright 2005-2012, Cake Software Foundation, Inc. (http://cakefoundation.org)
  14. * @link http://cakephp.org CakePHP(tm) Project
  15. * @package Cake.Model.Datasource
  16. * @since CakePHP(tm) v 0.10.0.1076
  17. * @license MIT License (http://www.opensource.org/licenses/mit-license.php)
  18. */
  19. App::uses('DataSource', 'Model/Datasource');
  20. App::uses('String', 'Utility');
  21. App::uses('View', 'View');
  22. /**
  23. * DboSource
  24. *
  25. * Creates DBO-descendant objects from a given db connection configuration
  26. *
  27. * @package Cake.Model.Datasource
  28. */
  29. class DboSource extends DataSource {
  30. /**
  31. * Description string for this Database Data Source.
  32. *
  33. * @var string
  34. */
  35. public $description = "Database Data Source";
  36. /**
  37. * index definition, standard cake, primary, index, unique
  38. *
  39. * @var array
  40. */
  41. public $index = array('PRI' => 'primary', 'MUL' => 'index', 'UNI' => 'unique');
  42. /**
  43. * Database keyword used to assign aliases to identifiers.
  44. *
  45. * @var string
  46. */
  47. public $alias = 'AS ';
  48. /**
  49. * Caches result from query parsing operations. Cached results for both DboSource::name() and
  50. * DboSource::conditions() will be stored here. Method caching uses `md5()`. If you have
  51. * problems with collisions, set DboSource::$cacheMethods to false.
  52. *
  53. * @var array
  54. */
  55. public static $methodCache = array();
  56. /**
  57. * Whether or not to cache the results of DboSource::name() and DboSource::conditions()
  58. * into the memory cache. Set to false to disable the use of the memory cache.
  59. *
  60. * @var boolean
  61. */
  62. public $cacheMethods = true;
  63. /**
  64. * Flag to support nested transactions. If it is set to false, you will be able to use
  65. * the transaction methods (begin/commit/rollback), but just the global transaction will
  66. * be executed.
  67. *
  68. * @var boolean
  69. */
  70. public $useNestedTransactions = false;
  71. /**
  72. * Print full query debug info?
  73. *
  74. * @var boolean
  75. */
  76. public $fullDebug = false;
  77. /**
  78. * String to hold how many rows were affected by the last SQL operation.
  79. *
  80. * @var string
  81. */
  82. public $affected = null;
  83. /**
  84. * Number of rows in current resultset
  85. *
  86. * @var integer
  87. */
  88. public $numRows = null;
  89. /**
  90. * Time the last query took
  91. *
  92. * @var integer
  93. */
  94. public $took = null;
  95. /**
  96. * Result
  97. *
  98. * @var array
  99. */
  100. protected $_result = null;
  101. /**
  102. * Queries count.
  103. *
  104. * @var integer
  105. */
  106. protected $_queriesCnt = 0;
  107. /**
  108. * Total duration of all queries.
  109. *
  110. * @var integer
  111. */
  112. protected $_queriesTime = null;
  113. /**
  114. * Log of queries executed by this DataSource
  115. *
  116. * @var array
  117. */
  118. protected $_queriesLog = array();
  119. /**
  120. * Maximum number of items in query log
  121. *
  122. * This is to prevent query log taking over too much memory.
  123. *
  124. * @var integer Maximum number of queries in the queries log.
  125. */
  126. protected $_queriesLogMax = 200;
  127. /**
  128. * Caches serialized results of executed queries
  129. *
  130. * @var array Cache of results from executed sql queries.
  131. */
  132. protected $_queryCache = array();
  133. /**
  134. * A reference to the physical connection of this DataSource
  135. *
  136. * @var array
  137. */
  138. protected $_connection = null;
  139. /**
  140. * The DataSource configuration key name
  141. *
  142. * @var string
  143. */
  144. public $configKeyName = null;
  145. /**
  146. * The starting character that this DataSource uses for quoted identifiers.
  147. *
  148. * @var string
  149. */
  150. public $startQuote = null;
  151. /**
  152. * The ending character that this DataSource uses for quoted identifiers.
  153. *
  154. * @var string
  155. */
  156. public $endQuote = null;
  157. /**
  158. * The set of valid SQL operations usable in a WHERE statement
  159. *
  160. * @var array
  161. */
  162. protected $_sqlOps = array('like', 'ilike', 'or', 'not', 'in', 'between', 'regexp', 'similar to');
  163. /**
  164. * Indicates the level of nested transactions
  165. *
  166. * @var integer
  167. */
  168. protected $_transactionNesting = 0;
  169. /**
  170. * Default fields that are used by the DBO
  171. *
  172. * @var array
  173. */
  174. protected $_queryDefaults = array(
  175. 'conditions' => array(),
  176. 'fields' => null,
  177. 'table' => null,
  178. 'alias' => null,
  179. 'order' => null,
  180. 'limit' => null,
  181. 'joins' => array(),
  182. 'group' => null,
  183. 'offset' => null
  184. );
  185. /**
  186. * Separator string for virtualField composition
  187. *
  188. * @var string
  189. */
  190. public $virtualFieldSeparator = '__';
  191. /**
  192. * List of table engine specific parameters used on table creating
  193. *
  194. * @var array
  195. */
  196. public $tableParameters = array();
  197. /**
  198. * List of engine specific additional field parameters used on table creating
  199. *
  200. * @var array
  201. */
  202. public $fieldParameters = array();
  203. /**
  204. * Indicates whether there was a change on the cached results on the methods of this class
  205. * This will be used for storing in a more persistent cache
  206. *
  207. * @var boolean
  208. */
  209. protected $_methodCacheChange = false;
  210. /**
  211. * Constructor
  212. *
  213. * @param array $config Array of configuration information for the Datasource.
  214. * @param boolean $autoConnect Whether or not the datasource should automatically connect.
  215. * @throws MissingConnectionException when a connection cannot be made.
  216. */
  217. public function __construct($config = null, $autoConnect = true) {
  218. if (!isset($config['prefix'])) {
  219. $config['prefix'] = '';
  220. }
  221. parent::__construct($config);
  222. $this->fullDebug = Configure::read('debug') > 1;
  223. if (!$this->enabled()) {
  224. throw new MissingConnectionException(array(
  225. 'class' => get_class($this),
  226. 'message' => __d('cake_dev', 'Selected driver is not enabled'),
  227. 'enabled' => false
  228. ));
  229. }
  230. if ($autoConnect) {
  231. $this->connect();
  232. }
  233. }
  234. /**
  235. * Reconnects to database server with optional new settings
  236. *
  237. * @param array $config An array defining the new configuration settings
  238. * @return boolean True on success, false on failure
  239. */
  240. public function reconnect($config = array()) {
  241. $this->disconnect();
  242. $this->setConfig($config);
  243. $this->_sources = null;
  244. return $this->connect();
  245. }
  246. /**
  247. * Disconnects from database.
  248. *
  249. * @return boolean True if the database could be disconnected, else false
  250. */
  251. public function disconnect() {
  252. if ($this->_result instanceof PDOStatement) {
  253. $this->_result->closeCursor();
  254. }
  255. unset($this->_connection);
  256. $this->connected = false;
  257. return true;
  258. }
  259. /**
  260. * Get the underlying connection object.
  261. *
  262. * @return PDO
  263. */
  264. public function getConnection() {
  265. return $this->_connection;
  266. }
  267. /**
  268. * Gets the version string of the database server
  269. *
  270. * @return string The database version
  271. */
  272. public function getVersion() {
  273. return $this->_connection->getAttribute(PDO::ATTR_SERVER_VERSION);
  274. }
  275. /**
  276. * Returns a quoted and escaped string of $data for use in an SQL statement.
  277. *
  278. * @param string $data String to be prepared for use in an SQL statement
  279. * @param string $column The column into which this data will be inserted
  280. * @return string Quoted and escaped data
  281. */
  282. public function value($data, $column = null) {
  283. if (is_array($data) && !empty($data)) {
  284. return array_map(
  285. array(&$this, 'value'),
  286. $data, array_fill(0, count($data), $column)
  287. );
  288. } elseif (is_object($data) && isset($data->type, $data->value)) {
  289. if ($data->type == 'identifier') {
  290. return $this->name($data->value);
  291. } elseif ($data->type == 'expression') {
  292. return $data->value;
  293. }
  294. } elseif (in_array($data, array('{$__cakeID__$}', '{$__cakeForeignKey__$}'), true)) {
  295. return $data;
  296. }
  297. if ($data === null || (is_array($data) && empty($data))) {
  298. return 'NULL';
  299. }
  300. if (empty($column)) {
  301. $column = $this->introspectType($data);
  302. }
  303. switch ($column) {
  304. case 'binary':
  305. return $this->_connection->quote($data, PDO::PARAM_LOB);
  306. case 'boolean':
  307. return $this->_connection->quote($this->boolean($data, true), PDO::PARAM_BOOL);
  308. case 'string':
  309. case 'text':
  310. return $this->_connection->quote($data, PDO::PARAM_STR);
  311. default:
  312. if ($data === '') {
  313. return 'NULL';
  314. }
  315. if (is_float($data)) {
  316. return str_replace(',', '.', strval($data));
  317. }
  318. if ((is_int($data) || $data === '0') || (
  319. is_numeric($data) && strpos($data, ',') === false &&
  320. $data[0] != '0' && strpos($data, 'e') === false)
  321. ) {
  322. return $data;
  323. }
  324. return $this->_connection->quote($data);
  325. }
  326. }
  327. /**
  328. * Returns an object to represent a database identifier in a query. Expression objects
  329. * are not sanitized or escaped.
  330. *
  331. * @param string $identifier A SQL expression to be used as an identifier
  332. * @return stdClass An object representing a database identifier to be used in a query
  333. */
  334. public function identifier($identifier) {
  335. $obj = new stdClass();
  336. $obj->type = 'identifier';
  337. $obj->value = $identifier;
  338. return $obj;
  339. }
  340. /**
  341. * Returns an object to represent a database expression in a query. Expression objects
  342. * are not sanitized or escaped.
  343. *
  344. * @param string $expression An arbitrary SQL expression to be inserted into a query.
  345. * @return stdClass An object representing a database expression to be used in a query
  346. */
  347. public function expression($expression) {
  348. $obj = new stdClass();
  349. $obj->type = 'expression';
  350. $obj->value = $expression;
  351. return $obj;
  352. }
  353. /**
  354. * Executes given SQL statement.
  355. *
  356. * @param string $sql SQL statement
  357. * @param array $params Additional options for the query.
  358. * @return boolean
  359. */
  360. public function rawQuery($sql, $params = array()) {
  361. $this->took = $this->numRows = false;
  362. return $this->execute($sql, $params);
  363. }
  364. /**
  365. * Queries the database with given SQL statement, and obtains some metadata about the result
  366. * (rows affected, timing, any errors, number of rows in resultset). The query is also logged.
  367. * If Configure::read('debug') is set, the log is shown all the time, else it is only shown on errors.
  368. *
  369. * ### Options
  370. *
  371. * - log - Whether or not the query should be logged to the memory log.
  372. *
  373. * @param string $sql SQL statement
  374. * @param array $options
  375. * @param array $params values to be bound to the query
  376. * @return mixed Resource or object representing the result set, or false on failure
  377. */
  378. public function execute($sql, $options = array(), $params = array()) {
  379. $options += array('log' => $this->fullDebug);
  380. $t = microtime(true);
  381. $this->_result = $this->_execute($sql, $params);
  382. if ($options['log']) {
  383. $this->took = round((microtime(true) - $t) * 1000, 0);
  384. $this->numRows = $this->affected = $this->lastAffected();
  385. $this->logQuery($sql, $params);
  386. }
  387. return $this->_result;
  388. }
  389. /**
  390. * Executes given SQL statement.
  391. *
  392. * @param string $sql SQL statement
  393. * @param array $params list of params to be bound to query
  394. * @param array $prepareOptions Options to be used in the prepare statement
  395. * @return mixed PDOStatement if query executes with no problem, true as the result of a successful, false on error
  396. * query returning no rows, such as a CREATE statement, false otherwise
  397. * @throws PDOException
  398. */
  399. protected function _execute($sql, $params = array(), $prepareOptions = array()) {
  400. $sql = trim($sql);
  401. if (preg_match('/^(?:CREATE|ALTER|DROP)\s+(?:TABLE|INDEX)/i', $sql)) {
  402. $statements = array_filter(explode(';', $sql));
  403. if (count($statements) > 1) {
  404. $result = array_map(array($this, '_execute'), $statements);
  405. return array_search(false, $result) === false;
  406. }
  407. }
  408. try {
  409. $query = $this->_connection->prepare($sql, $prepareOptions);
  410. $query->setFetchMode(PDO::FETCH_LAZY);
  411. if (!$query->execute($params)) {
  412. $this->_results = $query;
  413. $query->closeCursor();
  414. return false;
  415. }
  416. if (!$query->columnCount()) {
  417. $query->closeCursor();
  418. if (!$query->rowCount()) {
  419. return true;
  420. }
  421. }
  422. return $query;
  423. } catch (PDOException $e) {
  424. if (isset($query->queryString)) {
  425. $e->queryString = $query->queryString;
  426. } else {
  427. $e->queryString = $sql;
  428. }
  429. throw $e;
  430. }
  431. }
  432. /**
  433. * Returns a formatted error message from previous database operation.
  434. *
  435. * @param PDOStatement $query the query to extract the error from if any
  436. * @return string Error message with error number
  437. */
  438. public function lastError(PDOStatement $query = null) {
  439. if ($query) {
  440. $error = $query->errorInfo();
  441. } else {
  442. $error = $this->_connection->errorInfo();
  443. }
  444. if (empty($error[2])) {
  445. return null;
  446. }
  447. return $error[1] . ': ' . $error[2];
  448. }
  449. /**
  450. * Returns number of affected rows in previous database operation. If no previous operation exists,
  451. * this returns false.
  452. *
  453. * @param mixed $source
  454. * @return integer Number of affected rows
  455. */
  456. public function lastAffected($source = null) {
  457. if ($this->hasResult()) {
  458. return $this->_result->rowCount();
  459. }
  460. return 0;
  461. }
  462. /**
  463. * Returns number of rows in previous resultset. If no previous resultset exists,
  464. * this returns false.
  465. *
  466. * @param mixed $source Not used
  467. * @return integer Number of rows in resultset
  468. */
  469. public function lastNumRows($source = null) {
  470. return $this->lastAffected();
  471. }
  472. /**
  473. * DataSource Query abstraction
  474. *
  475. * @return resource Result resource identifier.
  476. */
  477. public function query() {
  478. $args = func_get_args();
  479. $fields = null;
  480. $order = null;
  481. $limit = null;
  482. $page = null;
  483. $recursive = null;
  484. if (count($args) === 1) {
  485. return $this->fetchAll($args[0]);
  486. } elseif (count($args) > 1 && (strpos($args[0], 'findBy') === 0 || strpos($args[0], 'findAllBy') === 0)) {
  487. $params = $args[1];
  488. if (substr($args[0], 0, 6) === 'findBy') {
  489. $all = false;
  490. $field = Inflector::underscore(substr($args[0], 6));
  491. } else {
  492. $all = true;
  493. $field = Inflector::underscore(substr($args[0], 9));
  494. }
  495. $or = (strpos($field, '_or_') !== false);
  496. if ($or) {
  497. $field = explode('_or_', $field);
  498. } else {
  499. $field = explode('_and_', $field);
  500. }
  501. $off = count($field) - 1;
  502. if (isset($params[1 + $off])) {
  503. $fields = $params[1 + $off];
  504. }
  505. if (isset($params[2 + $off])) {
  506. $order = $params[2 + $off];
  507. }
  508. if (!array_key_exists(0, $params)) {
  509. return false;
  510. }
  511. $c = 0;
  512. $conditions = array();
  513. foreach ($field as $f) {
  514. $conditions[$args[2]->alias . '.' . $f] = $params[$c++];
  515. }
  516. if ($or) {
  517. $conditions = array('OR' => $conditions);
  518. }
  519. if ($all) {
  520. if (isset($params[3 + $off])) {
  521. $limit = $params[3 + $off];
  522. }
  523. if (isset($params[4 + $off])) {
  524. $page = $params[4 + $off];
  525. }
  526. if (isset($params[5 + $off])) {
  527. $recursive = $params[5 + $off];
  528. }
  529. return $args[2]->find('all', compact('conditions', 'fields', 'order', 'limit', 'page', 'recursive'));
  530. } else {
  531. if (isset($params[3 + $off])) {
  532. $recursive = $params[3 + $off];
  533. }
  534. return $args[2]->find('first', compact('conditions', 'fields', 'order', 'recursive'));
  535. }
  536. } else {
  537. if (isset($args[1]) && $args[1] === true) {
  538. return $this->fetchAll($args[0], true);
  539. } elseif (isset($args[1]) && !is_array($args[1])) {
  540. return $this->fetchAll($args[0], false);
  541. } elseif (isset($args[1]) && is_array($args[1])) {
  542. if (isset($args[2])) {
  543. $cache = $args[2];
  544. } else {
  545. $cache = true;
  546. }
  547. return $this->fetchAll($args[0], $args[1], array('cache' => $cache));
  548. }
  549. }
  550. }
  551. /**
  552. * Returns a row from current resultset as an array
  553. *
  554. * @param string $sql Some SQL to be executed.
  555. * @return array The fetched row as an array
  556. */
  557. public function fetchRow($sql = null) {
  558. if (is_string($sql) && strlen($sql) > 5 && !$this->execute($sql)) {
  559. return null;
  560. }
  561. if ($this->hasResult()) {
  562. $this->resultSet($this->_result);
  563. $resultRow = $this->fetchResult();
  564. if (isset($resultRow[0])) {
  565. $this->fetchVirtualField($resultRow);
  566. }
  567. return $resultRow;
  568. } else {
  569. return null;
  570. }
  571. }
  572. /**
  573. * Returns an array of all result rows for a given SQL query.
  574. * Returns false if no rows matched.
  575. *
  576. *
  577. * ### Options
  578. *
  579. * - `cache` - Returns the cached version of the query, if exists and stores the result in cache.
  580. * This is a non-persistent cache, and only lasts for a single request. This option
  581. * defaults to true. If you are directly calling this method, you can disable caching
  582. * by setting $options to `false`
  583. *
  584. * @param string $sql SQL statement
  585. * @param array $params parameters to be bound as values for the SQL statement
  586. * @param array $options additional options for the query.
  587. * @return array Array of resultset rows, or false if no rows matched
  588. */
  589. public function fetchAll($sql, $params = array(), $options = array()) {
  590. if (is_string($options)) {
  591. $options = array('modelName' => $options);
  592. }
  593. if (is_bool($params)) {
  594. $options['cache'] = $params;
  595. $params = array();
  596. }
  597. $options += array('cache' => true);
  598. $cache = $options['cache'];
  599. if ($cache && ($cached = $this->getQueryCache($sql, $params)) !== false) {
  600. return $cached;
  601. }
  602. if ($result = $this->execute($sql, array(), $params)) {
  603. $out = array();
  604. if ($this->hasResult()) {
  605. $first = $this->fetchRow();
  606. if ($first) {
  607. $out[] = $first;
  608. }
  609. while ($item = $this->fetchResult()) {
  610. if (isset($item[0])) {
  611. $this->fetchVirtualField($item);
  612. }
  613. $out[] = $item;
  614. }
  615. }
  616. if (!is_bool($result) && $cache) {
  617. $this->_writeQueryCache($sql, $out, $params);
  618. }
  619. if (empty($out) && is_bool($this->_result)) {
  620. return $this->_result;
  621. }
  622. return $out;
  623. }
  624. return false;
  625. }
  626. /**
  627. * Fetches the next row from the current result set
  628. *
  629. * @return boolean
  630. */
  631. public function fetchResult() {
  632. return false;
  633. }
  634. /**
  635. * Modifies $result array to place virtual fields in model entry where they belongs to
  636. *
  637. * @param array $result Reference to the fetched row
  638. * @return void
  639. */
  640. public function fetchVirtualField(&$result) {
  641. if (isset($result[0]) && is_array($result[0])) {
  642. foreach ($result[0] as $field => $value) {
  643. if (strpos($field, $this->virtualFieldSeparator) === false) {
  644. continue;
  645. }
  646. list($alias, $virtual) = explode($this->virtualFieldSeparator, $field);
  647. if (!ClassRegistry::isKeySet($alias)) {
  648. return;
  649. }
  650. $model = ClassRegistry::getObject($alias);
  651. if ($model->isVirtualField($virtual)) {
  652. $result[$alias][$virtual] = $value;
  653. unset($result[0][$field]);
  654. }
  655. }
  656. if (empty($result[0])) {
  657. unset($result[0]);
  658. }
  659. }
  660. }
  661. /**
  662. * Returns a single field of the first of query results for a given SQL query, or false if empty.
  663. *
  664. * @param string $name Name of the field
  665. * @param string $sql SQL query
  666. * @return mixed Value of field read.
  667. */
  668. public function field($name, $sql) {
  669. $data = $this->fetchRow($sql);
  670. if (empty($data[$name])) {
  671. return false;
  672. }
  673. return $data[$name];
  674. }
  675. /**
  676. * Empties the method caches.
  677. * These caches are used by DboSource::name() and DboSource::conditions()
  678. *
  679. * @return void
  680. */
  681. public function flushMethodCache() {
  682. $this->_methodCacheChange = true;
  683. self::$methodCache = array();
  684. }
  685. /**
  686. * Cache a value into the methodCaches. Will respect the value of DboSource::$cacheMethods.
  687. * Will retrieve a value from the cache if $value is null.
  688. *
  689. * If caching is disabled and a write is attempted, the $value will be returned.
  690. * A read will either return the value or null.
  691. *
  692. * @param string $method Name of the method being cached.
  693. * @param string $key The key name for the cache operation.
  694. * @param mixed $value The value to cache into memory.
  695. * @return mixed Either null on failure, or the value if its set.
  696. */
  697. public function cacheMethod($method, $key, $value = null) {
  698. if ($this->cacheMethods === false) {
  699. return $value;
  700. }
  701. if (empty(self::$methodCache)) {
  702. self::$methodCache = Cache::read('method_cache', '_cake_core_');
  703. }
  704. if ($value === null) {
  705. return (isset(self::$methodCache[$method][$key])) ? self::$methodCache[$method][$key] : null;
  706. }
  707. $this->_methodCacheChange = true;
  708. return self::$methodCache[$method][$key] = $value;
  709. }
  710. /**
  711. * Returns a quoted name of $data for use in an SQL statement.
  712. * Strips fields out of SQL functions before quoting.
  713. *
  714. * Results of this method are stored in a memory cache. This improves performance, but
  715. * because the method uses a hashing algorithm it can have collisions.
  716. * Setting DboSource::$cacheMethods to false will disable the memory cache.
  717. *
  718. * @param mixed $data Either a string with a column to quote. An array of columns to quote or an
  719. * object from DboSource::expression() or DboSource::identifier()
  720. * @return string SQL field
  721. */
  722. public function name($data) {
  723. if (is_object($data) && isset($data->type)) {
  724. return $data->value;
  725. }
  726. if ($data === '*') {
  727. return '*';
  728. }
  729. if (is_array($data)) {
  730. foreach ($data as $i => $dataItem) {
  731. $data[$i] = $this->name($dataItem);
  732. }
  733. return $data;
  734. }
  735. $cacheKey = md5($this->startQuote . $data . $this->endQuote);
  736. if ($return = $this->cacheMethod(__FUNCTION__, $cacheKey)) {
  737. return $return;
  738. }
  739. $data = trim($data);
  740. if (preg_match('/^[\w-]+(?:\.[^ \*]*)*$/', $data)) { // string, string.string
  741. if (strpos($data, '.') === false) { // string
  742. return $this->cacheMethod(__FUNCTION__, $cacheKey, $this->startQuote . $data . $this->endQuote);
  743. }
  744. $items = explode('.', $data);
  745. return $this->cacheMethod(__FUNCTION__, $cacheKey,
  746. $this->startQuote . implode($this->endQuote . '.' . $this->startQuote, $items) . $this->endQuote
  747. );
  748. }
  749. if (preg_match('/^[\w-]+\.\*$/', $data)) { // string.*
  750. return $this->cacheMethod(__FUNCTION__, $cacheKey,
  751. $this->startQuote . str_replace('.*', $this->endQuote . '.*', $data)
  752. );
  753. }
  754. if (preg_match('/^([\w-]+)\((.*)\)$/', $data, $matches)) { // Functions
  755. return $this->cacheMethod(__FUNCTION__, $cacheKey,
  756. $matches[1] . '(' . $this->name($matches[2]) . ')'
  757. );
  758. }
  759. if (
  760. preg_match('/^([\w-]+(\.[\w-]+|\(.*\))*)\s+' . preg_quote($this->alias) . '\s*([\w-]+)$/i', $data, $matches
  761. )) {
  762. return $this->cacheMethod(
  763. __FUNCTION__, $cacheKey,
  764. preg_replace(
  765. '/\s{2,}/', ' ', $this->name($matches[1]) . ' ' . $this->alias . ' ' . $this->name($matches[3])
  766. )
  767. );
  768. }
  769. if (preg_match('/^[\w-_\s]*[\w-_]+/', $data)) {
  770. return $this->cacheMethod(__FUNCTION__, $cacheKey, $this->startQuote . $data . $this->endQuote);
  771. }
  772. return $this->cacheMethod(__FUNCTION__, $cacheKey, $data);
  773. }
  774. /**
  775. * Checks if the source is connected to the database.
  776. *
  777. * @return boolean True if the database is connected, else false
  778. */
  779. public function isConnected() {
  780. return $this->connected;
  781. }
  782. /**
  783. * Checks if the result is valid
  784. *
  785. * @return boolean True if the result is valid else false
  786. */
  787. public function hasResult() {
  788. return is_a($this->_result, 'PDOStatement');
  789. }
  790. /**
  791. * Get the query log as an array.
  792. *
  793. * @param boolean $sorted Get the queries sorted by time taken, defaults to false.
  794. * @param boolean $clear If True the existing log will cleared.
  795. * @return array Array of queries run as an array
  796. */
  797. public function getLog($sorted = false, $clear = true) {
  798. if ($sorted) {
  799. $log = sortByKey($this->_queriesLog, 'took', 'desc', SORT_NUMERIC);
  800. } else {
  801. $log = $this->_queriesLog;
  802. }
  803. if ($clear) {
  804. $this->_queriesLog = array();
  805. }
  806. return array('log' => $log, 'count' => $this->_queriesCnt, 'time' => $this->_queriesTime);
  807. }
  808. /**
  809. * Outputs the contents of the queries log. If in a non-CLI environment the sql_log element
  810. * will be rendered and output. If in a CLI environment, a plain text log is generated.
  811. *
  812. * @param boolean $sorted Get the queries sorted by time taken, defaults to false.
  813. * @return void
  814. */
  815. public function showLog($sorted = false) {
  816. $log = $this->getLog($sorted, false);
  817. if (empty($log['log'])) {
  818. return;
  819. }
  820. if (PHP_SAPI != 'cli') {
  821. $controller = null;
  822. $View = new View($controller, false);
  823. $View->set('logs', array($this->configKeyName => $log));
  824. echo $View->element('sql_dump', array('_forced_from_dbo_' => true));
  825. } else {
  826. foreach ($log['log'] as $k => $i) {
  827. print (($k + 1) . ". {$i['query']}\n");
  828. }
  829. }
  830. }
  831. /**
  832. * Log given SQL query.
  833. *
  834. * @param string $sql SQL statement
  835. * @param array $params Values binded to the query (prepared statements)
  836. * @return void
  837. */
  838. public function logQuery($sql, $params = array()) {
  839. $this->_queriesCnt++;
  840. $this->_queriesTime += $this->took;
  841. $this->_queriesLog[] = array(
  842. 'query' => $sql,
  843. 'params' => $params,
  844. 'affected' => $this->affected,
  845. 'numRows' => $this->numRows,
  846. 'took' => $this->took
  847. );
  848. if (count($this->_queriesLog) > $this->_queriesLogMax) {
  849. array_shift($this->_queriesLog);
  850. }
  851. }
  852. /**
  853. * Gets full table name including prefix
  854. *
  855. * @param Model|string $model Either a Model object or a string table name.
  856. * @param boolean $quote Whether you want the table name quoted.
  857. * @param boolean $schema Whether you want the schema name included.
  858. * @return string Full quoted table name
  859. */
  860. public function fullTableName($model, $quote = true, $schema = true) {
  861. if (is_object($model)) {
  862. $schemaName = $model->schemaName;
  863. $table = $model->tablePrefix . $model->table;
  864. } elseif (!empty($this->config['prefix']) && strpos($model, $this->config['prefix']) !== 0) {
  865. $table = $this->config['prefix'] . strval($model);
  866. } else {
  867. $table = strval($model);
  868. }
  869. if ($schema && !isset($schemaName)) {
  870. $schemaName = $this->getSchemaName();
  871. }
  872. if ($quote) {
  873. if ($schema && !empty($schemaName)) {
  874. if (false == strstr($table, '.')) {
  875. return $this->name($schemaName) . '.' . $this->name($table);
  876. }
  877. }
  878. return $this->name($table);
  879. }
  880. if ($schema && !empty($schemaName)) {
  881. if (false == strstr($table, '.')) {
  882. return $schemaName . '.' . $table;
  883. }
  884. }
  885. return $table;
  886. }
  887. /**
  888. * The "C" in CRUD
  889. *
  890. * Creates new records in the database.
  891. *
  892. * @param Model $model Model object that the record is for.
  893. * @param array $fields An array of field names to insert. If null, $model->data will be
  894. * used to generate field names.
  895. * @param array $values An array of values with keys matching the fields. If null, $model->data will
  896. * be used to generate values.
  897. * @return boolean Success
  898. */
  899. public function create(Model $model, $fields = null, $values = null) {
  900. $id = null;
  901. if (!$fields) {
  902. unset($fields, $values);
  903. $fields = array_keys($model->data);
  904. $values = array_values($model->data);
  905. }
  906. $count = count($fields);
  907. for ($i = 0; $i < $count; $i++) {
  908. $valueInsert[] = $this->value($values[$i], $model->getColumnType($fields[$i]));
  909. $fieldInsert[] = $this->name($fields[$i]);
  910. if ($fields[$i] == $model->primaryKey) {
  911. $id = $values[$i];
  912. }
  913. }
  914. $query = array(
  915. 'table' => $this->fullTableName($model),
  916. 'fields' => implode(', ', $fieldInsert),
  917. 'values' => implode(', ', $valueInsert)
  918. );
  919. if ($this->execute($this->renderStatement('create', $query))) {
  920. if (empty($id)) {
  921. $id = $this->lastInsertId($this->fullTableName($model, false, false), $model->primaryKey);
  922. }
  923. $model->setInsertID($id);
  924. $model->id = $id;
  925. return true;
  926. }
  927. $model->onError();
  928. return false;
  929. }
  930. /**
  931. * The "R" in CRUD
  932. *
  933. * Reads record(s) from the database.
  934. *
  935. * @param Model $model A Model object that the query is for.
  936. * @param array $queryData An array of queryData information containing keys similar to Model::find()
  937. * @param integer $recursive Number of levels of association
  938. * @return mixed boolean false on error/failure. An array of results on success.
  939. */
  940. public function read(Model $model, $queryData = array(), $recursive = null) {
  941. $queryData = $this->_scrubQueryData($queryData);
  942. $null = null;
  943. $array = array('callbacks' => $queryData['callbacks']);
  944. $linkedModels = array();
  945. $bypass = false;
  946. if ($recursive === null && isset($queryData['recursive'])) {
  947. $recursive = $queryData['recursive'];
  948. }
  949. if (!is_null($recursive)) {
  950. $_recursive = $model->recursive;
  951. $model->recursive = $recursive;
  952. }
  953. if (!empty($queryData['fields'])) {
  954. $bypass = true;
  955. $queryData['fields'] = $this->fields($model, null, $queryData['fields']);
  956. } else {
  957. $queryData['fields'] = $this->fields($model);
  958. }
  959. $_associations = $model->associations();
  960. if ($model->recursive == -1) {
  961. $_associations = array();
  962. } elseif ($model->recursive === 0) {
  963. unset($_associations[2], $_associations[3]);
  964. }
  965. foreach ($_associations as $type) {
  966. foreach ($model->{$type} as $assoc => $assocData) {
  967. $linkModel = $model->{$assoc};
  968. $external = isset($assocData['external']);
  969. $linkModel->getDataSource();
  970. if ($model->useDbConfig === $linkModel->useDbConfig) {
  971. if ($bypass) {
  972. $assocData['fields'] = false;
  973. }
  974. if (true === $this->generateAssociationQuery($model, $linkModel, $type, $assoc, $assocData, $queryData, $external, $null)) {
  975. $linkedModels[$type . '/' . $assoc] = true;
  976. }
  977. }
  978. }
  979. }
  980. $query = trim($this->generateAssociationQuery($model, null, null, null, null, $queryData, false, $null));
  981. $resultSet = $this->fetchAll($query, $model->cacheQueries);
  982. if ($resultSet === false) {
  983. $model->onError();
  984. return false;
  985. }
  986. $filtered = array();
  987. if ($queryData['callbacks'] === true || $queryData['callbacks'] === 'after') {
  988. $filtered = $this->_filterResults($resultSet, $model);
  989. }
  990. if ($model->recursive > -1) {
  991. $joined = array();
  992. if (isset($queryData['joins'][0]['alias'])) {
  993. $joined[$model->alias] = (array)Hash::extract($queryData['joins'], '{n}.alias');
  994. }
  995. foreach ($_associations as $type) {
  996. foreach ($model->{$type} as $assoc => $assocData) {
  997. $linkModel = $model->{$assoc};
  998. if (!isset($linkedModels[$type . '/' . $assoc])) {
  999. if ($model->useDbConfig === $linkModel->useDbConfig) {
  1000. $db = $this;
  1001. } else {
  1002. $db = ConnectionManager::getDataSource($linkModel->useDbConfig);
  1003. }
  1004. } elseif ($model->recursive > 1 && ($type === 'belongsTo' || $type === 'hasOne')) {
  1005. $db = $this;
  1006. }
  1007. if (isset($db) && method_exists($db, 'queryAssociation')) {
  1008. $stack = array($assoc);
  1009. $stack['_joined'] = $joined;
  1010. $db->queryAssociation($model, $linkModel, $type, $assoc, $assocData, $array, true, $resultSet, $model->recursive - 1, $stack);
  1011. unset($db);
  1012. if ($type === 'hasMany') {
  1013. $filtered[] = $assoc;
  1014. }
  1015. }
  1016. }
  1017. }
  1018. if ($queryData['callbacks'] === true || $queryData['callbacks'] === 'after') {
  1019. $this->_filterResults($resultSet, $model, $filtered);
  1020. }
  1021. }
  1022. if (!is_null($recursive)) {
  1023. $model->recursive = $_recursive;
  1024. }
  1025. return $resultSet;
  1026. }
  1027. /**
  1028. * Passes association results thru afterFind filters of corresponding model
  1029. *
  1030. * @param array $results Reference of resultset to be filtered
  1031. * @param Model $model Instance of model to operate against
  1032. * @param array $filtered List of classes already filtered, to be skipped
  1033. * @return array Array of results that have been filtered through $model->afterFind
  1034. */
  1035. protected function _filterResults(&$results, Model $model, $filtered = array()) {
  1036. $current = reset($results);
  1037. if (!is_array($current)) {
  1038. return array();
  1039. }
  1040. $keys = array_diff(array_keys($current), $filtered, array($model->alias));
  1041. $filtering = array();
  1042. foreach ($keys as $className) {
  1043. if (!isset($model->{$className}) || !is_object($model->{$className})) {
  1044. continue;
  1045. }
  1046. $linkedModel = $model->{$className};
  1047. $filtering[] = $className;
  1048. foreach ($results as $key => &$result) {
  1049. $data = $linkedModel->afterFind(array(array($className => $result[$className])), false);
  1050. if (isset($data[0][$className])) {
  1051. $result[$className] = $data[0][$className];
  1052. } else {
  1053. unset($results[$key]);
  1054. }
  1055. }
  1056. }
  1057. return $filtering;
  1058. }
  1059. /**
  1060. * Queries associations. Used to fetch results on recursive models.
  1061. *
  1062. * @param Model $model Primary Model object
  1063. * @param Model $linkModel Linked model that
  1064. * @param string $type Association type, one of the model association types ie. hasMany
  1065. * @param string $association
  1066. * @param array $assocData
  1067. * @param array $queryData
  1068. * @param boolean $external Whether or not the association query is on an external datasource.
  1069. * @param array $resultSet Existing results
  1070. * @param integer $recursive Number of levels of association
  1071. * @param array $stack
  1072. * @return mixed
  1073. * @throws CakeException when results cannot be created.
  1074. */
  1075. public function queryAssociation(Model $model, &$linkModel, $type, $association, $assocData, &$queryData, $external, &$resultSet, $recursive, $stack) {
  1076. if (isset($stack['_joined'])) {
  1077. $joined = $stack['_joined'];
  1078. unset($stack['_joined']);
  1079. }
  1080. if ($query = $this->generateAssociationQuery($model, $linkModel, $type, $association, $assocData, $queryData, $external, $resultSet)) {
  1081. if (!is_array($resultSet)) {
  1082. throw new CakeException(__d('cake_dev', 'Error in Model %s', get_class($model)));
  1083. }
  1084. if ($type === 'hasMany' && empty($assocData['limit']) && !empty($assocData['foreignKey'])) {
  1085. $ins = $fetch = array();
  1086. foreach ($resultSet as &$result) {
  1087. if ($in = $this->insertQueryData('{$__cakeID__$}', $result, $association, $assocData, $model, $linkModel, $stack)) {
  1088. $ins[] = $in;
  1089. }
  1090. }
  1091. if (!empty($ins)) {
  1092. $ins = array_unique($ins);
  1093. $fetch = $this->fetchAssociated($model, $query, $ins);
  1094. }
  1095. if (!empty($fetch) && is_array($fetch)) {
  1096. if ($recursive > 0) {
  1097. foreach ($linkModel->associations() as $type1) {
  1098. foreach ($linkModel->{$type1} as $assoc1 => $assocData1) {
  1099. $deepModel = $linkModel->{$assoc1};
  1100. $tmpStack = $stack;
  1101. $tmpStack[] = $assoc1;
  1102. if ($linkModel->useDbConfig === $deepModel->useDbConfig) {
  1103. $db = $this;
  1104. } else {
  1105. $db = ConnectionManager::getDataSource($deepModel->useDbConfig);
  1106. }
  1107. $db->queryAssociation($linkModel, $deepModel, $type1, $assoc1, $assocData1, $queryData, true, $fetch, $recursive - 1, $tmpStack);
  1108. }
  1109. }
  1110. }
  1111. }
  1112. if ($queryData['callbacks'] === true || $queryData['callbacks'] === 'after') {
  1113. $this->_filterResults($fetch, $model);
  1114. }
  1115. return $this->_mergeHasMany($resultSet, $fetch, $association, $model, $linkModel);
  1116. } elseif ($type === 'hasAndBelongsToMany') {
  1117. $ins = $fetch = array();
  1118. foreach ($resultSet as &$result) {
  1119. if ($in = $this->insertQueryData('{$__cakeID__$}', $result, $association, $assocData, $model, $linkModel, $stack)) {
  1120. $ins[] = $in;
  1121. }
  1122. }
  1123. if (!empty($ins)) {
  1124. $ins = array_unique($ins);
  1125. if (count($ins) > 1) {
  1126. $query = str_replace('{$__cakeID__$}', '(' . implode(', ', $ins) . ')', $query);
  1127. $query = str_replace('= (', 'IN (', $query);
  1128. } else {
  1129. $query = str_replace('{$__cakeID__$}', $ins[0], $query);
  1130. }
  1131. $query = str_replace(' WHERE 1 = 1', '', $query);
  1132. }
  1133. $foreignKey = $model->hasAndBelongsToMany[$association]['foreignKey'];
  1134. $joinKeys = array($foreignKey, $model->hasAndBelongsToMany[$association]['associationForeignKey']);
  1135. list($with, $habtmFields) = $model->joinModel($model->hasAndBelongsToMany[$association]['with'], $joinKeys);
  1136. $habtmFieldsCount = count($habtmFields);
  1137. $q = $this->insertQueryData($query, null, $association, $assocData, $model, $linkModel, $stack);
  1138. if ($q !== false) {
  1139. $fetch = $this->fetchAll($q, $model->cacheQueries);
  1140. } else {
  1141. $fetch = null;
  1142. }
  1143. }
  1144. $modelAlias = $model->alias;
  1145. $modelPK = $model->primaryKey;
  1146. foreach ($resultSet as &$row) {
  1147. if ($type !== 'hasAndBelongsToMany') {
  1148. $q = $this->insertQueryData($query, $row, $association, $assocData, $model, $linkModel, $stack);
  1149. $fetch = null;
  1150. if ($q !== false) {
  1151. $joinedData = array();
  1152. if (($type === 'belongsTo' || $type === 'hasOne') && isset($row[$linkModel->alias], $joined[$model->alias]) && in_array($linkModel->alias, $joined[$model->alias])) {
  1153. $joinedData = Hash::filter($row[$linkModel->alias]);
  1154. if (!empty($joinedData)) {
  1155. $fetch[0] = array($linkModel->alias => $row[$linkModel->alias]);
  1156. }
  1157. } else {
  1158. $fetch = $this->fetchAll($q, $model->cacheQueries);
  1159. }
  1160. }
  1161. }
  1162. $selfJoin = $linkModel->name === $model->name;
  1163. if (!empty($fetch) && is_array($fetch)) {
  1164. if ($recursive > 0) {
  1165. foreach ($linkModel->associations() as $type1) {
  1166. foreach ($linkModel->{$type1} as $assoc1 => $assocData1) {
  1167. $deepModel = $linkModel->{$assoc1};
  1168. if ($type1 === 'belongsTo' || ($deepModel->alias === $modelAlias && $type === 'belongsTo') || ($deepModel->alias !== $modelAlias)) {
  1169. $tmpStack = $stack;
  1170. $tmpStack[] = $assoc1;
  1171. if ($linkModel->useDbConfig == $deepModel->useDbConfig) {
  1172. $db = $this;
  1173. } else {
  1174. $db = ConnectionManager::getDataSource($deepModel->useDbConfig);
  1175. }
  1176. $db->queryAssociation($linkModel, $deepModel, $type1, $assoc1, $assocData1, $queryData, true, $fetch, $recursive - 1, $tmpStack);
  1177. }
  1178. }
  1179. }
  1180. }
  1181. if ($type === 'hasAndBelongsToMany') {
  1182. $merge = array();
  1183. foreach ($fetch as $data) {
  1184. if (isset($data[$with]) && $data[$with][$foreignKey] === $row[$modelAlias][$modelPK]) {
  1185. if ($habtmFieldsCount <= 2) {
  1186. unset($data[$with]);
  1187. }
  1188. $merge[] = $data;
  1189. }
  1190. }
  1191. if (empty($merge) && !isset($row[$association])) {
  1192. $row[$association] = $merge;
  1193. } else {
  1194. $this->_mergeAssociation($row, $merge, $association, $type);
  1195. }
  1196. } else {
  1197. $this->_mergeAssociation($row, $fetch, $association, $type, $selfJoin);
  1198. }
  1199. if (isset($row[$association])) {
  1200. $row[$association] = $linkModel->afterFind($row[$association], false);
  1201. }
  1202. } else {
  1203. $tempArray[0][$association] = false;
  1204. $this->_mergeAssociation($row, $tempArray, $association, $type, $selfJoin);
  1205. }
  1206. }
  1207. }
  1208. }
  1209. /**
  1210. * A more efficient way to fetch associations. Woohoo!
  1211. *
  1212. * @param Model $model Primary model object
  1213. * @param string $query Association query
  1214. * @param array $ids Array of IDs of associated records
  1215. * @return array Association results
  1216. */
  1217. public function fetchAssociated(Model $model, $query, $ids) {
  1218. $query = str_replace('{$__cakeID__$}', implode(', ', $ids), $query);
  1219. if (count($ids) > 1) {
  1220. $query = str_replace('= (', 'IN (', $query);
  1221. }
  1222. return $this->fetchAll($query, $model->cacheQueries);
  1223. }
  1224. /**
  1225. * mergeHasMany - Merge the results of hasMany relations.
  1226. *
  1227. *
  1228. * @param array $resultSet Data to merge into
  1229. * @param array $merge Data to merge
  1230. * @param string $association Name of Model being Merged
  1231. * @param Model $model Model being merged onto
  1232. * @param Model $linkModel Model being merged
  1233. * @return void
  1234. */
  1235. protected function _mergeHasMany(&$resultSet, $merge, $association, $model, $linkModel) {
  1236. $modelAlias = $model->alias;
  1237. $modelPK = $model->primaryKey;
  1238. $modelFK = $model->hasMany[$association]['foreignKey'];
  1239. foreach ($resultSet as &$result) {
  1240. if (!isset($result[$modelAlias])) {
  1241. continue;
  1242. }
  1243. $merged = array();
  1244. foreach ($merge as $data) {
  1245. if ($result[$modelAlias][$modelPK] === $data[$association][$modelFK]) {
  1246. if (count($data) > 1) {
  1247. $data = array_merge($data[$association], $data);
  1248. unset($data[$association]);
  1249. foreach ($data as $key => $name) {
  1250. if (is_numeric($key)) {
  1251. $data[$association][] = $name;
  1252. unset($data[$key]);
  1253. }
  1254. }
  1255. $merged[] = $data;
  1256. } else {
  1257. $merged[] = $data[$association];
  1258. }
  1259. }
  1260. }
  1261. $result = Hash::mergeDiff($result, array($association => $merged));
  1262. }
  1263. }
  1264. /**
  1265. * Merge association of merge into data
  1266. *
  1267. * @param array $data
  1268. * @param array $merge
  1269. * @param string $association
  1270. * @param string $type
  1271. * @param boolean $selfJoin
  1272. * @return void
  1273. */
  1274. protected function _mergeAssociation(&$data, &$merge, $association, $type, $selfJoin = false) {
  1275. if (isset($merge[0]) && !isset($merge[0][$association])) {
  1276. $association = Inflector::pluralize($association);
  1277. }
  1278. if ($type === 'belongsTo' || $type === 'hasOne') {
  1279. if (isset($merge[$association])) {
  1280. $data[$association] = $merge[$association][0];
  1281. } else {
  1282. if (count($merge[0][$association]) > 1) {
  1283. foreach ($merge[0] as $assoc => $data2) {
  1284. if ($assoc !== $association) {
  1285. $merge[0][$association][$assoc] = $data2;
  1286. }
  1287. }
  1288. }
  1289. if (!isset($data[$association])) {
  1290. $data[$association] = array();
  1291. if ($merge[0][$association]) {
  1292. $data[$association] = $merge[0][$association];
  1293. }
  1294. } else {
  1295. if (is_array($merge[0][$association])) {
  1296. foreach ($data[$association] as $k => $v) {
  1297. if (!is_array($v)) {
  1298. $dataAssocTmp[$k] = $v;
  1299. }
  1300. }
  1301. foreach ($merge[0][$association] as $k => $v) {
  1302. if (!is_array($v)) {
  1303. $mergeAssocTmp[$k] = $v;
  1304. }
  1305. }
  1306. $dataKeys = array_keys($data);
  1307. $mergeKeys = array_keys($merge[0]);
  1308. if ($mergeKeys[0] === $dataKeys[0] || $mergeKeys === $dataKeys) {
  1309. $data[$association][$association] = $merge[0][$association];
  1310. } else {
  1311. $diff = Hash::diff($dataAssocTmp, $mergeAssocTmp);
  1312. $data[$association] = array_merge($merge[0][$association], $diff);
  1313. }
  1314. } elseif ($selfJoin && array_key_exists($association, $merge[0])) {
  1315. $data[$association] = array_merge($data[$association], array($association => array()));
  1316. }
  1317. }
  1318. }
  1319. } else {
  1320. if (isset($merge[0][$association]) && $merge[0][$association] === false) {
  1321. if (!isset($data[$association])) {
  1322. $data[$association] = array();
  1323. }
  1324. } else {
  1325. foreach ($merge as $row) {
  1326. $insert = array();
  1327. if (count($row) === 1) {
  1328. $insert = $row[$association];
  1329. } elseif (isset($row[$association])) {
  1330. $insert = array_merge($row[$association], $row);
  1331. unset($insert[$association]);
  1332. }
  1333. if (empty($data[$association]) || (isset($data[$association]) && !in_array($insert, $data[$association], true))) {
  1334. $data[$association][] = $insert;
  1335. }
  1336. }
  1337. }
  1338. }
  1339. }
  1340. /**
  1341. * Generates an array representing a query or part of a query from a single model or two associated models
  1342. *
  1343. * @param Model $model
  1344. * @param Model $linkModel
  1345. * @param string $type
  1346. * @param string $association
  1347. * @param array $assocData
  1348. * @param array $queryData
  1349. * @param boolean $external
  1350. * @param array $resultSet
  1351. * @return mixed
  1352. */
  1353. public function generateAssociationQuery(Model $model, $linkModel, $type, $association, $assocData, &$queryData, $external, &$resultSet) {
  1354. $queryData = $this->_scrubQueryData($queryData);
  1355. $assocData = $this->_scrubQueryData($assocData);
  1356. $modelAlias = $model->alias;
  1357. if (empty($queryData['fields'])) {
  1358. $queryData['fields'] = $this->fields($model, $modelAlias);
  1359. } elseif (!empty($model->hasMany) && $model->recursive > -1) {
  1360. $assocFields = $this->fields($model, $modelAlias, array("{$modelAlias}.{$model->primaryKey}"));
  1361. $passedFields = $queryData['fields'];
  1362. if (count($passedFields) === 1) {
  1363. if (strpos($passedFields[0], $assocFields[0]) === false && !preg_match('/^[a-z]+\(/i', $passedFields[0])) {
  1364. $queryData['fields'] = array_merge($passedFields, $assocFields);
  1365. } else {
  1366. $queryData['fields'] = $passedFields;
  1367. }
  1368. } else {
  1369. $queryData['fields'] = array_merge($passedFields, $assocFields);
  1370. }
  1371. unset($assocFields, $passedFields);
  1372. }
  1373. if ($linkModel === null) {
  1374. return $this->buildStatement(
  1375. array(
  1376. 'fields' => array_unique($queryData['fields']),
  1377. 'table' => $this->fullTableName($model),
  1378. 'alias' => $modelAlias,
  1379. 'limit' => $queryData['limit'],
  1380. 'offset' => $queryData['offset'],
  1381. 'joins' => $queryData['joins'],
  1382. 'conditions' => $queryData['conditions'],
  1383. 'order' => $queryData['order'],
  1384. 'group' => $queryData['group']
  1385. ),
  1386. $model
  1387. );
  1388. }
  1389. if ($external && !empty($assocData['finderQuery'])) {
  1390. return $assocData['finderQuery'];
  1391. }
  1392. $self = $model->name === $linkModel->name;
  1393. $fields = array();
  1394. if ($external || (in_array($type, array('hasOne', 'belongsTo')) && $assocData['fields'] !== false)) {
  1395. $fields = $this->fields($linkModel, $association, $assocData['fields']);
  1396. }
  1397. if (empty($assocData['offset']) && !empty($assocData['page'])) {
  1398. $assocData['offset'] = ($assocData['page'] - 1) * $assocData['limit'];
  1399. }
  1400. $assocData['limit'] = $this->limit($assocData['limit'], $assocData['offset']);
  1401. switch ($type) {
  1402. case 'hasOne':
  1403. case 'belongsTo':
  1404. $conditions = $this->_mergeConditions(
  1405. $assocData['conditions'],
  1406. $this->getConstraint($type, $model, $linkModel, $association, array_merge($assocData, compact('external', 'self')))
  1407. );
  1408. if (!$self && $external) {
  1409. foreach ($conditions as $key => $condition) {
  1410. if (is_numeric($key) && strpos($condition, $modelAlias . '.') !== false) {
  1411. unset($conditions[$key]);
  1412. }
  1413. }
  1414. }
  1415. if ($external) {
  1416. $query = array_merge($assocData, array(
  1417. 'conditions' => $conditions,
  1418. 'table' => $this->fullTableName($linkModel),
  1419. 'fields' => $fields,
  1420. 'alias' => $association,
  1421. 'group' => null
  1422. ));
  1423. $query += array('order' => $assocData['order'], 'limit' => $assocData['limit']);
  1424. } else {
  1425. $join = array(
  1426. 'table' => $linkModel,
  1427. 'alias' => $association,
  1428. 'type' => isset($assocData['type']) ? $assocData['type'] : 'LEFT',
  1429. 'conditions' => trim($this->conditions($conditions, true, false, $model))
  1430. );
  1431. $queryData['fields'] = array_merge($queryData['fields'], $fields);
  1432. if (!empty($assocData['order'])) {
  1433. $queryData['order'][] = $assocData['order'];
  1434. }
  1435. if (!in_array($join, $queryData['joins'])) {
  1436. $queryData['joins'][] = $join;
  1437. }
  1438. return true;
  1439. }
  1440. break;
  1441. case 'hasMany':
  1442. $assocData['fields'] = $this->fields($linkModel, $association, $assocData['fields']);
  1443. if (!empty($assocData['foreignKey'])) {
  1444. $assocData['fields'] = array_merge($assocData['fields'], $this->fields($linkModel, $association, array("{$association}.{$assocData['foreignKey']}")));
  1445. }
  1446. $query = array(
  1447. 'conditions' => $this->_mergeConditions($this->getConstraint('hasMany', $model, $linkModel, $association, $assocData), $assocData['conditions']),
  1448. 'fields' => array_unique($assocData['fields']),
  1449. 'table' => $this->fullTableName($linkModel),
  1450. 'alias' => $association,
  1451. 'order' => $assocData['order'],
  1452. 'limit' => $assocData['limit'],
  1453. 'group' => null
  1454. );
  1455. break;
  1456. case 'hasAndBelongsToMany':
  1457. $joinFields = array();
  1458. $joinAssoc = null;
  1459. if (isset($assocData['with']) && !empty($assocData['with'])) {
  1460. $joinKeys = array($assocData['foreignKey'], $assocData['associationForeignKey']);
  1461. list($with, $joinFields) = $model->joinModel($assocData['with'], $joinKeys);
  1462. $joinTbl = $model->{$with};
  1463. $joinAlias = $joinTbl;
  1464. if (is_array($joinFields) && !empty($joinFields)) {
  1465. $joinAssoc = $joinAlias = $model->{$with}->alias;
  1466. $joinFields = $this->fields($model->{$with}, $joinAlias, $joinFields);
  1467. } else {
  1468. $joinFields = array();
  1469. }
  1470. } else {
  1471. $joinTbl = $assocData['joinTable'];
  1472. $joinAlias = $this->fullTableName($assocData['joinTable']);
  1473. }
  1474. $query = array(
  1475. 'conditions' => $assocData['conditions'],
  1476. 'limit' => $assocData['limit'],
  1477. 'table' => $this->fullTableName($linkModel),
  1478. 'alias' => $association,
  1479. 'fields' => array_merge($this->fields($linkModel, $association, $assocData['fields']), $joinFields),
  1480. 'order' => $assocData['order'],
  1481. 'group' => null,
  1482. 'joins' => array(array(
  1483. 'table' => $joinTbl,
  1484. 'alias' => $joinAssoc,
  1485. 'conditions' => $this->getConstraint('hasAndBelongsToMany', $model, $linkModel, $joinAlias, $assocData, $association)
  1486. ))
  1487. );
  1488. break;
  1489. }
  1490. if (isset($query)) {
  1491. return $this->buildStatement($query, $model);
  1492. }
  1493. return null;
  1494. }
  1495. /**
  1496. * Returns a conditions array for the constraint between two models
  1497. *
  1498. * @param string $type Association type
  1499. * @param Model $model Model object
  1500. * @param string $linkModel
  1501. * @param string $alias
  1502. * @param array $assoc
  1503. * @param string $alias2
  1504. * @return array Conditions array defining the constraint between $model and $association
  1505. */
  1506. public function getConstraint($type, $model, $linkModel, $alias, $assoc, $alias2 = null) {
  1507. $assoc += array('external' => false, 'self' => false);
  1508. if (empty($assoc['foreignKey'])) {
  1509. return array();
  1510. }
  1511. switch (true) {
  1512. case ($assoc['external'] && $type === 'hasOne'):
  1513. return array("{$alias}.{$assoc['foreignKey']}" => '{$__cakeID__$}');
  1514. case ($assoc['external'] && $type === 'belongsTo'):
  1515. return array("{$alias}.{$linkModel->primaryKey}" => '{$__cakeForeignKey__$}');
  1516. case (!$assoc['external'] && $type === 'hasOne'):
  1517. return array("{$alias}.{$assoc['foreignKey']}" => $this->identifier("{$model->alias}.{$model->primaryKey}"));
  1518. case (!$assoc['external'] && $type === 'belongsTo'):
  1519. return array("{$model->alias}.{$assoc['foreignKey']}" => $this->identifier("{$alias}.{$linkModel->primaryKey}"));
  1520. case ($type === 'hasMany'):
  1521. return array("{$alias}.{$assoc['foreignKey']}" => array('{$__cakeID__$}'));
  1522. case ($type === 'hasAndBelongsToMany'):
  1523. return array(
  1524. array("{$alias}.{$assoc['foreignKey']}" => '{$__cakeID__$}'),
  1525. array("{$alias}.{$assoc['associationForeignKey']}" => $this->identifier("{$alias2}.{$linkModel->primaryKey}"))
  1526. );
  1527. }
  1528. return array();
  1529. }
  1530. /**
  1531. * Builds and generates a JOIN statement from an array. Handles final clean-up before conversion.
  1532. *
  1533. * @param array $join An array defining a JOIN statement in a query
  1534. * @return string An SQL JOIN statement to be used in a query
  1535. * @see DboSource::renderJoinStatement()
  1536. * @see DboSource::buildStatement()
  1537. */
  1538. public function buildJoinStatement($join) {
  1539. $data = array_merge(array(
  1540. 'type' => null,
  1541. 'alias' => null,
  1542. 'table' => 'join_table',
  1543. 'conditions' => array()
  1544. ), $join);
  1545. if (!empty($data['alias'])) {
  1546. $data['alias'] = $this->alias . $this->name($data['alias']);
  1547. }
  1548. if (!empty($data['conditions'])) {
  1549. $data['conditions'] = trim($this->conditions($data['conditions'], true, false

Large files files are truncated, but you can click here to view the full file