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

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

https://github.com/Forbin/cakephp2x
PHP | 2785 lines | 1872 code | 234 blank | 679 comment | 594 complexity | e02690ef27f5d43ec6c3a525557e7149 MD5 | raw file

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

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

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