PageRenderTime 77ms CodeModel.GetById 32ms RepoModel.GetById 0ms app.codeStats 1ms

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

https://bitbucket.org/meLego/snelcms
PHP | 3069 lines | 2196 code | 224 blank | 649 comment | 509 complexity | 66516018ee8d3efce2b330a2bb783e07 MD5 | raw file
Possible License(s): LGPL-2.1

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

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

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