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

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

https://bitbucket.org/ds10/agent-j
PHP | 3156 lines | 2067 code | 264 blank | 825 comment | 560 complexity | 42bd6106f133144a27155edbad83f16c MD5 | raw file
Possible License(s): BSD-3-Clause, Apache-2.0, LGPL-3.0, GPL-2.0, LGPL-2.1, MIT

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

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