PageRenderTime 65ms CodeModel.GetById 18ms 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
  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" . join(",\n\t", array_filter(${$var}));
  1512. } else {
  1513. ${$var} = '';
  1514. }
  1515. }
  1516. if (trim($indexes) != '') {
  1517. $columns .= ',';
  1518. }
  1519. return "CREATE TABLE {$table} (\n{$columns}{$indexes}){$tableParameters};";
  1520. break;
  1521. case 'alter':
  1522. break;
  1523. }
  1524. }
  1525. /**
  1526. * Merges a mixed set of string/array conditions
  1527. *
  1528. * @return array
  1529. * @access private
  1530. */
  1531. function __mergeConditions($query, $assoc) {
  1532. if (empty($assoc)) {
  1533. return $query;
  1534. }
  1535. if (is_array($query)) {
  1536. return array_merge((array)$assoc, $query);
  1537. }
  1538. if (!empty($query)) {
  1539. $query = array($query);
  1540. if (is_array($assoc)) {
  1541. $query = array_merge($query, $assoc);
  1542. } else {
  1543. $query[] = $assoc;
  1544. }
  1545. return $query;
  1546. }
  1547. return $assoc;
  1548. }
  1549. /**
  1550. * Generates and executes an SQL UPDATE statement for given model, fields, and values.
  1551. * For databases that do not support aliases in UPDATE queries.
  1552. *
  1553. * @param Model $model
  1554. * @param array $fields
  1555. * @param array $values
  1556. * @param mixed $conditions
  1557. * @return boolean Success
  1558. */
  1559. public function update($model, $fields = array(), $values = null, $conditions = null) {
  1560. if ($values == null) {
  1561. $combined = $fields;
  1562. } else {
  1563. $combined = array_combine($fields, $values);
  1564. }
  1565. $fields = implode(', ', $this->_prepareUpdateFields($model, $combined, empty($conditions)));
  1566. $alias = $joins = null;
  1567. $table = $this->fullTableName($model);
  1568. $conditions = $this->_matchRecords($model, $conditions);
  1569. if ($conditions === false) {
  1570. return false;
  1571. }
  1572. $query = compact('table', 'alias', 'joins', 'fields', 'conditions');
  1573. if (!$this->execute($this->renderStatement('update', $query))) {
  1574. $model->onError();
  1575. return false;
  1576. }
  1577. return true;
  1578. }
  1579. /**
  1580. * Quotes and prepares fields and values for an SQL UPDATE statement
  1581. *
  1582. * @param Model $model
  1583. * @param array $fields
  1584. * @param boolean $quoteValues If values should be quoted, or treated as SQL snippets
  1585. * @param boolean $alias Include the model alias in the field name
  1586. * @return array Fields and values, quoted and preparted
  1587. */
  1588. protected function _prepareUpdateFields($model, $fields, $quoteValues = true, $alias = false) {
  1589. $quotedAlias = $this->startQuote . $model->alias . $this->endQuote;
  1590. $updates = array();
  1591. foreach ($fields as $field => $value) {
  1592. if ($alias && strpos($field, '.') === false) {
  1593. $quoted = $model->escapeField($field);
  1594. } elseif (!$alias && strpos($field, '.') !== false) {
  1595. $quoted = $this->name(str_replace($quotedAlias . '.', '', str_replace(
  1596. $model->alias . '.', '', $field
  1597. )));
  1598. } else {
  1599. $quoted = $this->name($field);
  1600. }
  1601. if ($value === null) {
  1602. $updates[] = $quoted . ' = NULL';
  1603. continue;
  1604. }
  1605. $update = $quoted . ' = ';
  1606. if ($quoteValues) {
  1607. $update .= $this->value($value, $model->getColumnType($field), false);
  1608. } elseif (!$alias) {
  1609. $update .= str_replace($quotedAlias . '.', '', str_replace(
  1610. $model->alias . '.', '', $value
  1611. ));
  1612. } else {
  1613. $update .= $value;
  1614. }
  1615. $updates[] = $update;
  1616. }
  1617. return $updates;
  1618. }
  1619. /**
  1620. * Generates and executes an SQL DELETE statement.
  1621. * For databases that do not support aliases in UPDATE queries.
  1622. *
  1623. * @param Model $model
  1624. * @param mixed $conditions
  1625. * @return boolean Success
  1626. */
  1627. public function delete($model, $conditions = null) {
  1628. $alias = $joins = null;
  1629. $table = $this->fullTableName($model);
  1630. $conditions = $this->_matchRecords($model, $conditions);
  1631. if ($conditions === false) {
  1632. return false;
  1633. }
  1634. if ($this->execute($this->renderStatement('delete', compact('alias', 'table', 'joins', 'conditions'))) === false) {
  1635. $model->onError();
  1636. return false;
  1637. }
  1638. return true;
  1639. }
  1640. /**
  1641. * Gets a list of record IDs for the given conditions. Used for multi-record updates and deletes
  1642. * in databases that do not support aliases in UPDATE/DELETE queries.
  1643. *
  1644. * @param Model $model
  1645. * @param mixed $conditions
  1646. * @return array List of record IDs
  1647. */
  1648. protected function _matchRecords($model, $conditions = null) {
  1649. if ($conditions === true) {
  1650. $conditions = $this->conditions(true);
  1651. } elseif ($conditions === null) {
  1652. $conditions = $this->conditions($this->defaultConditions($model, $conditions, false), true, true, $model);
  1653. } else {
  1654. $noJoin = true;
  1655. foreach ($conditions as $field => $value) {
  1656. $originalField = $field;
  1657. if (strpos($field, '.') !== false) {
  1658. list($alias, $field) = explode('.', $field);
  1659. $field = ltrim($field, $this->startQuote);
  1660. $field = rtrim($field, $this->endQuote);
  1661. }
  1662. if (!$model->hasField($field)) {
  1663. $noJoin = false;
  1664. break;
  1665. }
  1666. if ($field !== $originalField) {
  1667. $conditions[$field] = $value;
  1668. unset($conditions[$originalField]);
  1669. }
  1670. }
  1671. if ($noJoin === true) {
  1672. return $this->conditions($conditions);
  1673. }
  1674. $idList = $model->find('all', array(
  1675. 'fields' => "{$model->alias}.{$model->primaryKey}",
  1676. 'conditions' => $conditions
  1677. ));
  1678. if (empty($idList)) {
  1679. return false;
  1680. }
  1681. $conditions = $this->conditions(array(
  1682. $model->primaryKey => Set::extract($idList, "{n}.{$model->alias}.{$model->primaryKey}")
  1683. ));
  1684. }
  1685. return $conditions;
  1686. }
  1687. /**
  1688. * Returns an array of SQL JOIN fragments from a model's associations
  1689. *
  1690. * @param object $model
  1691. * @return array
  1692. */
  1693. protected function _getJoins($model) {
  1694. $join = array();
  1695. $joins = array_merge($model->getAssociated('hasOne'), $model->getAssociated('belongsTo'));
  1696. foreach ($joins as $assoc) {
  1697. if (isset($model->{$assoc}) && $model->useDbConfig == $model->{$assoc}->useDbConfig) {
  1698. $assocData = $model->getAssociated($assoc);
  1699. $join[] = $this->buildJoinStatement(array(
  1700. 'table' => $this->fullTableName($model->{$assoc}),
  1701. 'alias' => $assoc,
  1702. 'type' => isset($assocData['type']) ? $assocData['type'] : 'LEFT',
  1703. 'conditions' => trim($this->conditions(
  1704. $this->__mergeConditions($assocData['conditions'], $this->getConstraint($assocData['association'], $model, $model->{$assoc}, $assoc, $assocData)),
  1705. true, false, $model
  1706. ))
  1707. ));
  1708. }
  1709. }
  1710. return $join;
  1711. }
  1712. /**
  1713. * Returns an SQL calculation, i.e. COUNT() or MAX()
  1714. *
  1715. * @param model $model
  1716. * @param string $func Lowercase name of SQL function, i.e. 'count' or 'max'
  1717. * @param array $params Function parameters (any values must be quoted manually)
  1718. * @return string An SQL calculation function
  1719. */
  1720. public function calculate($model, $func, $params = array()) {
  1721. $params = (array)$params;
  1722. switch (strtolower($func)) {
  1723. case 'count':
  1724. if (!isset($params[0])) {
  1725. $params[0] = '*';
  1726. }
  1727. if (!isset($params[1])) {
  1728. $params[1] = 'count';
  1729. }
  1730. if (is_object($model) && $model->isVirtualField($params[0])){
  1731. $arg = $this->__quoteFields($model->getVirtualField($params[0]));
  1732. } else {
  1733. $arg = $this->name($params[0]);
  1734. }
  1735. return 'COUNT(' . $arg . ') AS ' . $this->name($params[1]);
  1736. case 'max':
  1737. case 'min':
  1738. if (!isset($params[1])) {
  1739. $params[1] = $params[0];
  1740. }
  1741. if (is_object($model) && $model->isVirtualField($params[0])) {
  1742. $arg = $this->__quoteFields($model->getVirtualField($params[0]));
  1743. } else {
  1744. $arg = $this->name($params[0]);
  1745. }
  1746. return strtoupper($func) . '(' . $arg . ') AS ' . $this->name($params[1]);
  1747. break;
  1748. }
  1749. }
  1750. /**
  1751. * Deletes all the records in a table and resets the count of the auto-incrementing
  1752. * primary key, where applicable.
  1753. *
  1754. * @param mixed $table A string or model class representing the table to be truncated
  1755. * @return boolean SQL TRUNCATE TABLE statement, false if not applicable.
  1756. */
  1757. public function truncate($table) {
  1758. return $this->execute('TRUNCATE TABLE ' . $this->fullTableName($table));
  1759. }
  1760. /**
  1761. * Begin a transaction
  1762. *
  1763. * @return boolean True on success, false on fail
  1764. * (i.e. if the database/model does not support transactions,
  1765. * or a transaction has not started).
  1766. */
  1767. public function begin() {
  1768. if ($this->_transactionStarted || $this->_connection->beginTransaction()) {
  1769. $this->_transactionStarted = true;
  1770. $this->_transactionNesting++;
  1771. return true;
  1772. }
  1773. return false;
  1774. }
  1775. /**
  1776. * Commit a transaction
  1777. *
  1778. * @return boolean True on success, false on fail
  1779. * (i.e. if the database/model does not support transactions,
  1780. * or a transaction has not started).
  1781. */
  1782. public function commit() {
  1783. if ($this->_transactionStarted) {
  1784. $this->_transactionNesting--;
  1785. if ($this->_transactionNesting <= 0) {
  1786. $this->_transactionStarted = false;
  1787. $this->_transactionNesting = 0;
  1788. return $this->_connection->commit();
  1789. }
  1790. return true;
  1791. }
  1792. return false;
  1793. }
  1794. /**
  1795. * Rollback a transaction
  1796. *
  1797. * @return boolean True on success, false on fail
  1798. * (i.e. if the database/model does not support transactions,
  1799. * or a transaction has not started).
  1800. */
  1801. public function rollback() {
  1802. if ($this->_transactionStarted && $this->_connection->rollBack()) {
  1803. $this->_transactionStarted = false;
  1804. $this->_transactionNesting = 0;
  1805. return true;
  1806. }
  1807. return false;
  1808. }
  1809. /**
  1810. * Returns the ID generated from the previous INSERT operation.
  1811. *
  1812. * @param unknown_type $source
  1813. * @return in
  1814. */
  1815. function lastInsertId($source = null) {
  1816. return $this->_connection->lastInsertId();
  1817. }
  1818. /**
  1819. * Creates a default set of conditions from the model if $conditions is null/empty.
  1820. * If conditions are supplied then they will be returned. If a model doesn't exist and no conditions
  1821. * were provided either null or false will be returned based on what was input.
  1822. *
  1823. * @param object $model
  1824. * @param mixed $conditions Array of conditions, conditions string, null or false. If an array of conditions,
  1825. * or string conditions those conditions will be returned. With other values the model's existance will be checked.
  1826. * If the model doesn't exist a null or false will be returned depending on the input value.
  1827. * @param boolean $useAlias Use model aliases rather than table names when generating conditions
  1828. * @return mixed Either null, false, $conditions or an array of default conditions to use.
  1829. * @see DboSource::update()
  1830. * @see DboSource::conditions()
  1831. */
  1832. public function defaultConditions($model, $conditions, $useAlias = true) {
  1833. if (!empty($conditions)) {
  1834. return $conditions;
  1835. }
  1836. $exists = $model->exists();
  1837. if (!$exists && $conditions !== null) {
  1838. return false;
  1839. } elseif (!$exists) {
  1840. return null;
  1841. }
  1842. $alias = $model->alias;
  1843. if (!$useAlias) {
  1844. $alias = $this->fullTableName($model, false);
  1845. }
  1846. return array("{$alias}.{$model->primaryKey}" => $model->getID());
  1847. }
  1848. /**
  1849. * Returns a key formatted like a string Model.fieldname(i.e. Post.title, or Country.name)
  1850. *
  1851. * @param unknown_type $model
  1852. * @param unknown_type $key
  1853. * @param unknown_type $assoc
  1854. * @return string
  1855. */
  1856. public function resolveKey($model, $key, $assoc = null) {
  1857. if (empty($assoc)) {
  1858. $assoc = $model->alias;
  1859. }
  1860. if (!strpos('.', $key)) {
  1861. return $this->name($model->alias) . '.' . $this->name($key);
  1862. }
  1863. return $key;
  1864. }
  1865. /**
  1866. * Private helper method to remove query metadata in given data array.
  1867. *
  1868. * @param array $data
  1869. * @return array
  1870. */
  1871. public function __scrubQueryData($data) {
  1872. foreach (array('conditions', 'fields', 'joins', 'order', 'limit', 'offset', 'group') as $key) {
  1873. if (empty($data[$key])) {
  1874. $data[$key] = array();
  1875. }
  1876. }
  1877. return $data;
  1878. }
  1879. /**
  1880. * Converts model virtual fields into sql expressions to be fetched later
  1881. *
  1882. * @param Model $model
  1883. * @param string $alias Alias tablename
  1884. * @param mixed $fields virtual fields to be used on query
  1885. * @return array
  1886. */
  1887. protected function _constructVirtualFields($model, $alias, $fields) {
  1888. $virtual = array();
  1889. foreach ($fields as $field) {
  1890. $virtualField = $this->name($alias . $this->virtualFieldSeparator . $field);
  1891. $expression = $this->__quoteFields($model->getVirtualField($field));
  1892. $virtual[] = '(' . $expression . ") {$this->alias} {$virtualField}";
  1893. }
  1894. return $virtual;
  1895. }
  1896. /**
  1897. * Generates the fields list of an SQL query.
  1898. *
  1899. * @param Model $model
  1900. * @param string $alias Alias tablename
  1901. * @param mixed $fields
  1902. * @param boolean $quote If false, returns fields array unquoted
  1903. * @return array
  1904. */
  1905. public function fields($model, $alias = null, $fields = array(), $quote = true) {
  1906. if (empty($alias)) {
  1907. $alias = $model->alias;
  1908. }
  1909. $cacheKey = array(
  1910. $model->useDbConfig,
  1911. $model->table,
  1912. array_keys($model->schema()),
  1913. $model->name,
  1914. $model->getVirtualField(),
  1915. $alias,
  1916. $fields,
  1917. $quote
  1918. );
  1919. $cacheKey = crc32(serialize($cacheKey));
  1920. if ($return = $this->cacheMethod(__FUNCTION__, $cacheKey)) {
  1921. return $return;
  1922. }
  1923. $allFields = empty($fields);
  1924. if ($allFields) {
  1925. $fields = array_keys($model->schema());
  1926. } elseif (!is_array($fields)) {
  1927. $fields = String::tokenize($fields);
  1928. }
  1929. $fields = array_values(array_filter($fields));
  1930. $allFields = $allFields || in_array('*', $fields) || in_array($model->alias . '.*', $fields);
  1931. $virtual = array();
  1932. $virtualFields = $model->getVirtualField();
  1933. if (!empty($virtualFields)) {
  1934. $virtualKeys = array_keys($virtualFields);
  1935. foreach ($virtualKeys as $field) {
  1936. $virtualKeys[] = $model->alias . '.' . $field;
  1937. }
  1938. $virtual = ($allFields) ? $virtualKeys : array_intersect($virtualKeys, $fields);
  1939. foreach ($virtual as $i => $field) {
  1940. if (strpos($field, '.') !== false) {
  1941. $virtual[$i] = str_replace($model->alias . '.', '', $field);
  1942. }
  1943. $fields = array_diff($fields, array($field));
  1944. }
  1945. $fields = array_values($fields);
  1946. }
  1947. if (!$quote) {
  1948. if (!empty($virtual)) {
  1949. $fields = array_merge($fields, $this->_constructVirtualFields($model, $alias, $virtual));
  1950. }
  1951. return $fields;
  1952. }
  1953. $count = count($fields);
  1954. if ($count >= 1 && !in_array($fields[0], array('*', 'COUNT(*)'))) {
  1955. for ($i = 0; $i < $count; $i++) {
  1956. if (is_string($fields[$i]) && in_array($fields[$i], $virtual)) {
  1957. unset($fields[$i]);
  1958. continue;
  1959. }
  1960. if (is_object($fields[$i]) && isset($fields[$i]->type) && $fields[$i]->type === 'expression') {
  1961. $fields[$i] = $fields[$i]->value;
  1962. } elseif (preg_match('/^\(.*\)\s' . $this->alias . '.*/i', $fields[$i])){
  1963. continue;
  1964. } elseif (!preg_match('/^.+\\(.*\\)/', $fields[$i])) {
  1965. $prepend = '';
  1966. if (strpos($fields[$i], 'DISTINCT') !== false) {
  1967. $prepend = 'DISTINCT ';
  1968. $fields[$i] = trim(str_replace('DISTINCT', '', $fields[$i]));
  1969. }
  1970. $dot = strpos($fields[$i], '.');
  1971. if ($dot === false) {
  1972. $prefix = !(
  1973. strpos($fields[$i], ' ') !== false ||
  1974. strpos($fields[$i], '(') !== false
  1975. );
  1976. $fields[$i] = $this->name(($prefix ? $alias . '.' : '') . $fields[$i]);
  1977. } else {
  1978. $value = array();
  1979. $comma = strpos($fields[$i], ',');
  1980. if ($comma === false) {
  1981. $build = explode('.', $fields[$i]);
  1982. if (!Set::numeric($build)) {
  1983. $fields[$i] = $this->name(implode('.', $build));
  1984. }
  1985. }
  1986. }
  1987. $fields[$i] = $prepend . $fields[$i];
  1988. } elseif (preg_match('/\(([\.\w]+)\)/', $fields[$i], $field)) {
  1989. if (isset($field[1])) {
  1990. if (strpos($field[1], '.') === false) {
  1991. $field[1] = $this->name($alias . '.' . $field[1]);
  1992. } else {
  1993. $field[0] = explode('.', $field[1]);
  1994. if (!Set::numeric($field[0])) {
  1995. $field[0] = implode('.', array_map(array(&$this, 'name'), $field[0]));
  1996. $fields[$i] = preg_replace('/\(' . $field[1] . '\)/', '(' . $field[0] . ')', $fields[$i], 1);
  1997. }
  1998. }
  1999. }
  2000. }
  2001. }
  2002. }
  2003. if (!empty($virtual)) {
  2004. $fields = array_merge($fields, $this->_constructVirtualFields($model, $alias, $virtual));
  2005. }
  2006. return $this->cacheMethod(__FUNCTION__, $cacheKey, array_unique($fields));
  2007. }
  2008. /**
  2009. * Creates a WHERE clause by parsing given conditions data. If an array or string
  2010. * conditions are provided those conditions will be parsed and quoted. If a boolean
  2011. * is given it will be integer cast as condition. Null will return 1 = 1.
  2012. *
  2013. * Results of this method are stored in a memory cache. This improves performance, but
  2014. * because the method uses a simple hashing algorithm it can infrequently have collisions.
  2015. * Setting DboSource::$cacheMethods to false will disable the memory cache.
  2016. *
  2017. * @param mixed $conditions Array or string of conditions, or any value.
  2018. * @param boolean $quoteValues If true, values should be quoted
  2019. * @param boolean $where If true, "WHERE " will be prepended to the return value
  2020. * @param Model $model A reference to the Model instance making the query
  2021. * @return string SQL fragment
  2022. */
  2023. public function conditions($conditions, $quoteValues = true, $where = true, $model = null) {
  2024. if (is_object($model)) {
  2025. $cacheKey = array(
  2026. $model->useDbConfig,
  2027. $model->table,
  2028. $model->schema(),
  2029. $model->name,
  2030. $model->getVirtualField(),
  2031. $conditions,
  2032. $quoteValues,
  2033. $where
  2034. );
  2035. } else {
  2036. $cacheKey = array($conditions, $quoteValues, $where);
  2037. }
  2038. $cacheKey = crc32(serialize($cacheKey));
  2039. if ($return = $this->cacheMethod(__FUNCTION__, $cacheKey)) {
  2040. return $return;
  2041. }
  2042. $clause = $out = '';
  2043. if ($where) {
  2044. $clause = ' WHERE ';
  2045. }
  2046. if (is_array($conditions) && !empty($conditions)) {
  2047. $out = $this->conditionKeysToString($conditions, $quoteValues, $model);
  2048. if (empty($out)) {
  2049. return $this->cacheMethod(__FUNCTION__, $cacheKey, $clause . ' 1 = 1');
  2050. }
  2051. return $this->cacheMethod(__FUNCTION__, $cacheKey, $clause . implode(' AND ', $out));
  2052. }
  2053. if ($conditions === false || $conditions === true) {
  2054. return $this->cacheMethod(__FUNCTION__, $cacheKey, $clause . (int)$conditions . ' = 1');
  2055. }
  2056. if (empty($conditions) || trim($conditions) == '') {
  2057. return $this->cacheMethod(__FUNCTION__, $cacheKey, $clause . '1 = 1');
  2058. }
  2059. $clauses = '/^WHERE\\x20|^GROUP\\x20BY\\x20|^HAVING\\x20|^ORDER\\x20BY\\x20/i';
  2060. if (preg_match($clauses, $conditions, $match)) {
  2061. $clause = '';
  2062. }
  2063. if (trim($conditions) == '') {
  2064. $conditions = ' 1 = 1';
  2065. } else {
  2066. $conditions = $this->__quoteFields($conditions);
  2067. }
  2068. return $this->cacheMethod(__FUNCTION__, $cacheKey, $clause . $conditions);
  2069. }
  2070. /**
  2071. * Creates a WHERE clause by parsing given conditions array. Used by DboSource::conditions().
  2072. *
  2073. * @param array $conditions Array or string of conditions
  2074. * @param boolean $quoteValues If true, values should be quoted
  2075. * @param Model $model A reference to the Model instance making the query
  2076. * @return string SQL fragment
  2077. */
  2078. public function conditionKeysToString($conditions, $quoteValues = true, $model = null) {
  2079. $c = 0;
  2080. $out = array();
  2081. $data = $columnType = null;
  2082. $bool = array('and', 'or', 'not', 'and not', 'or not', 'xor', '||', '&&');
  2083. foreach ($conditions as $key => $value) {
  2084. $join = ' AND ';
  2085. $not = null;
  2086. if (is_array($value)) {
  2087. $valueInsert = (
  2088. !empty($value) &&
  2089. (substr_count($key, '?') == count($value) || substr_count($key, ':') == count($value))
  2090. );
  2091. }
  2092. if (is_numeric($key) && empty($value)) {
  2093. continue;
  2094. } elseif (is_numeric($key) && is_string($value)) {
  2095. $out[] = $not . $this->__quoteFields($value);
  2096. } elseif ((is_numeric($key) && is_array($value)) || in_array(strtolower(trim($key)), $bool)) {
  2097. if (in_array(strtolower(trim($key)), $bool)) {
  2098. $join = ' ' . strtoupper($key) . ' ';
  2099. } else {
  2100. $key = $join;
  2101. }
  2102. $value = $this->conditionKeysToString($value, $quoteValues, $model);
  2103. if (strpos($join, 'NOT') !== false) {
  2104. if (strtoupper(trim($key)) == 'NOT') {
  2105. $key = 'AND ' . trim($key);
  2106. }
  2107. $not = 'NOT ';
  2108. }
  2109. if (empty($value[1])) {
  2110. if ($not) {
  2111. $out[] = $not . '(' . $value[0] . ')';
  2112. } else {
  2113. $out[] = $value[0] ;
  2114. }
  2115. } else {
  2116. $out[] = '(' . $not . '(' . implode(') ' . strtoupper($key) . ' (', $value) . '))';
  2117. }
  2118. } else {
  2119. if (is_object($value) && isset($value->type)) {
  2120. if ($value->type == 'identifier') {
  2121. $data .= $this->name($key) . ' = ' . $this->name($value->value);
  2122. } elseif ($value->type == 'expression') {
  2123. if (is_numeric($key)) {
  2124. $data .= $value->value;
  2125. } else {
  2126. $data .= $this->name($key) . ' = ' . $value->value;
  2127. }
  2128. }
  2129. } elseif (is_array($value) && !empty($value) && !$valueInsert) {
  2130. $keys = array_keys($value);
  2131. if ($keys === array_values($keys)) {
  2132. $count = count($value);
  2133. if ($count === 1) {
  2134. $data = $this->__quoteFields($key) . ' = (';
  2135. } else {
  2136. $data = $this->__quoteFields($key) . ' IN (';
  2137. }
  2138. if ($quoteValues) {
  2139. if (is_object($model)) {
  2140. $columnType = $model->getColumnType($key);
  2141. }
  2142. $data .= implode(', ', $this->value($value, $columnType));
  2143. }
  2144. $data .= ')';
  2145. } else {
  2146. $ret = $this->conditionKeysToString($value, $quoteValues, $model);
  2147. if (count($ret) > 1) {
  2148. $data = '(' . implode(') AND (', $ret) . ')';
  2149. } elseif (isset($ret[0])) {
  2150. $data = $ret[0];
  2151. }
  2152. }
  2153. } elseif (is_numeric($key) && !empty($value)) {
  2154. $data = $this->__quoteFields($value);
  2155. } else {
  2156. $data = $this->__parseKey($model, trim($key), $value);
  2157. }
  2158. if ($data != null) {
  2159. $out[] = $data;
  2160. $data = null;
  2161. }
  2162. }
  2163. $c++;
  2164. }
  2165. return $out;
  2166. }
  2167. /**
  2168. * Extracts a Model.field identifier and an SQL condition operator from a string, formats
  2169. * and inserts values, and composes them into an SQL snippet.
  2170. *
  2171. * @param Model $model Model object initiating the query
  2172. * @param string $key An SQL key snippet containing a field and optional SQL operator
  2173. * @param mixed $value The value(s) to be inserted in the string
  2174. * @return string
  2175. * @access private
  2176. */
  2177. function __parseKey($model, $key, $value) {
  2178. $operatorMatch = '/^((' . implode(')|(', $this->__sqlOps);
  2179. $operatorMatch .= '\\x20)|<[>=]?(?![^>]+>)\\x20?|[>=!]{1,3}(?!<)\\x20?)/is';
  2180. $bound = (strpos($key, '?') !== false || (is_array($value) && strpos($key, ':') !== false));
  2181. if (!strpos($key, ' ')) {
  2182. $operator = '=';
  2183. } else {
  2184. list($key, $operator) = explode(' ', trim($key), 2);
  2185. if (!preg_match($operatorMatch, trim($operator)) && strpos($operator, ' ') !== false) {
  2186. $key = $key . ' ' . $operator;
  2187. $split = strrpos($key, ' ');
  2188. $operator = substr($key, $split);
  2189. $key = substr($key, 0, $split);
  2190. }
  2191. }
  2192. $virtual = false;
  2193. if (is_object($model) && $model->isVirtualField($key)) {
  2194. $key = $this->__quoteFields($model->getVirtualField($key));
  2195. $virtual = true;
  2196. }
  2197. $type = (is_object($model) ? $model->getColumnType($key) : null);
  2198. $null = ($value === null || (is_array($value) && empty($value)));
  2199. if (strtolower($operator) === 'not') {
  2200. $data = $this->conditionKeysToString(
  2201. array($operator => array($key => $value)), true, $model
  2202. );
  2203. return $data[0];
  2204. }
  2205. $value = $this->value($value, $type);
  2206. if (!$virtual && $key !== '?') {
  2207. $isKey = (strpos($key, '(') !== false || strpos($key, ')') !== false);
  2208. $key = $isKey ? $this->__quoteFields($key) : $this->name($key);
  2209. }
  2210. if ($bound) {
  2211. return String::insert($key . ' ' . trim($operator), $value);
  2212. }
  2213. if (!preg_match($operatorMatch, trim($operator))) {
  2214. $operator .= ' =';
  2215. }
  2216. $operator = trim($operator);
  2217. if (is_array($value)) {
  2218. $value = implode(', ', $value);
  2219. switch ($operator) {
  2220. case '=':
  2221. $operator = 'IN';
  2222. break;
  2223. case '!=':
  2224. case '<>':
  2225. $operator = 'NOT IN';
  2226. break;
  2227. }
  2228. $value = "({$value})";
  2229. } elseif ($null) {
  2230. switch ($operator) {
  2231. case '=':
  2232. $operator = 'IS';
  2233. break;
  2234. case '!=':
  2235. case '<>':
  2236. $operator = 'IS NOT';
  2237. break;
  2238. }
  2239. }
  2240. if ($virtual) {
  2241. return "({$key}) {$operator} {$value}";
  2242. }
  2243. return "{$key} {$operator} {$value}";
  2244. }
  2245. /**
  2246. * Quotes Model.fields
  2247. *
  2248. * @param string $conditions
  2249. * @return string or false if no match
  2250. * @access private
  2251. */
  2252. function __quoteFields($conditions) {
  2253. $start = $end = null;
  2254. $original = $conditions;
  2255. if (!empty($this->startQuote)) {
  2256. $start = preg_quote($this->startQuote);
  2257. }
  2258. if (!empty($this->endQuote)) {
  2259. $end = preg_quote($this->endQuote);
  2260. }
  2261. $conditions = str_replace(array($start, $end), '', $conditions);
  2262. $conditions = preg_replace_callback('/(?:[\'\"][^\'\"\\\]*(?:\\\.[^\'\"\\\]*)*[\'\"])|([a-z0-9_' . $start . $end . ']*\\.[a-z0-9_' . $start . $end . ']*)/i', array(&$this, '__quoteMatchedField'), $conditions);
  2263. if ($conditions !== null) {
  2264. return $conditions;
  2265. }
  2266. return $original;
  2267. }
  2268. /**
  2269. * Auxiliary function to quote matches `Model.fields` from a preg_replace_callback call
  2270. *
  2271. * @param string matched string
  2272. * @return string quoted strig
  2273. * @access private
  2274. */
  2275. function __quoteMatchedField($match) {
  2276. if (is_numeric($match[0])) {
  2277. return $match[0];
  2278. }
  2279. return $this->name($match[0]);
  2280. }
  2281. /**
  2282. * Returns a limit statement in the correct format for the particular database.
  2283. *
  2284. * @param integer $limit Limit of results returned
  2285. * @param integer $offset Offset from which to start results
  2286. * @return string SQL limit/offset statement
  2287. */
  2288. public function limit($limit, $offset = null) {
  2289. if ($limit) {
  2290. $rt = '';
  2291. if (!strpos(strtolower($limit), 'limit') || strpos(strtolower($limit), 'limit') === 0) {
  2292. $rt = ' LIMIT';
  2293. }
  2294. if ($offset) {
  2295. $rt .= ' ' . $offset . ',';
  2296. }
  2297. $rt .= ' ' . $limit;
  2298. return $rt;
  2299. }
  2300. return null;
  2301. }
  2302. /**
  2303. * Returns an ORDER BY clause as a string.
  2304. *
  2305. * @param string $key Field reference, as a key (i.e. Post.title)
  2306. * @param string $direction Direction (ASC or DESC)
  2307. * @param object $model model reference (used to look for virtual field)
  2308. * @return string ORDER BY clause
  2309. */
  2310. public function order($keys, $direction = 'ASC', $model = null) {
  2311. if (!is_array($keys)) {
  2312. $keys = array($keys);
  2313. }
  2314. $keys = array_filter($keys);
  2315. $result = array();
  2316. while (!empty($keys)) {
  2317. list($key, $dir) = each($keys);
  2318. array_shift($keys);
  2319. if (is_numeric($key)) {
  2320. $key = $dir;
  2321. $dir = $direction;
  2322. }
  2323. if (is_string($key) && strpos($key, ',') && !preg_match('/\(.+\,.+\)/', $key)) {
  2324. $key = array_map('trim', explode(',', $key));
  2325. }
  2326. if (is_array($key)) {
  2327. //Flatten the array
  2328. $key = array_reverse($key, true);
  2329. foreach ($key as $k => $v) {
  2330. if (is_numeric($k)) {
  2331. array_unshift($keys, $v);
  2332. } else {
  2333. $keys = array($k => $v) + $keys;
  2334. }
  2335. }
  2336. continue;
  2337. } elseif (is_object($key) && isset($key->type) && $key->type === 'expression') {
  2338. $result[] = $key->value;
  2339. continue;
  2340. }
  2341. if (preg_match('/\\x20(ASC|DESC).*/i', $key, $_dir)) {
  2342. $dir = $_dir[0];
  2343. $key = preg_replace('/\\x20(ASC|DESC).*/i', '', $key);
  2344. }
  2345. $key = trim($key);
  2346. if (is_object($model) && $model->isVirtualField($key)) {
  2347. $key = '(' . $this->__quoteFields($model->getVirtualField($key)) . ')';
  2348. }
  2349. if (strpos($key, '.')) {
  2350. $key = preg_replace_callback('/([a-zA-Z0-9_]{1,})\\.([a-zA-Z0-9_]{1,})/', array(&$this, '__quoteMatchedField'), $key);
  2351. }
  2352. if (!preg_match('/\s/', $key) && !strpos($key, '.')) {
  2353. $key = $this->name($key);
  2354. }
  2355. $key .= ' ' . trim($dir);
  2356. $result[] = $key;
  2357. }
  2358. if (!empty($result)) {
  2359. return ' ORDER BY ' . implode(', ', $result);
  2360. }
  2361. return '';
  2362. }
  2363. /**
  2364. * Create a GROUP BY SQL clause
  2365. *
  2366. * @param string $group Group By Condition
  2367. * @return mixed string condition or null
  2368. */
  2369. public function group($group, $model = null) {
  2370. if ($group) {
  2371. if (!is_array($group)) {
  2372. $group = array($group);
  2373. }
  2374. foreach($group as $index => $key) {
  2375. if ($model->isVirtualField($key)) {
  2376. $group[$index] = '(' . $model->getVirtualField($key) . ')';
  2377. }
  2378. }
  2379. $group = implode(', ', $group);
  2380. return ' GROUP BY ' . $this->__quoteFields($group);
  2381. }
  2382. return null;
  2383. }
  2384. /**
  2385. * Disconnects database, kills the connection and says the connection is closed.
  2386. *
  2387. * @return void
  2388. */
  2389. public function close() {
  2390. $this->disconnect();
  2391. }
  2392. /**
  2393. * Checks if the specified table contains any record matching specified SQL
  2394. *
  2395. * @param Model $model Model to search
  2396. * @param string $sql SQL WHERE clause (condition only, not the "WHERE" part)
  2397. * @return boolean True if the table has a matching record, else false
  2398. */
  2399. public function hasAny($Model, $sql) {
  2400. $sql = $this->conditions($sql);
  2401. $table = $this->fullTableName($Model);
  2402. $alias = $this->alias . $this->name($Model->alias);
  2403. $where = $sql ? "{$sql}" : ' WHERE 1 = 1';
  2404. $id = $Model->escapeField();
  2405. $out = $this->fetchRow("SELECT COUNT({$id}) {$this->alias}count FROM {$table} {$alias}{$where}");
  2406. if (is_array($out)) {
  2407. return $out[0]['count'];
  2408. }
  2409. return false;
  2410. }
  2411. /**
  2412. * Gets the length of a database-native column description, or null if no length
  2413. *
  2414. * @param string $real Real database-layer column type (i.e. "varchar(255)")
  2415. * @return mixed An integer or string representing the length of the column
  2416. */
  2417. public function length($real) {
  2418. if (!preg_match_all('/([\w\s]+)(?:\((\d+)(?:,(\d+))?\))?(\sunsigned)?(\szerofill)?/', $real, $result)) {
  2419. trigger_error(__("FIXME: Can't parse field: " . $real), E_USER_WARNING);
  2420. $col = str_replace(array(')', 'unsigned'), '', $real);
  2421. $limit = null;
  2422. if (strpos($col, '(') !== false) {
  2423. list($col, $limit) = explode('(', $col);
  2424. }
  2425. if ($limit != null) {
  2426. return intval($limit);
  2427. }
  2428. return null;
  2429. }
  2430. $types = array(
  2431. 'int' => 1, 'tinyint' => 1, 'smallint' => 1, 'mediumint' => 1, 'integer' => 1, 'bigint' => 1
  2432. );
  2433. list($real, $type, $length, $offset, $sign, $zerofill) = $result;
  2434. $typeArr = $type;
  2435. $type = $type[0];
  2436. $length = $length[0];
  2437. $offset = $offset[0];
  2438. $isFloat = in_array($type, array('dec', 'decimal', 'float', 'numeric', 'double'));
  2439. if ($isFloat && $offset) {
  2440. return $length.','.$offset;
  2441. }
  2442. if (($real[0] == $type) && (count($real) == 1)) {
  2443. return null;
  2444. }
  2445. if (isset($types[$type])) {
  2446. $length += $types[$type];
  2447. if (!empty($sign)) {
  2448. $length--;
  2449. }
  2450. } elseif (in_array($type, array('enum', 'set'))) {
  2451. $length = 0;
  2452. foreach ($typeArr as $key => $enumValue) {
  2453. if ($key == 0) {
  2454. continue;
  2455. }
  2456. $tmpLength = strlen($enumValue);
  2457. if ($tmpLength > $length) {
  2458. $length = $tmpLength;
  2459. }
  2460. }
  2461. }
  2462. return intval($length);
  2463. }
  2464. /**
  2465. * Translates between PHP boolean values and Database (faked) boolean values
  2466. *
  2467. * @param mixed $data Value to be translated
  2468. * @return int Converted boolean value
  2469. */
  2470. public function boolean($data) {
  2471. if ($data === true || $data === false) {
  2472. if ($data === true) {
  2473. return 1;
  2474. }
  2475. return 0;
  2476. } else {
  2477. return (int) !empty($data);
  2478. }
  2479. }
  2480. /**
  2481. * Inserts multiple values into a table
  2482. *
  2483. * @param string $table
  2484. * @param string $fields
  2485. * @param array $values
  2486. */
  2487. public function insertMulti($table, $fields, $values) {
  2488. $table = $this->fullTableName($table);
  2489. $holder = implode(',', array_fill(0, count($fields), '?'));
  2490. $fields = implode(', ', array_map(array(&$this, 'name'), $fields));
  2491. $count = count($values);
  2492. $sql = "INSERT INTO {$table} ({$fields}) VALUES ({$holder})";
  2493. $statement = $this->_connection->prepare($sql);
  2494. $this->begin();
  2495. for ($x = 0; $x < $count; $x++) {
  2496. $statement->execute($values[$x]);
  2497. $statement->closeCursor();
  2498. }
  2499. return $this->commit();
  2500. }
  2501. /**
  2502. * Returns an array of the indexes in given datasource name.
  2503. *
  2504. * @param string $model Name of model to inspect
  2505. * @return array Fields in table. Keys are column and unique
  2506. */
  2507. public function index($model) {
  2508. return false;
  2509. }
  2510. /**
  2511. * Generate a database-native schema for the given Schema object
  2512. *
  2513. * @param object $schema An instance of a subclass of CakeSchema
  2514. * @param string $tableName Optional. If specified only the table name given will be generated.
  2515. * Otherwise, all tables defined in the schema are generated.
  2516. * @return string
  2517. */
  2518. public function createSchema($schema, $tableName = null) {
  2519. if (!is_a($schema, 'CakeSchema')) {
  2520. trigger_error(__('Invalid schema object'), E_USER_WARNING);
  2521. return null;
  2522. }
  2523. $out = '';
  2524. foreach ($schema->tables as $curTable => $columns) {
  2525. if (!$tableName || $tableName == $curTable) {
  2526. $cols = $colList = $indexes = $tableParameters = array();
  2527. $primary = null;
  2528. $table = $this->fullTableName($curTable);
  2529. foreach ($columns as $name => $col) {
  2530. if (is_string($col)) {
  2531. $col = array('type' => $col);
  2532. }
  2533. if (isset($col['key']) && $col['key'] == 'primary') {
  2534. $primary = $name;
  2535. }
  2536. if ($name !== 'indexes' && $name !== 'tableParameters') {
  2537. $col['name'] = $name;
  2538. if (!isset($col['type'])) {
  2539. $col['type'] = 'string';
  2540. }
  2541. $cols[] = $this->buildColumn($col);
  2542. } elseif ($name == 'indexes') {
  2543. $indexes = array_merge($indexes, $this->buildIndex($col, $table));
  2544. } elseif ($name == 'tableParameters') {
  2545. $tableParameters = array_merge($tableParameters, $this->buildTableParameters($col, $table));
  2546. }
  2547. }
  2548. if (empty($indexes) && !empty($primary)) {
  2549. $col = array('PRIMARY' => array('column' => $primary, 'unique' => 1));
  2550. $indexes = array_merge($indexes, $this->buildIndex($col, $table));
  2551. }
  2552. $columns = $cols;
  2553. $out .= $this->renderStatement('schema', compact('table', 'columns', 'indexes', 'tableParameters')) . "\n\n";
  2554. }
  2555. }
  2556. return $out;
  2557. }
  2558. /**
  2559. * Generate a alter syntax from CakeSchema::compare()
  2560. *
  2561. * @param unknown_type $schema
  2562. * @return boolean
  2563. */
  2564. function alterSchema($compare, $table = null) {
  2565. return false;
  2566. }
  2567. /**
  2568. * Generate a "drop table" statement for the given Schema object
  2569. *
  2570. * @param CakeSchema $schema An instance of a subclass of CakeSchema
  2571. * @param string $table Optional. If specified only the table name given will be generated.
  2572. * Otherwise, all tables defined in the schema are generated.
  2573. * @return string
  2574. */
  2575. public function dropSchema(CakeSchema $schema, $table = null) {
  2576. $out = '';
  2577. foreach ($schema->tables as $curTable => $columns) {
  2578. if (!$table || $table == $curTable) {
  2579. $out .= 'DROP TABLE ' . $this->fullTableName($curTable) . ";\n";
  2580. }
  2581. }
  2582. return $out;
  2583. }
  2584. /**
  2585. * Generate a database-native column schema string
  2586. *
  2587. * @param array $column An array structured like the following: array('name'=>'value', 'type'=>'value'[, options]),
  2588. * where options can be 'default', 'length', or 'key'.
  2589. * @return string
  2590. */
  2591. public function buildColumn($column) {
  2592. $name = $type = null;
  2593. extract(array_merge(array('null' => true), $column));
  2594. if (empty($name) || empty($type)) {
  2595. trigger_error(__('Column name or type not defined in schema'), E_USER_WARNING);
  2596. return null;
  2597. }
  2598. if (!isset($this->columns[$type])) {
  2599. trigger_error(__('Column type %s does not exist', $type), E_USER_WARNING);
  2600. return null;
  2601. }
  2602. $real = $this->columns[$type];
  2603. $out = $this->name($name) . ' ' . $real['name'];
  2604. if (isset($real['limit']) || isset($real['length']) || isset($column['limit']) || isset($column['length'])) {
  2605. if (isset($column['length'])) {
  2606. $length = $column['length'];
  2607. } elseif (isset($column['limit'])) {
  2608. $length = $column['limit'];
  2609. } elseif (isset($real['length'])) {
  2610. $length = $real['length'];
  2611. } else {
  2612. $length = $real['limit'];
  2613. }
  2614. $out .= '(' . $length . ')';
  2615. }
  2616. if (($column['type'] == 'integer' || $column['type'] == 'float' ) && isset($column['default']) && $column['default'] === '') {
  2617. $column['default'] = null;
  2618. }
  2619. $out = $this->_buildFieldParameters($out, $column, 'beforeDefault');
  2620. if (isset($column['key']) && $column['key'] == 'primary' && $type == 'integer') {
  2621. $out .= ' ' . $this->columns['primary_key']['name'];
  2622. } elseif (isset($column['key']) && $column['key'] == 'primary') {
  2623. $out .= ' NOT NULL';
  2624. } elseif (isset($column['default']) && isset($column['null']) && $column['null'] == false) {
  2625. $out .= ' DEFAULT ' . $this->value($column['default'], $type) . ' NOT NULL';
  2626. } elseif (isset($column['default'])) {
  2627. $out .= ' DEFAULT ' . $this->value($column['default'], $type);
  2628. } elseif ($type !== 'timestamp' && !empty($column['null'])) {
  2629. $out .= ' DEFAULT NULL';
  2630. } elseif ($type === 'timestamp' && !empty($column['null'])) {
  2631. $out .= ' NULL';
  2632. } elseif (isset($column['null']) && $column['null'] == false) {
  2633. $out .= ' NOT NULL';
  2634. }
  2635. if ($type == 'timestamp' && isset($column['default']) && strtolower($column['default']) == 'current_timestamp') {
  2636. $out = str_replace(array("'CURRENT_TIMESTAMP'", "'current_timestamp'"), 'CURRENT_TIMESTAMP', $out);
  2637. }
  2638. $out = $this->_buildFieldParameters($out, $column, 'afterDefault');
  2639. return $out;
  2640. }
  2641. /**
  2642. * Build the field parameters, in a position
  2643. *
  2644. * @param string $columnString The partially built column string
  2645. * @param array $columnData The array of column data.
  2646. * @param string $position The position type to use. 'beforeDefault' or 'afterDefault' are common
  2647. * @return string a built column with the field parameters added.
  2648. */
  2649. public function _buildFieldParameters($columnString, $columnData, $position) {
  2650. foreach ($this->fieldParameters as $paramName => $value) {
  2651. if (isset($columnData[$paramName]) && $value['position'] == $position) {
  2652. if (isset($value['options']) && !in_array($columnData[$paramName], $value['options'])) {
  2653. continue;
  2654. }
  2655. $val = $columnData[$paramName];
  2656. if ($value['quote']) {
  2657. $val = $this->value($val);
  2658. }
  2659. $columnString .= ' ' . $value['value'] . $value['join'] . $val;
  2660. }
  2661. }
  2662. return $columnString;
  2663. }
  2664. /**
  2665. * Format indexes for create table
  2666. *
  2667. * @param array $indexes
  2668. * @param string $table
  2669. * @return array
  2670. */
  2671. public function buildIndex($indexes, $table = null) {
  2672. $join = array();
  2673. foreach ($indexes as $name => $value) {
  2674. $out = '';
  2675. if ($name == 'PRIMARY') {
  2676. $out .= 'PRIMARY ';
  2677. $name = null;
  2678. } else {
  2679. if (!empty($value['unique'])) {
  2680. $out .= 'UNIQUE ';
  2681. }
  2682. $name = $this->startQuote . $name . $this->endQuote;
  2683. }
  2684. if (is_array($value['column'])) {
  2685. $out .= 'KEY ' . $name . ' (' . implode(', ', array_map(array(&$this, 'name'), $value['column'])) . ')';
  2686. } else {
  2687. $out .= 'KEY ' . $name . ' (' . $this->name($value['column']) . ')';
  2688. }
  2689. $join[] = $out;
  2690. }
  2691. return $join;
  2692. }
  2693. /**
  2694. * Read additional table parameters
  2695. *
  2696. * @param array $parameters
  2697. * @param string $table
  2698. * @return array
  2699. */
  2700. public function readTableParameters($name) {
  2701. $parameters = array();
  2702. if ($this->isInterfaceSupported('listDetailedSources')) {
  2703. $currentTableDetails = $this->listDetailedSources($name);
  2704. foreach ($this->tableParameters as $paramName => $parameter) {
  2705. if (!empty($parameter['column']) && !empty($currentTableDetails[$parameter['column']])) {
  2706. $parameters[$paramName] = $currentTableDetails[$parameter['column']];
  2707. }
  2708. }
  2709. }
  2710. return $parameters;
  2711. }
  2712. /**
  2713. * Format parameters for create table
  2714. *
  2715. * @param array $parameters
  2716. * @param string $table
  2717. * @return array
  2718. */
  2719. public function buildTableParameters($parameters, $table = null) {
  2720. $result = array();
  2721. foreach ($parameters as $name => $value) {
  2722. if (isset($this->tableParameters[$name])) {
  2723. if ($this->tableParameters[$name]['quote']) {
  2724. $value = $this->value($value);
  2725. }
  2726. $result[] = $this->tableParameters[$name]['value'] . $this->tableParameters[$name]['join'] . $value;
  2727. }
  2728. }
  2729. return $result;
  2730. }
  2731. /**
  2732. * Guesses the data type of an array
  2733. *
  2734. * @param string $value
  2735. * @return void
  2736. */
  2737. public function introspectType($value) {
  2738. if (!is_array($value)) {
  2739. if ($value === true || $value === false) {
  2740. return 'boolean';
  2741. }
  2742. if (is_float($value) && floatval($value) === $value) {
  2743. return 'float';
  2744. }
  2745. if (is_int($value) && intval($value) === $value) {
  2746. return 'integer';
  2747. }
  2748. if (is_string($value) && strlen($value) > 255) {
  2749. return 'text';
  2750. }
  2751. return 'string';
  2752. }
  2753. $isAllFloat = $isAllInt = true;
  2754. $containsFloat = $containsInt = $containsString = false;
  2755. foreach ($value as $key => $valElement) {
  2756. $valElement = trim($valElement);
  2757. if (!is_float($valElement) && !preg_match('/^[\d]+\.[\d]+$/', $valElement)) {
  2758. $isAllFloat = false;
  2759. } else {
  2760. $containsFloat = true;
  2761. continue;
  2762. }
  2763. if (!is_int($valElement) && !preg_match('/^[\d]+$/', $valElement)) {
  2764. $isAllInt = false;
  2765. } else {
  2766. $containsInt = true;
  2767. continue;
  2768. }
  2769. $containsString = true;
  2770. }
  2771. if ($isAllFloat) {
  2772. return 'float';
  2773. }
  2774. if ($isAllInt) {
  2775. return 'integer';
  2776. }
  2777. if ($containsInt && !$containsString) {
  2778. return 'integer';
  2779. }
  2780. return 'string';
  2781. }
  2782. /**
  2783. * Writes a new key for the in memory sql query cache
  2784. *
  2785. * @param string $sql SQL query
  2786. * @param mixed $data result of $sql query
  2787. * @param array $params query params bound as values
  2788. * @return void
  2789. */
  2790. protected function _writeQueryCache($sql, $data, $params = array()) {
  2791. if (preg_match('/^\s*select/i', $sql)) {
  2792. $this->_queryCache[$sql][serialize($params)] = $data;
  2793. }
  2794. }
  2795. /**
  2796. * Returns the result for a sql query if it is already cached
  2797. *
  2798. * @param string $sql SQL query
  2799. * @param array $params query params bound as values
  2800. * @return mixed results for query if it is cached, false otherwise
  2801. */
  2802. public function getQueryCache($sql, $params = array()) {
  2803. if (isset($this->_queryCache[$sql]) && preg_match('/^\s*select/i', $sql)) {
  2804. $serialized = serialize($params);
  2805. if (isset($this->_queryCache[$sql][$serialized])) {
  2806. return $this->_queryCache[$sql][$serialized];
  2807. }
  2808. }
  2809. return false;
  2810. }
  2811. }