PageRenderTime 61ms CodeModel.GetById 23ms RepoModel.GetById 0ms app.codeStats 1ms

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

https://github.com/Bancha/cakephp
PHP | 3150 lines | 2177 code | 229 blank | 744 comment | 454 complexity | f3cfebf929f0956071b8a60c342e1596 MD5 | raw file

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

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