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

/baser/models/datasources/dbo_source.php

https://github.com/hashing/basercms
PHP | 3504 lines | 2320 code | 398 blank | 786 comment | 646 complexity | bd03af0ab94a73429341bb52159c11fc MD5 | raw file
Possible License(s): MIT

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

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