PageRenderTime 83ms CodeModel.GetById 34ms RepoModel.GetById 0ms app.codeStats 1ms

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

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

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