PageRenderTime 59ms CodeModel.GetById 16ms RepoModel.GetById 0ms app.codeStats 1ms

/cake/libs/model/datasources/dbo_source.php

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

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