PageRenderTime 64ms CodeModel.GetById 22ms RepoModel.GetById 1ms app.codeStats 1ms

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

https://bitbucket.org/pyroka/hms
PHP | 3268 lines | 2133 code | 279 blank | 856 comment | 571 complexity | 1058254005214d775b281cdce7cf22ac MD5 | raw file
Possible License(s): LGPL-2.1

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. 'enabled' => false
  227. ));
  228. }
  229. if ($autoConnect) {
  230. $this->connect();
  231. }
  232. }
  233. /**
  234. * Reconnects to database server with optional new settings
  235. *
  236. * @param array $config An array defining the new configuration settings
  237. * @return boolean True on success, false on failure
  238. */
  239. public function reconnect($config = array()) {
  240. $this->disconnect();
  241. $this->setConfig($config);
  242. $this->_sources = null;
  243. return $this->connect();
  244. }
  245. /**
  246. * Disconnects from database.
  247. *
  248. * @return boolean True if the database could be disconnected, else false
  249. */
  250. public function disconnect() {
  251. if ($this->_result instanceof PDOStatement) {
  252. $this->_result->closeCursor();
  253. }
  254. unset($this->_connection);
  255. $this->connected = false;
  256. return true;
  257. }
  258. /**
  259. * Get the underlying connection object.
  260. *
  261. * @return PDO
  262. */
  263. public function getConnection() {
  264. return $this->_connection;
  265. }
  266. /**
  267. * Gets the version string of the database server
  268. *
  269. * @return string The database version
  270. */
  271. public function getVersion() {
  272. return $this->_connection->getAttribute(PDO::ATTR_SERVER_VERSION);
  273. }
  274. /**
  275. * Returns a quoted and escaped string of $data for use in an SQL statement.
  276. *
  277. * @param string $data String to be prepared for use in an SQL statement
  278. * @param string $column The column into which this data will be inserted
  279. * @return string Quoted and escaped data
  280. */
  281. public function value($data, $column = null) {
  282. if (is_array($data) && !empty($data)) {
  283. return array_map(
  284. array(&$this, 'value'),
  285. $data, array_fill(0, count($data), $column)
  286. );
  287. } elseif (is_object($data) && isset($data->type, $data->value)) {
  288. if ($data->type == 'identifier') {
  289. return $this->name($data->value);
  290. } elseif ($data->type == 'expression') {
  291. return $data->value;
  292. }
  293. } elseif (in_array($data, array('{$__cakeID__$}', '{$__cakeForeignKey__$}'), true)) {
  294. return $data;
  295. }
  296. if ($data === null || (is_array($data) && empty($data))) {
  297. return 'NULL';
  298. }
  299. if (empty($column)) {
  300. $column = $this->introspectType($data);
  301. }
  302. switch ($column) {
  303. case 'binary':
  304. return $this->_connection->quote($data, PDO::PARAM_LOB);
  305. break;
  306. case 'boolean':
  307. return $this->_connection->quote($this->boolean($data, true), PDO::PARAM_BOOL);
  308. break;
  309. case 'string':
  310. case 'text':
  311. return $this->_connection->quote($data, PDO::PARAM_STR);
  312. default:
  313. if ($data === '') {
  314. return 'NULL';
  315. }
  316. if (is_float($data)) {
  317. return str_replace(',', '.', strval($data));
  318. }
  319. if ((is_int($data) || $data === '0') || (
  320. is_numeric($data) && strpos($data, ',') === false &&
  321. $data[0] != '0' && strpos($data, 'e') === false)
  322. ) {
  323. return $data;
  324. }
  325. return $this->_connection->quote($data);
  326. break;
  327. }
  328. }
  329. /**
  330. * Returns an object to represent a database identifier in a query. Expression objects
  331. * are not sanitized or escaped.
  332. *
  333. * @param string $identifier A SQL expression to be used as an identifier
  334. * @return stdClass An object representing a database identifier to be used in a query
  335. */
  336. public function identifier($identifier) {
  337. $obj = new stdClass();
  338. $obj->type = 'identifier';
  339. $obj->value = $identifier;
  340. return $obj;
  341. }
  342. /**
  343. * Returns an object to represent a database expression in a query. Expression objects
  344. * are not sanitized or escaped.
  345. *
  346. * @param string $expression An arbitrary SQL expression to be inserted into a query.
  347. * @return stdClass An object representing a database expression to be used in a query
  348. */
  349. public function expression($expression) {
  350. $obj = new stdClass();
  351. $obj->type = 'expression';
  352. $obj->value = $expression;
  353. return $obj;
  354. }
  355. /**
  356. * Executes given SQL statement.
  357. *
  358. * @param string $sql SQL statement
  359. * @param array $params Additional options for the query.
  360. * @return boolean
  361. */
  362. public function rawQuery($sql, $params = array()) {
  363. $this->took = $this->numRows = false;
  364. return $this->execute($sql, $params);
  365. }
  366. /**
  367. * Queries the database with given SQL statement, and obtains some metadata about the result
  368. * (rows affected, timing, any errors, number of rows in resultset). The query is also logged.
  369. * If Configure::read('debug') is set, the log is shown all the time, else it is only shown on errors.
  370. *
  371. * ### Options
  372. *
  373. * - log - Whether or not the query should be logged to the memory log.
  374. *
  375. * @param string $sql SQL statement
  376. * @param array $options
  377. * @param array $params values to be bound to the query
  378. * @return mixed Resource or object representing the result set, or false on failure
  379. */
  380. public function execute($sql, $options = array(), $params = array()) {
  381. $options += array('log' => $this->fullDebug);
  382. $t = microtime(true);
  383. $this->_result = $this->_execute($sql, $params);
  384. if ($options['log']) {
  385. $this->took = round((microtime(true) - $t) * 1000, 0);
  386. $this->numRows = $this->affected = $this->lastAffected();
  387. $this->logQuery($sql, $params);
  388. }
  389. return $this->_result;
  390. }
  391. /**
  392. * Executes given SQL statement.
  393. *
  394. * @param string $sql SQL statement
  395. * @param array $params list of params to be bound to query
  396. * @param array $prepareOptions Options to be used in the prepare statement
  397. * @return mixed PDOStatement if query executes with no problem, true as the result of a successful, false on error
  398. * query returning no rows, such as a CREATE statement, false otherwise
  399. * @throws PDOException
  400. */
  401. protected function _execute($sql, $params = array(), $prepareOptions = array()) {
  402. $sql = trim($sql);
  403. if (preg_match('/^(?:CREATE|ALTER|DROP)/i', $sql)) {
  404. $statements = array_filter(explode(';', $sql));
  405. if (count($statements) > 1) {
  406. $result = array_map(array($this, '_execute'), $statements);
  407. return array_search(false, $result) === false;
  408. }
  409. }
  410. try {
  411. $query = $this->_connection->prepare($sql, $prepareOptions);
  412. $query->setFetchMode(PDO::FETCH_LAZY);
  413. if (!$query->execute($params)) {
  414. $this->_results = $query;
  415. $query->closeCursor();
  416. return false;
  417. }
  418. if (!$query->columnCount()) {
  419. $query->closeCursor();
  420. if (!$query->rowCount()) {
  421. return true;
  422. }
  423. }
  424. return $query;
  425. } catch (PDOException $e) {
  426. if (isset($query->queryString)) {
  427. $e->queryString = $query->queryString;
  428. } else {
  429. $e->queryString = $sql;
  430. }
  431. throw $e;
  432. }
  433. }
  434. /**
  435. * Returns a formatted error message from previous database operation.
  436. *
  437. * @param PDOStatement $query the query to extract the error from if any
  438. * @return string Error message with error number
  439. */
  440. public function lastError(PDOStatement $query = null) {
  441. if ($query) {
  442. $error = $query->errorInfo();
  443. } else {
  444. $error = $this->_connection->errorInfo();
  445. }
  446. if (empty($error[2])) {
  447. return null;
  448. }
  449. return $error[1] . ': ' . $error[2];
  450. }
  451. /**
  452. * Returns number of affected rows in previous database operation. If no previous operation exists,
  453. * this returns false.
  454. *
  455. * @param mixed $source
  456. * @return integer Number of affected rows
  457. */
  458. public function lastAffected($source = null) {
  459. if ($this->hasResult()) {
  460. return $this->_result->rowCount();
  461. }
  462. return 0;
  463. }
  464. /**
  465. * Returns number of rows in previous resultset. If no previous resultset exists,
  466. * this returns false.
  467. *
  468. * @param mixed $source Not used
  469. * @return integer Number of rows in resultset
  470. */
  471. public function lastNumRows($source = null) {
  472. return $this->lastAffected();
  473. }
  474. /**
  475. * DataSource Query abstraction
  476. *
  477. * @return resource Result resource identifier.
  478. */
  479. public function query() {
  480. $args = func_get_args();
  481. $fields = null;
  482. $order = null;
  483. $limit = null;
  484. $page = null;
  485. $recursive = null;
  486. if (count($args) === 1) {
  487. return $this->fetchAll($args[0]);
  488. } elseif (count($args) > 1 && (strpos($args[0], 'findBy') === 0 || strpos($args[0], 'findAllBy') === 0)) {
  489. $params = $args[1];
  490. if (substr($args[0], 0, 6) === 'findBy') {
  491. $all = false;
  492. $field = Inflector::underscore(substr($args[0], 6));
  493. } else {
  494. $all = true;
  495. $field = Inflector::underscore(substr($args[0], 9));
  496. }
  497. $or = (strpos($field, '_or_') !== false);
  498. if ($or) {
  499. $field = explode('_or_', $field);
  500. } else {
  501. $field = explode('_and_', $field);
  502. }
  503. $off = count($field) - 1;
  504. if (isset($params[1 + $off])) {
  505. $fields = $params[1 + $off];
  506. }
  507. if (isset($params[2 + $off])) {
  508. $order = $params[2 + $off];
  509. }
  510. if (!array_key_exists(0, $params)) {
  511. return false;
  512. }
  513. $c = 0;
  514. $conditions = array();
  515. foreach ($field as $f) {
  516. $conditions[$args[2]->alias . '.' . $f] = $params[$c++];
  517. }
  518. if ($or) {
  519. $conditions = array('OR' => $conditions);
  520. }
  521. if ($all) {
  522. if (isset($params[3 + $off])) {
  523. $limit = $params[3 + $off];
  524. }
  525. if (isset($params[4 + $off])) {
  526. $page = $params[4 + $off];
  527. }
  528. if (isset($params[5 + $off])) {
  529. $recursive = $params[5 + $off];
  530. }
  531. return $args[2]->find('all', compact('conditions', 'fields', 'order', 'limit', 'page', 'recursive'));
  532. } else {
  533. if (isset($params[3 + $off])) {
  534. $recursive = $params[3 + $off];
  535. }
  536. return $args[2]->find('first', compact('conditions', 'fields', 'order', 'recursive'));
  537. }
  538. } else {
  539. if (isset($args[1]) && $args[1] === true) {
  540. return $this->fetchAll($args[0], true);
  541. } elseif (isset($args[1]) && !is_array($args[1]) ) {
  542. return $this->fetchAll($args[0], false);
  543. } elseif (isset($args[1]) && is_array($args[1])) {
  544. if (isset($args[2])) {
  545. $cache = $args[2];
  546. } else {
  547. $cache = true;
  548. }
  549. return $this->fetchAll($args[0], $args[1], array('cache' => $cache));
  550. }
  551. }
  552. }
  553. /**
  554. * Returns a row from current resultset as an array
  555. *
  556. * @param string $sql Some SQL to be executed.
  557. * @return array The fetched row as an array
  558. */
  559. public function fetchRow($sql = null) {
  560. if (is_string($sql) && strlen($sql) > 5 && !$this->execute($sql)) {
  561. return null;
  562. }
  563. if ($this->hasResult()) {
  564. $this->resultSet($this->_result);
  565. $resultRow = $this->fetchResult();
  566. if (isset($resultRow[0])) {
  567. $this->fetchVirtualField($resultRow);
  568. }
  569. return $resultRow;
  570. } else {
  571. return null;
  572. }
  573. }
  574. /**
  575. * Returns an array of all result rows for a given SQL query.
  576. * Returns false if no rows matched.
  577. *
  578. *
  579. * ### Options
  580. *
  581. * - `cache` - Returns the cached version of the query, if exists and stores the result in cache.
  582. * This is a non-persistent cache, and only lasts for a single request. This option
  583. * defaults to true. If you are directly calling this method, you can disable caching
  584. * by setting $options to `false`
  585. *
  586. * @param string $sql SQL statement
  587. * @param array $params parameters to be bound as values for the SQL statement
  588. * @param array $options additional options for the query.
  589. * @return array Array of resultset rows, or false if no rows matched
  590. */
  591. public function fetchAll($sql, $params = array(), $options = array()) {
  592. if (is_string($options)) {
  593. $options = array('modelName' => $options);
  594. }
  595. if (is_bool($params)) {
  596. $options['cache'] = $params;
  597. $params = array();
  598. }
  599. $options += array('cache' => true);
  600. $cache = $options['cache'];
  601. if ($cache && ($cached = $this->getQueryCache($sql, $params)) !== false) {
  602. return $cached;
  603. }
  604. if ($result = $this->execute($sql, array(), $params)) {
  605. $out = array();
  606. if ($this->hasResult()) {
  607. $first = $this->fetchRow();
  608. if ($first != null) {
  609. $out[] = $first;
  610. }
  611. while ($item = $this->fetchResult()) {
  612. if (isset($item[0])) {
  613. $this->fetchVirtualField($item);
  614. }
  615. $out[] = $item;
  616. }
  617. }
  618. if (!is_bool($result) && $cache) {
  619. $this->_writeQueryCache($sql, $out, $params);
  620. }
  621. if (empty($out) && is_bool($this->_result)) {
  622. return $this->_result;
  623. }
  624. return $out;
  625. }
  626. return false;
  627. }
  628. /**
  629. * Fetches the next row from the current result set
  630. *
  631. * @return boolean
  632. */
  633. public function fetchResult() {
  634. return false;
  635. }
  636. /**
  637. * Modifies $result array to place virtual fields in model entry where they belongs to
  638. *
  639. * @param array $result Reference to the fetched row
  640. * @return void
  641. */
  642. public function fetchVirtualField(&$result) {
  643. if (isset($result[0]) && is_array($result[0])) {
  644. foreach ($result[0] as $field => $value) {
  645. if (strpos($field, $this->virtualFieldSeparator) === false) {
  646. continue;
  647. }
  648. list($alias, $virtual) = explode($this->virtualFieldSeparator, $field);
  649. if (!ClassRegistry::isKeySet($alias)) {
  650. return;
  651. }
  652. $model = ClassRegistry::getObject($alias);
  653. if ($model->isVirtualField($virtual)) {
  654. $result[$alias][$virtual] = $value;
  655. unset($result[0][$field]);
  656. }
  657. }
  658. if (empty($result[0])) {
  659. unset($result[0]);
  660. }
  661. }
  662. }
  663. /**
  664. * Returns a single field of the first of query results for a given SQL query, or false if empty.
  665. *
  666. * @param string $name Name of the field
  667. * @param string $sql SQL query
  668. * @return mixed Value of field read.
  669. */
  670. public function field($name, $sql) {
  671. $data = $this->fetchRow($sql);
  672. if (empty($data[$name])) {
  673. return false;
  674. }
  675. return $data[$name];
  676. }
  677. /**
  678. * Empties the method caches.
  679. * These caches are used by DboSource::name() and DboSource::conditions()
  680. *
  681. * @return void
  682. */
  683. public function flushMethodCache() {
  684. $this->_methodCacheChange = true;
  685. self::$methodCache = array();
  686. }
  687. /**
  688. * Cache a value into the methodCaches. Will respect the value of DboSource::$cacheMethods.
  689. * Will retrieve a value from the cache if $value is null.
  690. *
  691. * If caching is disabled and a write is attempted, the $value will be returned.
  692. * A read will either return the value or null.
  693. *
  694. * @param string $method Name of the method being cached.
  695. * @param string $key The key name for the cache operation.
  696. * @param mixed $value The value to cache into memory.
  697. * @return mixed Either null on failure, or the value if its set.
  698. */
  699. public function cacheMethod($method, $key, $value = null) {
  700. if ($this->cacheMethods === false) {
  701. return $value;
  702. }
  703. if (empty(self::$methodCache)) {
  704. self::$methodCache = Cache::read('method_cache', '_cake_core_');
  705. }
  706. if ($value === null) {
  707. return (isset(self::$methodCache[$method][$key])) ? self::$methodCache[$method][$key] : null;
  708. }
  709. $this->_methodCacheChange = true;
  710. return self::$methodCache[$method][$key] = $value;
  711. }
  712. /**
  713. * Returns a quoted name of $data for use in an SQL statement.
  714. * Strips fields out of SQL functions before quoting.
  715. *
  716. * Results of this method are stored in a memory cache. This improves performance, but
  717. * because the method uses a hashing algorithm it can have collisions.
  718. * Setting DboSource::$cacheMethods to false will disable the memory cache.
  719. *
  720. * @param mixed $data Either a string with a column to quote. An array of columns to quote or an
  721. * object from DboSource::expression() or DboSource::identifier()
  722. * @return string SQL field
  723. */
  724. public function name($data) {
  725. if (is_object($data) && isset($data->type)) {
  726. return $data->value;
  727. }
  728. if ($data === '*') {
  729. return '*';
  730. }
  731. if (is_array($data)) {
  732. foreach ($data as $i => $dataItem) {
  733. $data[$i] = $this->name($dataItem);
  734. }
  735. return $data;
  736. }
  737. $cacheKey = md5($this->startQuote . $data . $this->endQuote);
  738. if ($return = $this->cacheMethod(__FUNCTION__, $cacheKey)) {
  739. return $return;
  740. }
  741. $data = trim($data);
  742. if (preg_match('/^[\w-]+(?:\.[^ \*]*)*$/', $data)) { // string, string.string
  743. if (strpos($data, '.') === false) { // string
  744. return $this->cacheMethod(__FUNCTION__, $cacheKey, $this->startQuote . $data . $this->endQuote);
  745. }
  746. $items = explode('.', $data);
  747. return $this->cacheMethod(__FUNCTION__, $cacheKey,
  748. $this->startQuote . implode($this->endQuote . '.' . $this->startQuote, $items) . $this->endQuote
  749. );
  750. }
  751. if (preg_match('/^[\w-]+\.\*$/', $data)) { // string.*
  752. return $this->cacheMethod(__FUNCTION__, $cacheKey,
  753. $this->startQuote . str_replace('.*', $this->endQuote . '.*', $data)
  754. );
  755. }
  756. if (preg_match('/^([\w-]+)\((.*)\)$/', $data, $matches)) { // Functions
  757. return $this->cacheMethod(__FUNCTION__, $cacheKey,
  758. $matches[1] . '(' . $this->name($matches[2]) . ')'
  759. );
  760. }
  761. if (
  762. preg_match('/^([\w-]+(\.[\w-]+|\(.*\))*)\s+' . preg_quote($this->alias) . '\s*([\w-]+)$/i', $data, $matches
  763. )) {
  764. return $this->cacheMethod(
  765. __FUNCTION__, $cacheKey,
  766. preg_replace(
  767. '/\s{2,}/', ' ', $this->name($matches[1]) . ' ' . $this->alias . ' ' . $this->name($matches[3])
  768. )
  769. );
  770. }
  771. if (preg_match('/^[\w-_\s]*[\w-_]+/', $data)) {
  772. return $this->cacheMethod(__FUNCTION__, $cacheKey, $this->startQuote . $data . $this->endQuote);
  773. }
  774. return $this->cacheMethod(__FUNCTION__, $cacheKey, $data);
  775. }
  776. /**
  777. * Checks if the source is connected to the database.
  778. *
  779. * @return boolean True if the database is connected, else false
  780. */
  781. public function isConnected() {
  782. return $this->connected;
  783. }
  784. /**
  785. * Checks if the result is valid
  786. *
  787. * @return boolean True if the result is valid else false
  788. */
  789. public function hasResult() {
  790. return is_a($this->_result, 'PDOStatement');
  791. }
  792. /**
  793. * Get the query log as an array.
  794. *
  795. * @param boolean $sorted Get the queries sorted by time taken, defaults to false.
  796. * @param boolean $clear If True the existing log will cleared.
  797. * @return array Array of queries run as an array
  798. */
  799. public function getLog($sorted = false, $clear = true) {
  800. if ($sorted) {
  801. $log = sortByKey($this->_queriesLog, 'took', 'desc', SORT_NUMERIC);
  802. } else {
  803. $log = $this->_queriesLog;
  804. }
  805. if ($clear) {
  806. $this->_queriesLog = array();
  807. }
  808. return array('log' => $log, 'count' => $this->_queriesCnt, 'time' => $this->_queriesTime);
  809. }
  810. /**
  811. * Outputs the contents of the queries log. If in a non-CLI environment the sql_log element
  812. * will be rendered and output. If in a CLI environment, a plain text log is generated.
  813. *
  814. * @param boolean $sorted Get the queries sorted by time taken, defaults to false.
  815. * @return void
  816. */
  817. public function showLog($sorted = false) {
  818. $log = $this->getLog($sorted, false);
  819. if (empty($log['log'])) {
  820. return;
  821. }
  822. if (PHP_SAPI != 'cli') {
  823. $controller = null;
  824. $View = new View($controller, false);
  825. $View->set('logs', array($this->configKeyName => $log));
  826. echo $View->element('sql_dump', array('_forced_from_dbo_' => true));
  827. } else {
  828. foreach ($log['log'] as $k => $i) {
  829. print (($k + 1) . ". {$i['query']}\n");
  830. }
  831. }
  832. }
  833. /**
  834. * Log given SQL query.
  835. *
  836. * @param string $sql SQL statement
  837. * @param array $params Values binded to the query (prepared statements)
  838. * @return void
  839. */
  840. public function logQuery($sql, $params = array()) {
  841. $this->_queriesCnt++;
  842. $this->_queriesTime += $this->took;
  843. $this->_queriesLog[] = array(
  844. 'query' => $sql,
  845. 'params' => $params,
  846. 'affected' => $this->affected,
  847. 'numRows' => $this->numRows,
  848. 'took' => $this->took
  849. );
  850. if (count($this->_queriesLog) > $this->_queriesLogMax) {
  851. array_pop($this->_queriesLog);
  852. }
  853. }
  854. /**
  855. * Gets full table name including prefix
  856. *
  857. * @param Model|string $model Either a Model object or a string table name.
  858. * @param boolean $quote Whether you want the table name quoted.
  859. * @param boolean $schema Whether you want the schema name included.
  860. * @return string Full quoted table name
  861. */
  862. public function fullTableName($model, $quote = true, $schema = true) {
  863. if (is_object($model)) {
  864. $schemaName = $model->schemaName;
  865. $table = $model->tablePrefix . $model->table;
  866. } elseif (!empty($this->config['prefix']) && strpos($model, $this->config['prefix']) !== 0) {
  867. $table = $this->config['prefix'] . strval($model);
  868. } else {
  869. $table = strval($model);
  870. }
  871. if ($schema && !isset($schemaName)) {
  872. $schemaName = $this->getSchemaName();
  873. }
  874. if ($quote) {
  875. if ($schema && !empty($schemaName)) {
  876. if (false == strstr($table, '.')) {
  877. return $this->name($schemaName) . '.' . $this->name($table);
  878. }
  879. }
  880. return $this->name($table);
  881. }
  882. if ($schema && !empty($schemaName)) {
  883. if (false == strstr($table, '.')) {
  884. return $schemaName . '.' . $table;
  885. }
  886. }
  887. return $table;
  888. }
  889. /**
  890. * The "C" in CRUD
  891. *
  892. * Creates new records in the database.
  893. *
  894. * @param Model $model Model object that the record is for.
  895. * @param array $fields An array of field names to insert. If null, $model->data will be
  896. * used to generate field names.
  897. * @param array $values An array of values with keys matching the fields. If null, $model->data will
  898. * be used to generate values.
  899. * @return boolean Success
  900. */
  901. public function create(Model $model, $fields = null, $values = null) {
  902. $id = null;
  903. if ($fields == null) {
  904. unset($fields, $values);
  905. $fields = array_keys($model->data);
  906. $values = array_values($model->data);
  907. }
  908. $count = count($fields);
  909. for ($i = 0; $i < $count; $i++) {
  910. $valueInsert[] = $this->value($values[$i], $model->getColumnType($fields[$i]));
  911. $fieldInsert[] = $this->name($fields[$i]);
  912. if ($fields[$i] == $model->primaryKey) {
  913. $id = $values[$i];
  914. }
  915. }
  916. $query = array(
  917. 'table' => $this->fullTableName($model),
  918. 'fields' => implode(', ', $fieldInsert),
  919. 'values' => implode(', ', $valueInsert)
  920. );
  921. if ($this->execute($this->renderStatement('create', $query))) {
  922. if (empty($id)) {
  923. $id = $this->lastInsertId($this->fullTableName($model, false, false), $model->primaryKey);
  924. }
  925. $model->setInsertID($id);
  926. $model->id = $id;
  927. return true;
  928. }
  929. $model->onError();
  930. return false;
  931. }
  932. /**
  933. * The "R" in CRUD
  934. *
  935. * Reads record(s) from the database.
  936. *
  937. * @param Model $model A Model object that the query is for.
  938. * @param array $queryData An array of queryData information containing keys similar to Model::find()
  939. * @param integer $recursive Number of levels of association
  940. * @return mixed boolean false on error/failure. An array of results on success.
  941. */
  942. public function read(Model $model, $queryData = array(), $recursive = null) {
  943. $queryData = $this->_scrubQueryData($queryData);
  944. $null = null;
  945. $array = array('callbacks' => $queryData['callbacks']);
  946. $linkedModels = array();
  947. $bypass = false;
  948. if ($recursive === null && isset($queryData['recursive'])) {
  949. $recursive = $queryData['recursive'];
  950. }
  951. if (!is_null($recursive)) {
  952. $_recursive = $model->recursive;
  953. $model->recursive = $recursive;
  954. }
  955. if (!empty($queryData['fields'])) {
  956. $bypass = true;
  957. $queryData['fields'] = $this->fields($model, null, $queryData['fields']);
  958. } else {
  959. $queryData['fields'] = $this->fields($model);
  960. }
  961. $_associations = $model->associations();
  962. if ($model->recursive == -1) {
  963. $_associations = array();
  964. } elseif ($model->recursive == 0) {
  965. unset($_associations[2], $_associations[3]);
  966. }
  967. foreach ($_associations as $type) {
  968. foreach ($model->{$type} as $assoc => $assocData) {
  969. $linkModel = $model->{$assoc};
  970. $external = isset($assocData['external']);
  971. $linkModel->getDataSource();
  972. if ($model->useDbConfig === $linkModel->useDbConfig) {
  973. if ($bypass) {
  974. $assocData['fields'] = false;
  975. }
  976. if (true === $this->generateAssociationQuery($model, $linkModel, $type, $assoc, $assocData, $queryData, $external, $null)) {
  977. $linkedModels[$type . '/' . $assoc] = true;
  978. }
  979. }
  980. }
  981. }
  982. $query = trim($this->generateAssociationQuery($model, null, null, null, null, $queryData, false, $null));
  983. $resultSet = $this->fetchAll($query, $model->cacheQueries);
  984. if ($resultSet === false) {
  985. $model->onError();
  986. return false;
  987. }
  988. $filtered = array();
  989. if ($queryData['callbacks'] === true || $queryData['callbacks'] === 'after') {
  990. $filtered = $this->_filterResults($resultSet, $model);
  991. }
  992. if ($model->recursive > -1) {
  993. $joined = array();
  994. if (isset($queryData['joins'][0]['alias'])) {
  995. $joined[$model->alias] = (array)Hash::extract($queryData['joins'], '{n}.alias');
  996. }
  997. foreach ($_associations as $type) {
  998. foreach ($model->{$type} as $assoc => $assocData) {
  999. $linkModel = $model->{$assoc};
  1000. if (!isset($linkedModels[$type . '/' . $assoc])) {
  1001. if ($model->useDbConfig === $linkModel->useDbConfig) {
  1002. $db = $this;
  1003. } else {
  1004. $db = ConnectionManager::getDataSource($linkModel->useDbConfig);
  1005. }
  1006. } elseif ($model->recursive > 1 && ($type === 'belongsTo' || $type === 'hasOne')) {
  1007. $db = $this;
  1008. }
  1009. if (isset($db) && method_exists($db, 'queryAssociation')) {
  1010. $stack = array($assoc);
  1011. $stack['_joined'] = $joined;
  1012. $db->queryAssociation($model, $linkModel, $type, $assoc, $assocData, $array, true, $resultSet, $model->recursive - 1, $stack);
  1013. unset($db);
  1014. if ($type === 'hasMany') {
  1015. $filtered[] = $assoc;
  1016. }
  1017. }
  1018. }
  1019. }
  1020. if ($queryData['callbacks'] === true || $queryData['callbacks'] === 'after') {
  1021. $this->_filterResults($resultSet, $model, $filtered);
  1022. }
  1023. }
  1024. if (!is_null($recursive)) {
  1025. $model->recursive = $_recursive;
  1026. }
  1027. return $resultSet;
  1028. }
  1029. /**
  1030. * Passes association results thru afterFind filters of corresponding model
  1031. *
  1032. * @param array $results Reference of resultset to be filtered
  1033. * @param Model $model Instance of model to operate against
  1034. * @param array $filtered List of classes already filtered, to be skipped
  1035. * @return array Array of results that have been filtered through $model->afterFind
  1036. */
  1037. protected function _filterResults(&$results, Model $model, $filtered = array()) {
  1038. $current = reset($results);
  1039. if (!is_array($current)) {
  1040. return array();
  1041. }
  1042. $keys = array_diff(array_keys($current), $filtered, array($model->alias));
  1043. $filtering = array();
  1044. foreach ($keys as $className) {
  1045. if (!isset($model->{$className}) || !is_object($model->{$className})) {
  1046. continue;
  1047. }
  1048. $linkedModel = $model->{$className};
  1049. $filtering[] = $className;
  1050. foreach ($results as &$result) {
  1051. $data = $linkedModel->afterFind(array(array($className => $result[$className])), false);
  1052. if (isset($data[0][$className])) {
  1053. $result[$className] = $data[0][$className];
  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. $uniqueIds = $merge = array();
  1183. foreach ($fetch as $j => $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. if ($merge[0][$association] != null) {
  1291. $data[$association] = $merge[0][$association];
  1292. } else {
  1293. $data[$association] = array();
  1294. }
  1295. } else {
  1296. if (is_array($merge[0][$association])) {
  1297. foreach ($data[$association] as $k => $v) {
  1298. if (!is_array($v)) {
  1299. $dataAssocTmp[$k] = $v;
  1300. }
  1301. }
  1302. foreach ($merge[0][$association] as $k => $v) {
  1303. if (!is_array($v)) {
  1304. $mergeAssocTmp[$k] = $v;
  1305. }
  1306. }
  1307. $dataKeys = array_keys($data);
  1308. $mergeKeys = array_keys($merge[0]);
  1309. if ($mergeKeys[0] === $dataKeys[0] || $mergeKeys === $dataKeys) {
  1310. $data[$association][$association] = $merge[0][$association];
  1311. } else {
  1312. $diff = Hash::diff($dataAssocTmp, $mergeAssocTmp);
  1313. $data[$association] = array_merge($merge[0][$association], $diff);
  1314. }
  1315. } elseif ($selfJoin && array_key_exists($association, $merge[0])) {
  1316. $data[$association] = array_merge($data[$association], array($association => array()));
  1317. }
  1318. }
  1319. }
  1320. } else {
  1321. if (isset($merge[0][$association]) && $merge[0][$association] === false) {
  1322. if (!isset($data[$association])) {
  1323. $data[$association] = array();
  1324. }
  1325. } else {
  1326. foreach ($merge as $i => $row) {
  1327. $insert = array();
  1328. if (count($row) === 1) {
  1329. $insert = $row[$association];
  1330. } elseif (isset($row[$association])) {
  1331. $insert = array_merge($row[$association], $row);
  1332. unset($insert[$association]);
  1333. }
  1334. if (empty($data[$association]) || (isset($data[$association]) && !in_array($insert, $data[$association], true))) {
  1335. $data[$association][] = $insert;
  1336. }
  1337. }
  1338. }
  1339. }
  1340. }
  1341. /**
  1342. * Generates an array representing a query or part of a query from a single model or two associated models
  1343. *
  1344. * @param Model $model
  1345. * @param Model $linkModel
  1346. * @param string $type
  1347. * @param string $association
  1348. * @param array $assocData
  1349. * @param array $queryData
  1350. * @param boolean $external
  1351. * @param array $resultSet
  1352. * @return mixed
  1353. */
  1354. public function generateAssociationQuery(Model $model, $linkModel, $type, $association, $assocData, &$queryData, $external, &$resultSet) {
  1355. $queryData = $this->_scrubQueryData($queryData);
  1356. $assocData = $this->_scrubQueryData($assocData);
  1357. $modelAlias = $model->alias;
  1358. if (empty($queryData['fields'])) {
  1359. $queryData['fields'] = $this->fields($model, $modelAlias);
  1360. } elseif (!empty($model->hasMany) && $model->recursive > -1) {
  1361. $assocFields = $this->fields($model, $modelAlias, array("{$modelAlias}.{$model->primaryKey}"));
  1362. $passedFields = $queryData['fields'];
  1363. if (count($passedFields) === 1) {
  1364. if (strpos($passedFields[0], $assocFields[0]) === false && !preg_match('/^[a-z]+\(/i', $passedFields[0])) {
  1365. $queryData['fields'] = array_merge($passedFields, $assocFields);
  1366. } else {
  1367. $queryData['fields'] = $passedFields;
  1368. }
  1369. } else {
  1370. $queryData['fields'] = array_merge($passedFields, $assocFields);
  1371. }
  1372. unset($assocFields, $passedFields);
  1373. }
  1374. if ($linkModel === null) {
  1375. return $this->buildStatement(
  1376. array(
  1377. 'fields' => array_unique($queryData['fields']),
  1378. 'table' => $this->fullTableName($model),
  1379. 'alias' => $modelAlias,
  1380. 'limit' => $queryData['limit'],
  1381. 'offset' => $queryData['offset'],
  1382. 'joins' => $queryData['joins'],
  1383. 'conditions' => $queryData['conditions'],
  1384. 'order' => $queryData['order'],
  1385. 'group' => $queryData['group']
  1386. ),
  1387. $model
  1388. );
  1389. }
  1390. if ($external && !empty($assocData['finderQuery'])) {
  1391. return $assocData['finderQuery'];
  1392. }
  1393. $self = $model->name === $linkModel->name;
  1394. $fields = array();
  1395. if ($external || (in_array($type, array('hasOne', 'belongsTo')) && $assocData['fields'] !== false)) {
  1396. $fields = $this->fields($linkModel, $association, $assocData['fields']);
  1397. }
  1398. if (empty($assocData['offset']) && !empty($assocData['page'])) {
  1399. $assocData['offset'] = ($assocData['page'] - 1) * $assocData['limit'];
  1400. }
  1401. $assocData['limit'] = $this->limit($assocData['limit'], $assocData['offset']);
  1402. switch ($type) {
  1403. case 'hasOne':
  1404. case 'belongsTo':
  1405. $conditions = $this->_mergeConditions(
  1406. $assocData['conditions'],
  1407. $this->getConstraint($type, $model, $linkModel, $association, array_merge($assocData, compact('external', 'self')))
  1408. );
  1409. if (!$self && $external) {
  1410. foreach ($conditions as $key => $condition) {
  1411. if (is_numeric($key) && strpos($condition, $modelAlias . '.') !== false) {
  1412. unset($conditions[$key]);
  1413. }
  1414. }
  1415. }
  1416. if ($external) {
  1417. $query = array_merge($assocData, array(
  1418. 'conditions' => $conditions,
  1419. 'table' => $this->fullTableName($linkModel),
  1420. 'fields' => $fields,
  1421. 'alias' => $association,
  1422. 'group' => null
  1423. ));
  1424. $query += array('order' => $assocData['order'], 'limit' => $assocData['limit']);
  1425. } else {
  1426. $join = array(
  1427. 'table' => $linkModel,
  1428. 'alias' => $association,
  1429. 'type' => isset($assocData['type']) ? $assocData['type'] : 'LEFT',
  1430. 'conditions' => trim($this->conditions($conditions, true, false, $model))
  1431. );
  1432. $queryData['fields'] = array_merge($queryData['fields'], $fields);
  1433. if (!empty($assocData['order'])) {
  1434. $queryData['order'][] = $assocData['order'];
  1435. }
  1436. if (!in_array($join, $queryData['joins'])) {
  1437. $queryData['joins'][] = $join;
  1438. }
  1439. return true;
  1440. }
  1441. break;
  1442. case 'hasMany':
  1443. $assocData['fields'] = $this->fields($linkModel, $association, $assocData['fields']);
  1444. if (!empty($assocData['foreignKey'])) {
  1445. $assocData['fields'] = array_merge($assocData['fields'], $this->fields($linkModel, $association, array("{$association}.{$assocData['foreignKey']}")));
  1446. }
  1447. $query = array(
  1448. 'conditions' => $this->_mergeConditions($this->getConstraint('hasMany', $model, $linkModel, $association, $assocData), $assocData['conditions']),
  1449. 'fields' => array_unique($assocData['fields']),
  1450. 'table' => $this->fullTableName($linkModel),
  1451. 'alias' => $association,
  1452. 'order' => $assocData['order'],
  1453. 'limit' => $assocData['limit'],
  1454. 'group' => null
  1455. );
  1456. break;
  1457. case 'hasAndBelongsToMany':
  1458. $joinFields = array();
  1459. $joinAssoc = null;
  1460. if (isset($assocData['with']) && !empty($assocData['with'])) {
  1461. $joinKeys = array($assocData['foreignKey'], $assocData['associationForeignKey']);
  1462. list($with, $joinFields) = $model->joinModel($assocData['with'], $joinKeys);
  1463. $joinTbl = $model->{$with};
  1464. $joinAlias = $joinTbl;
  1465. if (is_array($joinFields) && !empty($joinFields)) {
  1466. $joinAssoc = $joinAlias = $model->{$with}->alias;
  1467. $joinFields = $this->fields($model->{$with}, $joinAlias, $joinFields);
  1468. } else {
  1469. $joinFields = array();
  1470. }
  1471. } else {
  1472. $joinTbl = $assocData['joinTable'];
  1473. $joinAlias = $this->fullTableName($assocData['joinTable']);
  1474. }
  1475. $query = array(
  1476. 'conditions' => $assocData['conditions'],
  1477. 'limit' => $assocData['limit'],
  1478. 'table' => $this->fullTableName($linkModel),
  1479. 'alias' => $association,
  1480. 'fields' => array_merge($this->fields($linkModel, $association, $assocData['fields']), $joinFields),
  1481. 'order' => $assocData['order'],
  1482. 'group' => null,
  1483. 'joins' => array(array(
  1484. 'table' => $joinTbl,
  1485. 'alias' => $joinAssoc,
  1486. 'conditions' => $this->getConstraint('hasAndBelongsToMany', $model, $linkModel, $joinAlias, $assocData, $association)
  1487. ))
  1488. );
  1489. break;
  1490. }
  1491. if (isset($query)) {
  1492. return $this->buildStatement($query, $model);
  1493. }
  1494. return null;
  1495. }
  1496. /**
  1497. * Returns a conditions array for the constraint between two models
  1498. *
  1499. * @param string $type Association type
  1500. * @param Model $model Model object
  1501. * @param string $linkModel
  1502. * @param string $alias
  1503. * @param array $assoc
  1504. * @param string $alias2
  1505. * @return array Conditions array defining the constraint between $model and $association
  1506. */
  1507. public function getConstraint($type, $model, $linkModel, $alias, $assoc, $alias2 = null) {
  1508. $assoc += array('external' => false, 'self' => false);
  1509. if (empty($assoc['foreignKey'])) {
  1510. return array();
  1511. }
  1512. switch (true) {
  1513. case ($assoc['external'] && $type === 'hasOne'):
  1514. return array("{$alias}.{$assoc['foreignKey']}" => '{$__cakeID__$}');
  1515. case ($assoc['external'] && $type === 'belongsTo'):
  1516. return array("{$alias}.{$linkModel->primaryKey}" => '{$__cakeForeignKey__$}');
  1517. case (!$assoc['external'] && $type === 'hasOne'):
  1518. return array("{$alias}.{$assoc['foreignKey']}" => $this->identifier("{$model->alias}.{$model->primaryKey}"));
  1519. case (!$assoc['external'] && $type === 'belongsTo'):
  1520. return array("{$model->alias}.{$assoc['foreignKey']}" => $this->identifier("{$alias}.{$linkModel->primaryKey}"));
  1521. case ($type === 'hasMany'):
  1522. return array("{$alias}.{$assoc['foreignKey']}" => array('{$__cakeID__$}'));
  1523. case ($type === 'hasAndBelongsToMany'):
  1524. return array(
  1525. array("{$alias}.{$assoc['foreignKey']}" => '{$__cakeID__$}'),
  1526. array("{$alias}.{$assoc['associationForeignKey']}" => $this->identifier("{$alias2}.{$linkModel->primaryKey}"))
  1527. );
  1528. }
  1529. return array();
  1530. }
  1531. /**
  1532. * Builds and generates a JOIN statement from an array. Handles final clean-up before conversion.
  1533. *
  1534. * @param array $join An array defining a JOIN statement in a query
  1535. * @return string An SQL JOIN statement to be used in a query
  1536. * @see DboSource::renderJoinStatement()
  1537. * @see DboSource::buildStatement()
  1538. */
  1539. public function buildJoinStatement($join) {
  1540. $data = array_merge(array(
  1541. 'type' => null,
  1542. 'alias' => null,
  1543. 'table' => 'join_table',
  1544. 'conditions' => array()
  1545. ), $join);
  1546. if (!empty($data['alias'])) {
  1547. $data['alias'] = $this->alias . $this->name($data['alias']);
  1548. }
  1549. if (!empty($data['conditions'])) {
  1550. $data['conditions'] = trim($this->conditions($data['conditions'], true, false));
  1551. }
  1552. if (!empty(

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