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

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

https://github.com/mariuz/firetube
PHP | 2497 lines | 1777 code | 163 blank | 557 comment | 567 complexity | 75051a39ade878fecd470a0aa5887a40 MD5 | raw file
Possible License(s): LGPL-2.1

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

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

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