PageRenderTime 62ms CodeModel.GetById 18ms RepoModel.GetById 1ms app.codeStats 0ms

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

https://github.com/dwija/ZoneMinder
PHP | 3544 lines | 2226 code | 378 blank | 940 comment | 550 complexity | f00b6053077554321772de44305a869c MD5 | raw file
Possible License(s): GPL-2.0

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

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

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