PageRenderTime 64ms CodeModel.GetById 17ms RepoModel.GetById 1ms app.codeStats 0ms

/lib/Cake/Model/Datasource/DboSource.php

https://github.com/aeha/cakephp
PHP | 3094 lines | 2016 code | 260 blank | 818 comment | 536 complexity | f27b6a2c21718903289fd062c738257b MD5 | raw file
  1. <?php
  2. /**
  3. * Dbo Source
  4. *
  5. * PHP 5
  6. *
  7. * CakePHP(tm) : Rapid Development Framework (http://cakephp.org)
  8. * Copyright 2005-2011, 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-2011, Cake Software Foundation, Inc. (http://cakefoundation.org)
  14. * @link http://cakephp.org CakePHP(tm) Project
  15. * @package Cake.Model.Datasource
  16. * @since CakePHP(tm) v 0.10.0.1076
  17. * @license MIT License (http://www.opensource.org/licenses/mit-license.php)
  18. */
  19. App::uses('DataSource', 'Model/Datasource');
  20. App::uses('String', 'Utility');
  21. App::uses('View', 'View');
  22. /**
  23. * DboSource
  24. *
  25. * Creates DBO-descendant objects from a given db connection configuration
  26. *
  27. * @package Cake.Model.Datasource
  28. */
  29. class DboSource extends DataSource {
  30. /**
  31. * Description string for this Database Data Source.
  32. *
  33. * @var string
  34. */
  35. public $description = "Database Data Source";
  36. /**
  37. * index definition, standard cake, primary, index, unique
  38. *
  39. * @var array
  40. */
  41. public $index = array('PRI' => 'primary', 'MUL' => 'index', 'UNI' => 'unique');
  42. /**
  43. * Database keyword used to assign aliases to identifiers.
  44. *
  45. * @var string
  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. */
  56. public static $methodCache = array();
  57. /**
  58. * Whether or not to cache the results of DboSource::name() and DboSource::conditions()
  59. * into the memory cache. Set to false to disable the use of the memory cache.
  60. *
  61. * @var boolean.
  62. */
  63. public $cacheMethods = true;
  64. /**
  65. * Print full query debug info?
  66. *
  67. * @var boolean
  68. */
  69. public $fullDebug = false;
  70. /**
  71. * String to hold how many rows were affected by the last SQL operation.
  72. *
  73. * @var string
  74. */
  75. public $affected = null;
  76. /**
  77. * Number of rows in current resultset
  78. *
  79. * @var integer
  80. */
  81. public $numRows = null;
  82. /**
  83. * Time the last query took
  84. *
  85. * @var integer
  86. */
  87. public $took = null;
  88. /**
  89. * Result
  90. *
  91. * @var array
  92. */
  93. protected $_result = null;
  94. /**
  95. * Queries count.
  96. *
  97. * @var integer
  98. */
  99. protected $_queriesCnt = 0;
  100. /**
  101. * Total duration of all queries.
  102. *
  103. * @var integer
  104. */
  105. protected $_queriesTime = null;
  106. /**
  107. * Log of queries executed by this DataSource
  108. *
  109. * @var array
  110. */
  111. protected $_queriesLog = array();
  112. /**
  113. * Maximum number of items in query log
  114. *
  115. * This is to prevent query log taking over too much memory.
  116. *
  117. * @var integer Maximum number of queries in the queries log.
  118. */
  119. protected $_queriesLogMax = 200;
  120. /**
  121. * Caches serialzed results of executed queries
  122. *
  123. * @var array Maximum number of queries in the queries log.
  124. */
  125. protected $_queryCache = array();
  126. /**
  127. * A reference to the physical connection of this DataSource
  128. *
  129. * @var array
  130. */
  131. protected $_connection = null;
  132. /**
  133. * The DataSource configuration key name
  134. *
  135. * @var string
  136. */
  137. public $configKeyName = null;
  138. /**
  139. * The starting character that this DataSource uses for quoted identifiers.
  140. *
  141. * @var string
  142. */
  143. public $startQuote = null;
  144. /**
  145. * The ending character that this DataSource uses for quoted identifiers.
  146. *
  147. * @var string
  148. */
  149. public $endQuote = null;
  150. /**
  151. * The set of valid SQL operations usable in a WHERE statement
  152. *
  153. * @var array
  154. */
  155. protected $_sqlOps = array('like', 'ilike', 'or', 'not', 'in', 'between', 'regexp', 'similar to');
  156. /**
  157. * Indicates the level of nested transactions
  158. *
  159. * @var integer
  160. */
  161. protected $_transactionNesting = 0;
  162. /**
  163. * Index of basic SQL commands
  164. *
  165. * @var array
  166. */
  167. protected $_commands = array(
  168. 'begin' => 'BEGIN',
  169. 'commit' => 'COMMIT',
  170. 'rollback' => 'ROLLBACK'
  171. );
  172. /**
  173. * Separator string for virtualField composition
  174. *
  175. * @var string
  176. */
  177. public $virtualFieldSeparator = '__';
  178. /**
  179. * List of table engine specific parameters used on table creating
  180. *
  181. * @var array
  182. */
  183. public $tableParameters = array();
  184. /**
  185. * List of engine specific additional field parameters used on table creating
  186. *
  187. * @var array
  188. */
  189. public $fieldParameters = array();
  190. /**
  191. * Indicates whether there was a change on the cached results on the methods of this class
  192. * This will be used for storing in a more persistent cache
  193. *
  194. * @var boolean
  195. */
  196. protected $_methodCacheChange = false;
  197. /**
  198. * Constructor
  199. *
  200. * @param array $config Array of configuration information for the Datasource.
  201. * @param boolean $autoConnect Whether or not the datasource should automatically connect.
  202. */
  203. public function __construct($config = null, $autoConnect = true) {
  204. if (!isset($config['prefix'])) {
  205. $config['prefix'] = '';
  206. }
  207. parent::__construct($config);
  208. $this->fullDebug = Configure::read('debug') > 1;
  209. if (!$this->enabled()) {
  210. throw new MissingConnectionException(array(
  211. 'class' => get_class($this)
  212. ));
  213. }
  214. if ($autoConnect) {
  215. $this->connect();
  216. }
  217. }
  218. /**
  219. * Reconnects to database server with optional new settings
  220. *
  221. * @param array $config An array defining the new configuration settings
  222. * @return boolean True on success, false on failure
  223. */
  224. public function reconnect($config = array()) {
  225. $this->disconnect();
  226. $this->setConfig($config);
  227. $this->_sources = null;
  228. return $this->connect();
  229. }
  230. /**
  231. * Disconnects from database.
  232. *
  233. * @return boolean True if the database could be disconnected, else false
  234. */
  235. public function disconnect() {
  236. if ($this->_result instanceof PDOStatement) {
  237. $this->_result->closeCursor();
  238. }
  239. unset($this->_connection);
  240. $this->connected = false;
  241. return true;
  242. }
  243. /**
  244. * Get the underlying connection object.
  245. *
  246. * @return PDOConnection
  247. */
  248. public function getConnection() {
  249. return $this->_connection;
  250. }
  251. /**
  252. * Returns a quoted and escaped string of $data for use in an SQL statement.
  253. *
  254. * @param string $data String to be prepared for use in an SQL statement
  255. * @param string $column The column into which this data will be inserted
  256. * @return string Quoted and escaped data
  257. */
  258. public function value($data, $column = null) {
  259. if (is_array($data) && !empty($data)) {
  260. return array_map(
  261. array(&$this, 'value'),
  262. $data, array_fill(0, count($data), $column)
  263. );
  264. } elseif (is_object($data) && isset($data->type, $data->value)) {
  265. if ($data->type == 'identifier') {
  266. return $this->name($data->value);
  267. } elseif ($data->type == 'expression') {
  268. return $data->value;
  269. }
  270. } elseif (in_array($data, array('{$__cakeID__$}', '{$__cakeForeignKey__$}'), true)) {
  271. return $data;
  272. }
  273. if ($data === null || (is_array($data) && empty($data))) {
  274. return 'NULL';
  275. }
  276. if (empty($column)) {
  277. $column = $this->introspectType($data);
  278. }
  279. switch ($column) {
  280. case 'binary':
  281. return $this->_connection->quote($data, PDO::PARAM_LOB);
  282. break;
  283. case 'boolean':
  284. return $this->_connection->quote($this->boolean($data, true), PDO::PARAM_BOOL);
  285. break;
  286. case 'string':
  287. case 'text':
  288. return $this->_connection->quote($data, PDO::PARAM_STR);
  289. default:
  290. if ($data === '') {
  291. return 'NULL';
  292. }
  293. if (is_float($data)) {
  294. return str_replace(',', '.', strval($data));
  295. }
  296. if ((is_int($data) || $data === '0') || (
  297. is_numeric($data) && strpos($data, ',') === false &&
  298. $data[0] != '0' && strpos($data, 'e') === false)
  299. ) {
  300. return $data;
  301. }
  302. return $this->_connection->quote($data);
  303. break;
  304. }
  305. }
  306. /**
  307. * Returns an object to represent a database identifier in a query. Expression objects
  308. * are not sanitized or esacped.
  309. *
  310. * @param string $identifier A SQL expression to be used as an identifier
  311. * @return stdClass An object representing a database identifier to be used in a query
  312. */
  313. public function identifier($identifier) {
  314. $obj = new stdClass();
  315. $obj->type = 'identifier';
  316. $obj->value = $identifier;
  317. return $obj;
  318. }
  319. /**
  320. * Returns an object to represent a database expression in a query. Expression objects
  321. * are not sanitized or esacped.
  322. *
  323. * @param string $expression An arbitrary SQL expression to be inserted into a query.
  324. * @return stdClass An object representing a database expression to be used in a query
  325. */
  326. public function expression($expression) {
  327. $obj = new stdClass();
  328. $obj->type = 'expression';
  329. $obj->value = $expression;
  330. return $obj;
  331. }
  332. /**
  333. * Executes given SQL statement.
  334. *
  335. * @param string $sql SQL statement
  336. * @param array $params Additional options for the query.
  337. * @return boolean
  338. */
  339. public function rawQuery($sql, $params = array()) {
  340. $this->took = $this->numRows = false;
  341. return $this->execute($sql, $params);
  342. }
  343. /**
  344. * Queries the database with given SQL statement, and obtains some metadata about the result
  345. * (rows affected, timing, any errors, number of rows in resultset). The query is also logged.
  346. * If Configure::read('debug') is set, the log is shown all the time, else it is only shown on errors.
  347. *
  348. * ### Options
  349. *
  350. * - log - Whether or not the query should be logged to the memory log.
  351. *
  352. * @param string $sql
  353. * @param array $options
  354. * @param array $params values to be bided to the query
  355. * @return mixed Resource or object representing the result set, or false on failure
  356. */
  357. public function execute($sql, $options = array(), $params = array()) {
  358. $options += array('log' => $this->fullDebug);
  359. $t = microtime(true);
  360. $this->_result = $this->_execute($sql, $params);
  361. if ($options['log']) {
  362. $this->took = round((microtime(true) - $t) * 1000, 0);
  363. $this->numRows = $this->affected = $this->lastAffected();
  364. $this->logQuery($sql);
  365. }
  366. return $this->_result;
  367. }
  368. /**
  369. * Executes given SQL statement.
  370. *
  371. * @param string $sql SQL statement
  372. * @param array $params list of params to be bound to query
  373. * @param array $prepareOptions Options to be used in the prepare statement
  374. * @return mixed PDOStatement if query executes with no problem, true as the result of a successful, false on error
  375. * query returning no rows, suchs as a CREATE statement, false otherwise
  376. */
  377. protected function _execute($sql, $params = array(), $prepareOptions = array()) {
  378. $sql = trim($sql);
  379. if (preg_match('/^(?:CREATE|ALTER|DROP)/i', $sql)) {
  380. $statements = array_filter(explode(';', $sql));
  381. if (count($statements) > 1) {
  382. $result = array_map(array($this, '_execute'), $statements);
  383. return array_search(false, $result) === false;
  384. }
  385. }
  386. try {
  387. $query = $this->_connection->prepare($sql, $prepareOptions);
  388. $query->setFetchMode(PDO::FETCH_LAZY);
  389. if (!$query->execute($params)) {
  390. $this->_results = $query;
  391. $query->closeCursor();
  392. return false;
  393. }
  394. if (!$query->columnCount()) {
  395. $query->closeCursor();
  396. return true;
  397. }
  398. return $query;
  399. } catch (PDOException $e) {
  400. if (isset($query->queryString)) {
  401. $e->queryString = $query->queryString;
  402. } else {
  403. $e->queryString = $sql;
  404. }
  405. throw $e;
  406. }
  407. }
  408. /**
  409. * Returns a formatted error message from previous database operation.
  410. *
  411. * @param PDOStatement $query the query to extract the error from if any
  412. * @return string Error message with error number
  413. */
  414. public function lastError(PDOStatement $query = null) {
  415. if ($query) {
  416. $error = $query->errorInfo();
  417. } else {
  418. $error = $this->_connection->errorInfo();
  419. }
  420. if (empty($error[2])) {
  421. return null;
  422. }
  423. return $error[1] . ': ' . $error[2];
  424. }
  425. /**
  426. * Returns number of affected rows in previous database operation. If no previous operation exists,
  427. * this returns false.
  428. *
  429. * @param mixed $source
  430. * @return integer Number of affected rows
  431. */
  432. public function lastAffected($source = null) {
  433. if ($this->hasResult()) {
  434. return $this->_result->rowCount();
  435. }
  436. return null;
  437. }
  438. /**
  439. * Returns number of rows in previous resultset. If no previous resultset exists,
  440. * this returns false.
  441. *
  442. * @param mixed $source Not used
  443. * @return integer Number of rows in resultset
  444. */
  445. public function lastNumRows($source = null) {
  446. return $this->lastAffected();
  447. }
  448. /**
  449. * DataSource Query abstraction
  450. *
  451. * @return resource Result resource identifier.
  452. */
  453. public function query() {
  454. $args = func_get_args();
  455. $fields = null;
  456. $order = null;
  457. $limit = null;
  458. $page = null;
  459. $recursive = null;
  460. if (count($args) === 1) {
  461. return $this->fetchAll($args[0]);
  462. } elseif (count($args) > 1 && (strpos($args[0], 'findBy') === 0 || strpos($args[0], 'findAllBy') === 0)) {
  463. $params = $args[1];
  464. if (substr($args[0], 0, 6) === 'findBy') {
  465. $all = false;
  466. $field = Inflector::underscore(substr($args[0], 6));
  467. } else {
  468. $all = true;
  469. $field = Inflector::underscore(substr($args[0], 9));
  470. }
  471. $or = (strpos($field, '_or_') !== false);
  472. if ($or) {
  473. $field = explode('_or_', $field);
  474. } else {
  475. $field = explode('_and_', $field);
  476. }
  477. $off = count($field) - 1;
  478. if (isset($params[1 + $off])) {
  479. $fields = $params[1 + $off];
  480. }
  481. if (isset($params[2 + $off])) {
  482. $order = $params[2 + $off];
  483. }
  484. if (!array_key_exists(0, $params)) {
  485. return false;
  486. }
  487. $c = 0;
  488. $conditions = array();
  489. foreach ($field as $f) {
  490. $conditions[$args[2]->alias . '.' . $f] = $params[$c++];
  491. }
  492. if ($or) {
  493. $conditions = array('OR' => $conditions);
  494. }
  495. if ($all) {
  496. if (isset($params[3 + $off])) {
  497. $limit = $params[3 + $off];
  498. }
  499. if (isset($params[4 + $off])) {
  500. $page = $params[4 + $off];
  501. }
  502. if (isset($params[5 + $off])) {
  503. $recursive = $params[5 + $off];
  504. }
  505. return $args[2]->find('all', compact('conditions', 'fields', 'order', 'limit', 'page', 'recursive'));
  506. } else {
  507. if (isset($params[3 + $off])) {
  508. $recursive = $params[3 + $off];
  509. }
  510. return $args[2]->find('first', compact('conditions', 'fields', 'order', 'recursive'));
  511. }
  512. } else {
  513. if (isset($args[1]) && $args[1] === true) {
  514. return $this->fetchAll($args[0], true);
  515. } else if (isset($args[1]) && !is_array($args[1]) ) {
  516. return $this->fetchAll($args[0], false);
  517. } else if (isset($args[1]) && is_array($args[1])) {
  518. $offset = 0;
  519. if (isset($args[2])) {
  520. $cache = $args[2];
  521. } else {
  522. $cache = true;
  523. }
  524. return $this->fetchAll($args[0], $args[1], array('cache' => $cache));
  525. }
  526. }
  527. }
  528. /**
  529. * Returns a row from current resultset as an array
  530. *
  531. * @param string $sql Some SQL to be executed.
  532. * @return array The fetched row as an array
  533. */
  534. public function fetchRow($sql = null) {
  535. if (is_string($sql) && strlen($sql) > 5 && !$this->execute($sql)) {
  536. return null;
  537. }
  538. if ($this->hasResult()) {
  539. $this->resultSet($this->_result);
  540. $resultRow = $this->fetchResult();
  541. if (isset($resultRow[0])) {
  542. $this->fetchVirtualField($resultRow);
  543. }
  544. return $resultRow;
  545. } else {
  546. return null;
  547. }
  548. }
  549. /**
  550. * Returns an array of all result rows for a given SQL query.
  551. * Returns false if no rows matched.
  552. *
  553. *
  554. * ### Options
  555. *
  556. * - `cache` - Returns the cached version of the query, if exists and stores the result in cache.
  557. * This is a non-persistent cache, and only lasts for a single request. This option
  558. * defaults to true. If you are directly calling this method, you can disable caching
  559. * by setting $options to `false`
  560. *
  561. * @param string $sql SQL statement
  562. * @param array $params parameters to be bound as values for the SQL statement
  563. * @param array $options additional options for the query.
  564. * @return array Array of resultset rows, or false if no rows matched
  565. */
  566. public function fetchAll($sql, $params = array(), $options = array()) {
  567. if (is_string($options)) {
  568. $options = array('modelName' => $options);
  569. }
  570. if (is_bool($params)) {
  571. $options['cache'] = $params;
  572. $params = array();
  573. }
  574. $options += array('cache' => true);
  575. $cache = $options['cache'];
  576. if ($cache && ($cached = $this->getQueryCache($sql, $params)) !== false) {
  577. return $cached;
  578. }
  579. if ($result = $this->execute($sql, array(), $params)) {
  580. $out = array();
  581. if ($this->hasResult()) {
  582. $first = $this->fetchRow();
  583. if ($first != null) {
  584. $out[] = $first;
  585. }
  586. while ($item = $this->fetchResult()) {
  587. if (isset($item[0])) {
  588. $this->fetchVirtualField($item);
  589. }
  590. $out[] = $item;
  591. }
  592. }
  593. if (!is_bool($result) && $cache) {
  594. $this->_writeQueryCache($sql, $out, $params);
  595. }
  596. if (empty($out) && is_bool($this->_result)) {
  597. return $this->_result;
  598. }
  599. return $out;
  600. }
  601. return false;
  602. }
  603. /**
  604. * Fetches the next row from the current result set
  605. *
  606. * @return boolean
  607. */
  608. public function fetchResult() {
  609. return false;
  610. }
  611. /**
  612. * Modifies $result array to place virtual fields in model entry where they belongs to
  613. *
  614. * @param array $result Reference to the fetched row
  615. * @return void
  616. */
  617. public function fetchVirtualField(&$result) {
  618. if (isset($result[0]) && is_array($result[0])) {
  619. foreach ($result[0] as $field => $value) {
  620. if (strpos($field, $this->virtualFieldSeparator) === false) {
  621. continue;
  622. }
  623. list($alias, $virtual) = explode($this->virtualFieldSeparator, $field);
  624. if (!ClassRegistry::isKeySet($alias)) {
  625. return;
  626. }
  627. $model = ClassRegistry::getObject($alias);
  628. if ($model->isVirtualField($virtual)) {
  629. $result[$alias][$virtual] = $value;
  630. unset($result[0][$field]);
  631. }
  632. }
  633. if (empty($result[0])) {
  634. unset($result[0]);
  635. }
  636. }
  637. }
  638. /**
  639. * Returns a single field of the first of query results for a given SQL query, or false if empty.
  640. *
  641. * @param string $name Name of the field
  642. * @param string $sql SQL query
  643. * @return mixed Value of field read.
  644. */
  645. public function field($name, $sql) {
  646. $data = $this->fetchRow($sql);
  647. if (empty($data[$name])) {
  648. return false;
  649. }
  650. return $data[$name];
  651. }
  652. /**
  653. * Empties the method caches.
  654. * These caches are used by DboSource::name() and DboSource::conditions()
  655. *
  656. * @return void
  657. */
  658. public function flushMethodCache() {
  659. $this->_methodCacheChange = true;
  660. self::$methodCache = array();
  661. }
  662. /**
  663. * Cache a value into the methodCaches. Will respect the value of DboSource::$cacheMethods.
  664. * Will retrieve a value from the cache if $value is null.
  665. *
  666. * If caching is disabled and a write is attempted, the $value will be returned.
  667. * A read will either return the value or null.
  668. *
  669. * @param string $method Name of the method being cached.
  670. * @param string $key The keyname for the cache operation.
  671. * @param mixed $value The value to cache into memory.
  672. * @return mixed Either null on failure, or the value if its set.
  673. */
  674. public function cacheMethod($method, $key, $value = null) {
  675. if ($this->cacheMethods === false) {
  676. return $value;
  677. }
  678. if (empty(self::$methodCache)) {
  679. self::$methodCache = Cache::read('method_cache', '_cake_core_');
  680. }
  681. if ($value === null) {
  682. return (isset(self::$methodCache[$method][$key])) ? self::$methodCache[$method][$key] : null;
  683. }
  684. $this->_methodCacheChange = true;
  685. return self::$methodCache[$method][$key] = $value;
  686. }
  687. /**
  688. * Returns a quoted name of $data for use in an SQL statement.
  689. * Strips fields out of SQL functions before quoting.
  690. *
  691. * Results of this method are stored in a memory cache. This improves performance, but
  692. * because the method uses a simple hashing algorithm it can infrequently have collisions.
  693. * Setting DboSource::$cacheMethods to false will disable the memory cache.
  694. *
  695. * @param mixed $data Either a string with a column to quote. An array of columns to quote or an
  696. * object from DboSource::expression() or DboSource::identifier()
  697. * @return string SQL field
  698. */
  699. public function name($data) {
  700. if (is_object($data) && isset($data->type)) {
  701. return $data->value;
  702. }
  703. if ($data === '*') {
  704. return '*';
  705. }
  706. if (is_array($data)) {
  707. foreach ($data as $i => $dataItem) {
  708. $data[$i] = $this->name($dataItem);
  709. }
  710. return $data;
  711. }
  712. $cacheKey = crc32($this->startQuote.$data.$this->endQuote);
  713. if ($return = $this->cacheMethod(__FUNCTION__, $cacheKey)) {
  714. return $return;
  715. }
  716. $data = trim($data);
  717. if (preg_match('/^[\w-]+(?:\.[^ \*]*)*$/', $data)) { // string, string.string
  718. if (strpos($data, '.') === false) { // string
  719. return $this->cacheMethod(__FUNCTION__, $cacheKey, $this->startQuote . $data . $this->endQuote);
  720. }
  721. $items = explode('.', $data);
  722. return $this->cacheMethod(__FUNCTION__, $cacheKey,
  723. $this->startQuote . implode($this->endQuote . '.' . $this->startQuote, $items) . $this->endQuote
  724. );
  725. }
  726. if (preg_match('/^[\w-]+\.\*$/', $data)) { // string.*
  727. return $this->cacheMethod(__FUNCTION__, $cacheKey,
  728. $this->startQuote . str_replace('.*', $this->endQuote . '.*', $data)
  729. );
  730. }
  731. if (preg_match('/^([\w-]+)\((.*)\)$/', $data, $matches)) { // Functions
  732. return $this->cacheMethod(__FUNCTION__, $cacheKey,
  733. $matches[1] . '(' . $this->name($matches[2]) . ')'
  734. );
  735. }
  736. if (
  737. preg_match('/^([\w-]+(\.[\w-]+|\(.*\))*)\s+' . preg_quote($this->alias) . '\s*([\w-]+)$/i', $data, $matches
  738. )) {
  739. return $this->cacheMethod(
  740. __FUNCTION__, $cacheKey,
  741. preg_replace(
  742. '/\s{2,}/', ' ', $this->name($matches[1]) . ' ' . $this->alias . ' ' . $this->name($matches[3])
  743. )
  744. );
  745. }
  746. if (preg_match('/^[\w-_\s]*[\w-_]+/', $data)) {
  747. return $this->cacheMethod(__FUNCTION__, $cacheKey, $this->startQuote . $data . $this->endQuote);
  748. }
  749. return $this->cacheMethod(__FUNCTION__, $cacheKey, $data);
  750. }
  751. /**
  752. * Checks if the source is connected to the database.
  753. *
  754. * @return boolean True if the database is connected, else false
  755. */
  756. public function isConnected() {
  757. return $this->connected;
  758. }
  759. /**
  760. * Checks if the result is valid
  761. *
  762. * @return boolean True if the result is valid else false
  763. */
  764. public function hasResult() {
  765. return is_a($this->_result, 'PDOStatement');
  766. }
  767. /**
  768. * Get the query log as an array.
  769. *
  770. * @param boolean $sorted Get the queries sorted by time taken, defaults to false.
  771. * @param boolean $clear If True the existing log will cleared.
  772. * @return array Array of queries run as an array
  773. */
  774. public function getLog($sorted = false, $clear = true) {
  775. if ($sorted) {
  776. $log = sortByKey($this->_queriesLog, 'took', 'desc', SORT_NUMERIC);
  777. } else {
  778. $log = $this->_queriesLog;
  779. }
  780. if ($clear) {
  781. $this->_queriesLog = array();
  782. }
  783. return array('log' => $log, 'count' => $this->_queriesCnt, 'time' => $this->_queriesTime);
  784. }
  785. /**
  786. * Outputs the contents of the queries log. If in a non-CLI environment the sql_log element
  787. * will be rendered and output. If in a CLI environment, a plain text log is generated.
  788. *
  789. * @param boolean $sorted Get the queries sorted by time taken, defaults to false.
  790. * @return void
  791. */
  792. public function showLog($sorted = false) {
  793. $log = $this->getLog($sorted, false);
  794. if (empty($log['log'])) {
  795. return;
  796. }
  797. if (PHP_SAPI != 'cli') {
  798. $controller = null;
  799. $View = new View($controller, false);
  800. $View->set('logs', array($this->configKeyName => $log));
  801. echo $View->element('sql_dump', array('_forced_from_dbo_' => true));
  802. } else {
  803. foreach ($log['log'] as $k => $i) {
  804. print (($k + 1) . ". {$i['query']}\n");
  805. }
  806. }
  807. }
  808. /**
  809. * Log given SQL query.
  810. *
  811. * @param string $sql SQL statement
  812. * @return void
  813. */
  814. public function logQuery($sql) {
  815. $this->_queriesCnt++;
  816. $this->_queriesTime += $this->took;
  817. $this->_queriesLog[] = array(
  818. 'query' => $sql,
  819. 'affected' => $this->affected,
  820. 'numRows' => $this->numRows,
  821. 'took' => $this->took
  822. );
  823. if (count($this->_queriesLog) > $this->_queriesLogMax) {
  824. array_pop($this->_queriesLog);
  825. }
  826. }
  827. /**
  828. * Gets full table name including prefix
  829. *
  830. * @param mixed $model Either a Model object or a string table name.
  831. * @param boolean $quote Whether you want the table name quoted.
  832. * @return string Full quoted table name
  833. */
  834. public function fullTableName($model, $quote = true) {
  835. if (is_object($model)) {
  836. $table = $model->tablePrefix . $model->table;
  837. } elseif (isset($this->config['prefix'])) {
  838. $table = $this->config['prefix'] . strval($model);
  839. } else {
  840. $table = strval($model);
  841. }
  842. if ($quote) {
  843. return $this->name($table);
  844. }
  845. return $table;
  846. }
  847. /**
  848. * The "C" in CRUD
  849. *
  850. * Creates new records in the database.
  851. *
  852. * @param Model $model Model object that the record is for.
  853. * @param array $fields An array of field names to insert. If null, $model->data will be
  854. * used to generate field names.
  855. * @param array $values An array of values with keys matching the fields. If null, $model->data will
  856. * be used to generate values.
  857. * @return boolean Success
  858. */
  859. public function create(Model $model, $fields = null, $values = null) {
  860. $id = null;
  861. if ($fields == null) {
  862. unset($fields, $values);
  863. $fields = array_keys($model->data);
  864. $values = array_values($model->data);
  865. }
  866. $count = count($fields);
  867. for ($i = 0; $i < $count; $i++) {
  868. $valueInsert[] = $this->value($values[$i], $model->getColumnType($fields[$i]));
  869. }
  870. for ($i = 0; $i < $count; $i++) {
  871. $fieldInsert[] = $this->name($fields[$i]);
  872. if ($fields[$i] == $model->primaryKey) {
  873. $id = $values[$i];
  874. }
  875. }
  876. $query = array(
  877. 'table' => $this->fullTableName($model),
  878. 'fields' => implode(', ', $fieldInsert),
  879. 'values' => implode(', ', $valueInsert)
  880. );
  881. if ($this->execute($this->renderStatement('create', $query))) {
  882. if (empty($id)) {
  883. $id = $this->lastInsertId($this->fullTableName($model, false), $model->primaryKey);
  884. }
  885. $model->setInsertID($id);
  886. $model->id = $id;
  887. return true;
  888. }
  889. $model->onError();
  890. return false;
  891. }
  892. /**
  893. * The "R" in CRUD
  894. *
  895. * Reads record(s) from the database.
  896. *
  897. * @param Model $model A Model object that the query is for.
  898. * @param array $queryData An array of queryData information containing keys similar to Model::find()
  899. * @param integer $recursive Number of levels of association
  900. * @return mixed boolean false on error/failure. An array of results on success.
  901. */
  902. public function read(Model $model, $queryData = array(), $recursive = null) {
  903. $queryData = $this->_scrubQueryData($queryData);
  904. $null = null;
  905. $array = array();
  906. $linkedModels = array();
  907. $bypass = false;
  908. if ($recursive === null && isset($queryData['recursive'])) {
  909. $recursive = $queryData['recursive'];
  910. }
  911. if (!is_null($recursive)) {
  912. $_recursive = $model->recursive;
  913. $model->recursive = $recursive;
  914. }
  915. if (!empty($queryData['fields'])) {
  916. $bypass = true;
  917. $queryData['fields'] = $this->fields($model, null, $queryData['fields']);
  918. } else {
  919. $queryData['fields'] = $this->fields($model);
  920. }
  921. $_associations = $model->associations();
  922. if ($model->recursive == -1) {
  923. $_associations = array();
  924. } elseif ($model->recursive == 0) {
  925. unset($_associations[2], $_associations[3]);
  926. }
  927. foreach ($_associations as $type) {
  928. foreach ($model->{$type} as $assoc => $assocData) {
  929. $linkModel = $model->{$assoc};
  930. $external = isset($assocData['external']);
  931. $linkModel->getDataSource();
  932. if ($model->useDbConfig === $linkModel->useDbConfig) {
  933. if ($bypass) {
  934. $assocData['fields'] = false;
  935. }
  936. if (true === $this->generateAssociationQuery($model, $linkModel, $type, $assoc, $assocData, $queryData, $external, $null)) {
  937. $linkedModels[$type . '/' . $assoc] = true;
  938. }
  939. }
  940. }
  941. }
  942. $query = trim($this->generateAssociationQuery($model, null, null, null, null, $queryData, false, $null));
  943. $resultSet = $this->fetchAll($query, $model->cacheQueries);
  944. if ($resultSet === false) {
  945. $model->onError();
  946. return false;
  947. }
  948. $filtered = $this->_filterResults($resultSet, $model);
  949. if ($model->recursive > -1) {
  950. foreach ($_associations as $type) {
  951. foreach ($model->{$type} as $assoc => $assocData) {
  952. $linkModel = $model->{$assoc};
  953. if (!isset($linkedModels[$type . '/' . $assoc])) {
  954. if ($model->useDbConfig === $linkModel->useDbConfig) {
  955. $db = $this;
  956. } else {
  957. $db = ConnectionManager::getDataSource($linkModel->useDbConfig);
  958. }
  959. } elseif ($model->recursive > 1 && ($type === 'belongsTo' || $type === 'hasOne')) {
  960. $db = $this;
  961. }
  962. if (isset($db) && method_exists($db, 'queryAssociation')) {
  963. $stack = array($assoc);
  964. $db->queryAssociation($model, $linkModel, $type, $assoc, $assocData, $array, true, $resultSet, $model->recursive - 1, $stack);
  965. unset($db);
  966. if ($type === 'hasMany') {
  967. $filtered[] = $assoc;
  968. }
  969. }
  970. }
  971. }
  972. $this->_filterResults($resultSet, $model, $filtered);
  973. }
  974. if (!is_null($recursive)) {
  975. $model->recursive = $_recursive;
  976. }
  977. return $resultSet;
  978. }
  979. /**
  980. * Passes association results thru afterFind filters of corresponding model
  981. *
  982. * @param array $results Reference of resultset to be filtered
  983. * @param Model $model Instance of model to operate against
  984. * @param array $filtered List of classes already filtered, to be skipped
  985. * @return array Array of results that have been filtered through $model->afterFind
  986. */
  987. protected function _filterResults(&$results, Model $model, $filtered = array()) {
  988. $current = current($results);
  989. if (!is_array($current)) {
  990. return array();
  991. }
  992. $keys = array_diff(array_keys($current), $filtered, array($model->alias));
  993. $filtering = array();
  994. foreach ($keys as $className) {
  995. if (!isset($model->{$className}) || !is_object($model->{$className})) {
  996. continue;
  997. }
  998. $linkedModel = $model->{$className};
  999. $filtering[] = $className;
  1000. foreach ($results as &$result) {
  1001. $data = $linkedModel->afterFind(array(array($className => $result[$className])), false);
  1002. if (isset($data[0][$className])) {
  1003. $result[$className] = $data[0][$className];
  1004. }
  1005. }
  1006. }
  1007. return $filtering;
  1008. }
  1009. /**
  1010. * Queries associations. Used to fetch results on recursive models.
  1011. *
  1012. * @param Model $model Primary Model object
  1013. * @param Model $linkModel Linked model that
  1014. * @param string $type Association type, one of the model association types ie. hasMany
  1015. * @param string $association
  1016. * @param array $assocData
  1017. * @param array $queryData
  1018. * @param boolean $external Whether or not the association query is on an external datasource.
  1019. * @param array $resultSet Existing results
  1020. * @param integer $recursive Number of levels of association
  1021. * @param array $stack
  1022. * @return mixed
  1023. */
  1024. public function queryAssociation($model, &$linkModel, $type, $association, $assocData, &$queryData, $external = false, &$resultSet, $recursive, $stack) {
  1025. if ($query = $this->generateAssociationQuery($model, $linkModel, $type, $association, $assocData, $queryData, $external, $resultSet)) {
  1026. if (!is_array($resultSet)) {
  1027. throw new CakeException(__d('cake_dev', 'Error in Model %s', get_class($model)));
  1028. }
  1029. if ($type === 'hasMany' && empty($assocData['limit']) && !empty($assocData['foreignKey'])) {
  1030. $ins = $fetch = array();
  1031. foreach ($resultSet as &$result) {
  1032. if ($in = $this->insertQueryData('{$__cakeID__$}', $result, $association, $assocData, $model, $linkModel, $stack)) {
  1033. $ins[] = $in;
  1034. }
  1035. }
  1036. if (!empty($ins)) {
  1037. $ins = array_unique($ins);
  1038. $fetch = $this->fetchAssociated($model, $query, $ins);
  1039. }
  1040. if (!empty($fetch) && is_array($fetch)) {
  1041. if ($recursive > 0) {
  1042. foreach ($linkModel->associations() as $type1) {
  1043. foreach ($linkModel->{$type1} as $assoc1 => $assocData1) {
  1044. $deepModel = $linkModel->{$assoc1};
  1045. $tmpStack = $stack;
  1046. $tmpStack[] = $assoc1;
  1047. if ($linkModel->useDbConfig === $deepModel->useDbConfig) {
  1048. $db = $this;
  1049. } else {
  1050. $db = ConnectionManager::getDataSource($deepModel->useDbConfig);
  1051. }
  1052. $db->queryAssociation($linkModel, $deepModel, $type1, $assoc1, $assocData1, $queryData, true, $fetch, $recursive - 1, $tmpStack);
  1053. }
  1054. }
  1055. }
  1056. }
  1057. $this->_filterResults($fetch, $model);
  1058. return $this->_mergeHasMany($resultSet, $fetch, $association, $model, $linkModel);
  1059. } elseif ($type === 'hasAndBelongsToMany') {
  1060. $ins = $fetch = array();
  1061. foreach ($resultSet as &$result) {
  1062. if ($in = $this->insertQueryData('{$__cakeID__$}', $result, $association, $assocData, $model, $linkModel, $stack)) {
  1063. $ins[] = $in;
  1064. }
  1065. }
  1066. if (!empty($ins)) {
  1067. $ins = array_unique($ins);
  1068. if (count($ins) > 1) {
  1069. $query = str_replace('{$__cakeID__$}', '(' .implode(', ', $ins) .')', $query);
  1070. $query = str_replace('= (', 'IN (', $query);
  1071. } else {
  1072. $query = str_replace('{$__cakeID__$}', $ins[0], $query);
  1073. }
  1074. $query = str_replace(' WHERE 1 = 1', '', $query);
  1075. }
  1076. $foreignKey = $model->hasAndBelongsToMany[$association]['foreignKey'];
  1077. $joinKeys = array($foreignKey, $model->hasAndBelongsToMany[$association]['associationForeignKey']);
  1078. list($with, $habtmFields) = $model->joinModel($model->hasAndBelongsToMany[$association]['with'], $joinKeys);
  1079. $habtmFieldsCount = count($habtmFields);
  1080. $q = $this->insertQueryData($query, null, $association, $assocData, $model, $linkModel, $stack);
  1081. if ($q !== false) {
  1082. $fetch = $this->fetchAll($q, $model->cacheQueries);
  1083. } else {
  1084. $fetch = null;
  1085. }
  1086. }
  1087. $modelAlias = $model->alias;
  1088. $modelPK = $model->primaryKey;
  1089. foreach ($resultSet as &$row) {
  1090. if ($type !== 'hasAndBelongsToMany') {
  1091. $q = $this->insertQueryData($query, $row, $association, $assocData, $model, $linkModel, $stack);
  1092. if ($q !== false) {
  1093. $fetch = $this->fetchAll($q, $model->cacheQueries);
  1094. } else {
  1095. $fetch = null;
  1096. }
  1097. }
  1098. $selfJoin = $linkModel->name === $model->name;
  1099. if (!empty($fetch) && is_array($fetch)) {
  1100. if ($recursive > 0) {
  1101. foreach ($linkModel->associations() as $type1) {
  1102. foreach ($linkModel->{$type1} as $assoc1 => $assocData1) {
  1103. $deepModel = $linkModel->{$assoc1};
  1104. if ($type1 === 'belongsTo' || ($deepModel->alias === $modelAlias && $type === 'belongsTo') || ($deepModel->alias !== $modelAlias)) {
  1105. $tmpStack = $stack;
  1106. $tmpStack[] = $assoc1;
  1107. if ($linkModel->useDbConfig == $deepModel->useDbConfig) {
  1108. $db = $this;
  1109. } else {
  1110. $db = ConnectionManager::getDataSource($deepModel->useDbConfig);
  1111. }
  1112. $db->queryAssociation($linkModel, $deepModel, $type1, $assoc1, $assocData1, $queryData, true, $fetch, $recursive - 1, $tmpStack);
  1113. }
  1114. }
  1115. }
  1116. }
  1117. if ($type === 'hasAndBelongsToMany') {
  1118. $uniqueIds = $merge = array();
  1119. foreach ($fetch as $j => $data) {
  1120. if (isset($data[$with]) && $data[$with][$foreignKey] === $row[$modelAlias][$modelPK]) {
  1121. if ($habtmFieldsCount <= 2) {
  1122. unset($data[$with]);
  1123. }
  1124. $merge[] = $data;
  1125. }
  1126. }
  1127. if (empty($merge) && !isset($row[$association])) {
  1128. $row[$association] = $merge;
  1129. } else {
  1130. $this->_mergeAssociation($row, $merge, $association, $type);
  1131. }
  1132. } else {
  1133. $this->_mergeAssociation($row, $fetch, $association, $type, $selfJoin);
  1134. }
  1135. if (isset($row[$association])) {
  1136. $row[$association] = $linkModel->afterFind($row[$association], false);
  1137. }
  1138. } else {
  1139. $tempArray[0][$association] = false;
  1140. $this->_mergeAssociation($row, $tempArray, $association, $type, $selfJoin);
  1141. }
  1142. }
  1143. }
  1144. }
  1145. /**
  1146. * A more efficient way to fetch associations. Woohoo!
  1147. *
  1148. * @param Model $model Primary model object
  1149. * @param string $query Association query
  1150. * @param array $ids Array of IDs of associated records
  1151. * @return array Association results
  1152. */
  1153. public function fetchAssociated($model, $query, $ids) {
  1154. $query = str_replace('{$__cakeID__$}', implode(', ', $ids), $query);
  1155. if (count($ids) > 1) {
  1156. $query = str_replace('= (', 'IN (', $query);
  1157. }
  1158. return $this->fetchAll($query, $model->cacheQueries);
  1159. }
  1160. /**
  1161. * mergeHasMany - Merge the results of hasMany relations.
  1162. *
  1163. *
  1164. * @param array $resultSet Data to merge into
  1165. * @param array $merge Data to merge
  1166. * @param string $association Name of Model being Merged
  1167. * @param Model $model Model being merged onto
  1168. * @param Model $linkModel Model being merged
  1169. * @return void
  1170. */
  1171. protected function _mergeHasMany(&$resultSet, $merge, $association, $model, $linkModel) {
  1172. $modelAlias = $model->alias;
  1173. $modelPK = $model->primaryKey;
  1174. $modelFK = $model->hasMany[$association]['foreignKey'];
  1175. foreach ($resultSet as &$result) {
  1176. if (!isset($result[$modelAlias])) {
  1177. continue;
  1178. }
  1179. $merged = array();
  1180. foreach ($merge as $data) {
  1181. if ($result[$modelAlias][$modelPK] === $data[$association][$modelFK]) {
  1182. if (count($data) > 1) {
  1183. $data = array_merge($data[$association], $data);
  1184. unset($data[$association]);
  1185. foreach ($data as $key => $name) {
  1186. if (is_numeric($key)) {
  1187. $data[$association][] = $name;
  1188. unset($data[$key]);
  1189. }
  1190. }
  1191. $merged[] = $data;
  1192. } else {
  1193. $merged[] = $data[$association];
  1194. }
  1195. }
  1196. }
  1197. $result = Set::pushDiff($result, array($association => $merged));
  1198. }
  1199. }
  1200. /**
  1201. * Merge association of merge into data
  1202. *
  1203. * @param array $data
  1204. * @param array $merge
  1205. * @param string $association
  1206. * @param string $type
  1207. * @param boolean $selfJoin
  1208. * @return void
  1209. */
  1210. protected function _mergeAssociation(&$data, &$merge, $association, $type, $selfJoin = false) {
  1211. if (isset($merge[0]) && !isset($merge[0][$association])) {
  1212. $association = Inflector::pluralize($association);
  1213. }
  1214. if ($type === 'belongsTo' || $type === 'hasOne') {
  1215. if (isset($merge[$association])) {
  1216. $data[$association] = $merge[$association][0];
  1217. } else {
  1218. if (count($merge[0][$association]) > 1) {
  1219. foreach ($merge[0] as $assoc => $data2) {
  1220. if ($assoc !== $association) {
  1221. $merge[0][$association][$assoc] = $data2;
  1222. }
  1223. }
  1224. }
  1225. if (!isset($data[$association])) {
  1226. if ($merge[0][$association] != null) {
  1227. $data[$association] = $merge[0][$association];
  1228. } else {
  1229. $data[$association] = array();
  1230. }
  1231. } else {
  1232. if (is_array($merge[0][$association])) {
  1233. foreach ($data[$association] as $k => $v) {
  1234. if (!is_array($v)) {
  1235. $dataAssocTmp[$k] = $v;
  1236. }
  1237. }
  1238. foreach ($merge[0][$association] as $k => $v) {
  1239. if (!is_array($v)) {
  1240. $mergeAssocTmp[$k] = $v;
  1241. }
  1242. }
  1243. $dataKeys = array_keys($data);
  1244. $mergeKeys = array_keys($merge[0]);
  1245. if ($mergeKeys[0] === $dataKeys[0] || $mergeKeys === $dataKeys) {
  1246. $data[$association][$association] = $merge[0][$association];
  1247. } else {
  1248. $diff = Set::diff($dataAssocTmp, $mergeAssocTmp);
  1249. $data[$association] = array_merge($merge[0][$association], $diff);
  1250. }
  1251. } elseif ($selfJoin && array_key_exists($association, $merge[0])) {
  1252. $data[$association] = array_merge($data[$association], array($association => array()));
  1253. }
  1254. }
  1255. }
  1256. } else {
  1257. if (isset($merge[0][$association]) && $merge[0][$association] === false) {
  1258. if (!isset($data[$association])) {
  1259. $data[$association] = array();
  1260. }
  1261. } else {
  1262. foreach ($merge as $i => $row) {
  1263. if (count($row) === 1) {
  1264. if (empty($data[$association]) || (isset($data[$association]) && !in_array($row[$association], $data[$association]))) {
  1265. $data[$association][] = $row[$association];
  1266. }
  1267. } elseif (!empty($row)) {
  1268. $tmp = array_merge($row[$association], $row);
  1269. unset($tmp[$association]);
  1270. $data[$association][] = $tmp;
  1271. }
  1272. }
  1273. }
  1274. }
  1275. }
  1276. /**
  1277. * Generates an array representing a query or part of a query from a single model or two associated models
  1278. *
  1279. * @param Model $model
  1280. * @param Model $linkModel
  1281. * @param string $type
  1282. * @param string $association
  1283. * @param array $assocData
  1284. * @param array $queryData
  1285. * @param boolean $external
  1286. * @param array $resultSet
  1287. * @return mixed
  1288. */
  1289. public function generateAssociationQuery($model, $linkModel, $type, $association = null, $assocData = array(), &$queryData, $external = false, &$resultSet) {
  1290. $queryData = $this->_scrubQueryData($queryData);
  1291. $assocData = $this->_scrubQueryData($assocData);
  1292. $modelAlias = $model->alias;
  1293. if (empty($queryData['fields'])) {
  1294. $queryData['fields'] = $this->fields($model, $modelAlias);
  1295. } elseif (!empty($model->hasMany) && $model->recursive > -1) {
  1296. $assocFields = $this->fields($model, $modelAlias, array("{$modelAlias}.{$model->primaryKey}"));
  1297. $passedFields = $queryData['fields'];
  1298. if (count($passedFields) === 1) {
  1299. if (strpos($passedFields[0], $assocFields[0]) === false && !preg_match('/^[a-z]+\(/i', $passedFields[0])) {
  1300. $queryData['fields'] = array_merge($passedFields, $assocFields);
  1301. } else {
  1302. $queryData['fields'] = $passedFields;
  1303. }
  1304. } else {
  1305. $queryData['fields'] = array_merge($passedFields, $assocFields);
  1306. }
  1307. unset($assocFields, $passedFields);
  1308. }
  1309. if ($linkModel === null) {
  1310. return $this->buildStatement(
  1311. array(
  1312. 'fields' => array_unique($queryData['fields']),
  1313. 'table' => $this->fullTableName($model),
  1314. 'alias' => $modelAlias,
  1315. 'limit' => $queryData['limit'],
  1316. 'offset' => $queryData['offset'],
  1317. 'joins' => $queryData['joins'],
  1318. 'conditions' => $queryData['conditions'],
  1319. 'order' => $queryData['order'],
  1320. 'group' => $queryData['group']
  1321. ),
  1322. $model
  1323. );
  1324. }
  1325. if ($external && !empty($assocData['finderQuery'])) {
  1326. return $assocData['finderQuery'];
  1327. }
  1328. $self = $model->name === $linkModel->name;
  1329. $fields = array();
  1330. if ($external || (in_array($type, array('hasOne', 'belongsTo')) && $assocData['fields'] !== false)) {
  1331. $fields = $this->fields($linkModel, $association, $assocData['fields']);
  1332. }
  1333. if (empty($assocData['offset']) && !empty($assocData['page'])) {
  1334. $assocData['offset'] = ($assocData['page'] - 1) * $assocData['limit'];
  1335. }
  1336. $assocData['limit'] = $this->limit($assocData['limit'], $assocData['offset']);
  1337. switch ($type) {
  1338. case 'hasOne':
  1339. case 'belongsTo':
  1340. $conditions = $this->_mergeConditions(
  1341. $assocData['conditions'],
  1342. $this->getConstraint($type, $model, $linkModel, $association, array_merge($assocData, compact('external', 'self')))
  1343. );
  1344. if (!$self && $external) {
  1345. foreach ($conditions as $key => $condition) {
  1346. if (is_numeric($key) && strpos($condition, $modelAlias . '.') !== false) {
  1347. unset($conditions[$key]);
  1348. }
  1349. }
  1350. }
  1351. if ($external) {
  1352. $query = array_merge($assocData, array(
  1353. 'conditions' => $conditions,
  1354. 'table' => $this->fullTableName($linkModel),
  1355. 'fields' => $fields,
  1356. 'alias' => $association,
  1357. 'group' => null
  1358. ));
  1359. $query += array('order' => $assocData['order'], 'limit' => $assocData['limit']);
  1360. } else {
  1361. $join = array(
  1362. 'table' => $linkModel,
  1363. 'alias' => $association,
  1364. 'type' => isset($assocData['type']) ? $assocData['type'] : 'LEFT',
  1365. 'conditions' => trim($this->conditions($conditions, true, false, $model))
  1366. );
  1367. $queryData['fields'] = array_merge($queryData['fields'], $fields);
  1368. if (!empty($assocData['order'])) {
  1369. $queryData['order'][] = $assocData['order'];
  1370. }
  1371. if (!in_array($join, $queryData['joins'])) {
  1372. $queryData['joins'][] = $join;
  1373. }
  1374. return true;
  1375. }
  1376. break;
  1377. case 'hasMany':
  1378. $assocData['fields'] = $this->fields($linkModel, $association, $assocData['fields']);
  1379. if (!empty($assocData['foreignKey'])) {
  1380. $assocData['fields'] = array_merge($assocData['fields'], $this->fields($linkModel, $association, array("{$association}.{$assocData['foreignKey']}")));
  1381. }
  1382. $query = array(
  1383. 'conditions' => $this->_mergeConditions($this->getConstraint('hasMany', $model, $linkModel, $association, $assocData), $assocData['conditions']),
  1384. 'fields' => array_unique($assocData['fields']),
  1385. 'table' => $this->fullTableName($linkModel),
  1386. 'alias' => $association,
  1387. 'order' => $assocData['order'],
  1388. 'limit' => $assocData['limit'],
  1389. 'group' => null
  1390. );
  1391. break;
  1392. case 'hasAndBelongsToMany':
  1393. $joinFields = array();
  1394. $joinAssoc = null;
  1395. if (isset($assocData['with']) && !empty($assocData['with'])) {
  1396. $joinKeys = array($assocData['foreignKey'], $assocData['associationForeignKey']);
  1397. list($with, $joinFields) = $model->joinModel($assocData['with'], $joinKeys);
  1398. $joinTbl = $model->{$with};
  1399. $joinAlias = $joinTbl;
  1400. if (is_array($joinFields) && !empty($joinFields)) {
  1401. $joinAssoc = $joinAlias = $model->{$with}->alias;
  1402. $joinFields = $this->fields($model->{$with}, $joinAlias, $joinFields);
  1403. } else {
  1404. $joinFields = array();
  1405. }
  1406. } else {
  1407. $joinTbl = $assocData['joinTable'];
  1408. $joinAlias = $this->fullTableName($assocData['joinTable']);
  1409. }
  1410. $query = array(
  1411. 'conditions' => $assocData['conditions'],
  1412. 'limit' => $assocData['limit'],
  1413. 'table' => $this->fullTableName($linkModel),
  1414. 'alias' => $association,
  1415. 'fields' => array_merge($this->fields($linkModel, $association, $assocData['fields']), $joinFields),
  1416. 'order' => $assocData['order'],
  1417. 'group' => null,
  1418. 'joins' => array(array(
  1419. 'table' => $joinTbl,
  1420. 'alias' => $joinAssoc,
  1421. 'conditions' => $this->getConstraint('hasAndBelongsToMany', $model, $linkModel, $joinAlias, $assocData, $association)
  1422. ))
  1423. );
  1424. break;
  1425. }
  1426. if (isset($query)) {
  1427. return $this->buildStatement($query, $model);
  1428. }
  1429. return null;
  1430. }
  1431. /**
  1432. * Returns a conditions array for the constraint between two models
  1433. *
  1434. * @param string $type Association type
  1435. * @param Model $model Model object
  1436. * @param string $linkModel
  1437. * @param string $alias
  1438. * @param array $assoc
  1439. * @param string $alias2
  1440. * @return array Conditions array defining the constraint between $model and $association
  1441. */
  1442. public function getConstraint($type, $model, $linkModel, $alias, $assoc, $alias2 = null) {
  1443. $assoc += array('external' => false, 'self' => false);
  1444. if (empty($assoc['foreignKey'])) {
  1445. return array();
  1446. }
  1447. switch (true) {
  1448. case ($assoc['external'] && $type === 'hasOne'):
  1449. return array("{$alias}.{$assoc['foreignKey']}" => '{$__cakeID__$}');
  1450. case ($assoc['external'] && $type === 'belongsTo'):
  1451. return array("{$alias}.{$linkModel->primaryKey}" => '{$__cakeForeignKey__$}');
  1452. case (!$assoc['external'] && $type === 'hasOne'):
  1453. return array("{$alias}.{$assoc['foreignKey']}" => $this->identifier("{$model->alias}.{$model->primaryKey}"));
  1454. case (!$assoc['external'] && $type === 'belongsTo'):
  1455. return array("{$model->alias}.{$assoc['foreignKey']}" => $this->identifier("{$alias}.{$linkModel->primaryKey}"));
  1456. case ($type === 'hasMany'):
  1457. return array("{$alias}.{$assoc['foreignKey']}" => array('{$__cakeID__$}'));
  1458. case ($type === 'hasAndBelongsToMany'):
  1459. return array(
  1460. array("{$alias}.{$assoc['foreignKey']}" => '{$__cakeID__$}'),
  1461. array("{$alias}.{$assoc['associationForeignKey']}" => $this->identifier("{$alias2}.{$linkModel->primaryKey}"))
  1462. );
  1463. }
  1464. return array();
  1465. }
  1466. /**
  1467. * Builds and generates a JOIN statement from an array. Handles final clean-up before conversion.
  1468. *
  1469. * @param array $join An array defining a JOIN statement in a query
  1470. * @return string An SQL JOIN statement to be used in a query
  1471. * @see DboSource::renderJoinStatement()
  1472. * @see DboSource::buildStatement()
  1473. */
  1474. public function buildJoinStatement($join) {
  1475. $data = array_merge(array(
  1476. 'type' => null,
  1477. 'alias' => null,
  1478. 'table' => 'join_table',
  1479. 'conditions' => array()
  1480. ), $join);
  1481. if (!empty($data['alias'])) {
  1482. $data['alias'] = $this->alias . $this->name($data['alias']);
  1483. }
  1484. if (!empty($data['conditions'])) {
  1485. $data['conditions'] = trim($this->conditions($data['conditions'], true, false));
  1486. }
  1487. if (!empty($data['table'])) {
  1488. $data['table'] = $this->fullTableName($data['table']);
  1489. }
  1490. return $this->renderJoinStatement($data);
  1491. }
  1492. /**
  1493. * Builds and generates an SQL statement from an array. Handles final clean-up before conversion.
  1494. *
  1495. * @param array $query An array defining an SQL query
  1496. * @param Model $model The model object which initiated the query
  1497. * @return string An executable SQL statement
  1498. * @see DboSource::renderStatement()
  1499. */
  1500. public function buildStatement($query, $model) {
  1501. $query = array_merge(array('offset' => null, 'joins' => array()), $query);
  1502. if (!empty($query['joins'])) {
  1503. $count = count($query['joins']);
  1504. for ($i = 0; $i < $count; $i++) {
  1505. if (is_array($query['joins'][$i])) {
  1506. $query['joins'][$i] = $this->buildJoinStatement($query['joins'][$i]);
  1507. }
  1508. }
  1509. }
  1510. return $this->renderStatement('select', array(
  1511. 'conditions' => $this->conditions($query['conditions'], true, true, $model),
  1512. 'fields' => implode(', ', $query['fields']),
  1513. 'table' => $query['table'],
  1514. 'alias' => $this->alias . $this->name($query['alias']),
  1515. 'order' => $this->order($query['order'], 'ASC', $model),
  1516. 'limit' => $this->limit($query['limit'], $query['offset']),
  1517. 'joins' => implode(' ', $query['joins']),
  1518. 'group' => $this->group($query['group'], $model)
  1519. ));
  1520. }
  1521. /**
  1522. * Renders a final SQL JOIN statement
  1523. *
  1524. * @param array $data
  1525. * @return string
  1526. */
  1527. public function renderJoinStatement($data) {
  1528. extract($data);
  1529. return trim("{$type} JOIN {$table} {$alias} ON ({$conditions})");
  1530. }
  1531. /**
  1532. * Renders a final SQL statement by putting together the component parts in the correct order
  1533. *
  1534. * @param string $type type of query being run. e.g select, create, update, delete, schema, alter.
  1535. * @param array $data Array of data to insert into the query.
  1536. * @return string Rendered SQL expression to be run.
  1537. */
  1538. public function renderStatement($type, $data) {
  1539. extract($data);
  1540. $aliases = null;
  1541. switch (strtolower($type)) {
  1542. case 'select':
  1543. return "SELECT {$fields} FROM {$table} {$alias} {$joins} {$conditions} {$group} {$order} {$limit}";
  1544. case 'create':
  1545. return "INSERT INTO {$table} ({$fields}) VALUES ({$values})";
  1546. case 'update':
  1547. if (!empty($alias)) {
  1548. $aliases = "{$this->alias}{$alias} {$joins} ";
  1549. }
  1550. return "UPDATE {$table} {$aliases}SET {$fields} {$conditions}";
  1551. case 'delete':
  1552. if (!empty($alias)) {
  1553. $aliases = "{$this->alias}{$alias} {$joins} ";
  1554. }
  1555. return "DELETE {$alias} FROM {$table} {$aliases}{$conditions}";
  1556. case 'schema':
  1557. foreach (array('columns', 'indexes', 'tableParameters') as $var) {
  1558. if (is_array(${$var})) {
  1559. ${$var} = "\t" . join(",\n\t", array_filter(${$var}));
  1560. } else {
  1561. ${$var} = '';
  1562. }
  1563. }
  1564. if (trim($indexes) !== '') {
  1565. $columns .= ',';
  1566. }
  1567. return "CREATE TABLE {$table} (\n{$columns}{$indexes}){$tableParameters};";
  1568. case 'alter':
  1569. return;
  1570. }
  1571. }
  1572. /**
  1573. * Merges a mixed set of string/array conditions
  1574. *
  1575. * @param mixed $query
  1576. * @param mixed $assoc
  1577. * @return array
  1578. */
  1579. protected function _mergeConditions($query, $assoc) {
  1580. if (empty($assoc)) {
  1581. return $query;
  1582. }
  1583. if (is_array($query)) {
  1584. return array_merge((array)$assoc, $query);
  1585. }
  1586. if (!empty($query)) {
  1587. $query = array($query);
  1588. if (is_array($assoc)) {
  1589. $query = array_merge($query, $assoc);
  1590. } else {
  1591. $query[] = $assoc;
  1592. }
  1593. return $query;
  1594. }
  1595. return $assoc;
  1596. }
  1597. /**
  1598. * Generates and executes an SQL UPDATE statement for given model, fields, and values.
  1599. * For databases that do not support aliases in UPDATE queries.
  1600. *
  1601. * @param Model $model
  1602. * @param array $fields
  1603. * @param array $values
  1604. * @param mixed $conditions
  1605. * @return boolean Success
  1606. */
  1607. public function update(Model $model, $fields = array(), $values = null, $conditions = null) {
  1608. if ($values == null) {
  1609. $combined = $fields;
  1610. } else {
  1611. $combined = array_combine($fields, $values);
  1612. }
  1613. $fields = implode(', ', $this->_prepareUpdateFields($model, $combined, empty($conditions)));
  1614. $alias = $joins = null;
  1615. $table = $this->fullTableName($model);
  1616. $conditions = $this->_matchRecords($model, $conditions);
  1617. if ($conditions === false) {
  1618. return false;
  1619. }
  1620. $query = compact('table', 'alias', 'joins', 'fields', 'conditions');
  1621. if (!$this->execute($this->renderStatement('update', $query))) {
  1622. $model->onError();
  1623. return false;
  1624. }
  1625. return true;
  1626. }
  1627. /**
  1628. * Quotes and prepares fields and values for an SQL UPDATE statement
  1629. *
  1630. * @param Model $model
  1631. * @param array $fields
  1632. * @param boolean $quoteValues If values should be quoted, or treated as SQL snippets
  1633. * @param boolean $alias Include the model alias in the field name
  1634. * @return array Fields and values, quoted and preparted
  1635. */
  1636. protected function _prepareUpdateFields($model, $fields, $quoteValues = true, $alias = false) {
  1637. $quotedAlias = $this->startQuote . $model->alias . $this->endQuote;
  1638. $updates = array();
  1639. foreach ($fields as $field => $value) {
  1640. if ($alias && strpos($field, '.') === false) {
  1641. $quoted = $model->escapeField($field);
  1642. } elseif (!$alias && strpos($field, '.') !== false) {
  1643. $quoted = $this->name(str_replace($quotedAlias . '.', '', str_replace(
  1644. $model->alias . '.', '', $field
  1645. )));
  1646. } else {
  1647. $quoted = $this->name($field);
  1648. }
  1649. if ($value === null) {
  1650. $updates[] = $quoted . ' = NULL';
  1651. continue;
  1652. }
  1653. $update = $quoted . ' = ';
  1654. if ($quoteValues) {
  1655. $update .= $this->value($value, $model->getColumnType($field));
  1656. } elseif (!$alias) {
  1657. $update .= str_replace($quotedAlias . '.', '', str_replace(
  1658. $model->alias . '.', '', $value
  1659. ));
  1660. } else {
  1661. $update .= $value;
  1662. }
  1663. $updates[] = $update;
  1664. }
  1665. return $updates;
  1666. }
  1667. /**
  1668. * Generates and executes an SQL DELETE statement.
  1669. * For databases that do not support aliases in UPDATE queries.
  1670. *
  1671. * @param Model $model
  1672. * @param mixed $conditions
  1673. * @return boolean Success
  1674. */
  1675. public function delete(Model $model, $conditions = null) {
  1676. $alias = $joins = null;
  1677. $table = $this->fullTableName($model);
  1678. $conditions = $this->_matchRecords($model, $conditions);
  1679. if ($conditions === false) {
  1680. return false;
  1681. }
  1682. if ($this->execute($this->renderStatement('delete', compact('alias', 'table', 'joins', 'conditions'))) === false) {
  1683. $model->onError();
  1684. return false;
  1685. }
  1686. return true;
  1687. }
  1688. /**
  1689. * Gets a list of record IDs for the given conditions. Used for multi-record updates and deletes
  1690. * in databases that do not support aliases in UPDATE/DELETE queries.
  1691. *
  1692. * @param Model $model
  1693. * @param mixed $conditions
  1694. * @return array List of record IDs
  1695. */
  1696. protected function _matchRecords($model, $conditions = null) {
  1697. if ($conditions === true) {
  1698. $conditions = $this->conditions(true);
  1699. } elseif ($conditions === null) {
  1700. $conditions = $this->conditions($this->defaultConditions($model, $conditions, false), true, true, $model);
  1701. } else {
  1702. $noJoin = true;
  1703. foreach ($conditions as $field => $value) {
  1704. $originalField = $field;
  1705. if (strpos($field, '.') !== false) {
  1706. list($alias, $field) = explode('.', $field);
  1707. $field = ltrim($field, $this->startQuote);
  1708. $field = rtrim($field, $this->endQuote);
  1709. }
  1710. if (!$model->hasField($field)) {
  1711. $noJoin = false;
  1712. break;
  1713. }
  1714. if ($field !== $originalField) {
  1715. $conditions[$field] = $value;
  1716. unset($conditions[$originalField]);
  1717. }
  1718. }
  1719. if ($noJoin === true) {
  1720. return $this->conditions($conditions);
  1721. }
  1722. $idList = $model->find('all', array(
  1723. 'fields' => "{$model->alias}.{$model->primaryKey}",
  1724. 'conditions' => $conditions
  1725. ));
  1726. if (empty($idList)) {
  1727. return false;
  1728. }
  1729. $conditions = $this->conditions(array(
  1730. $model->primaryKey => Set::extract($idList, "{n}.{$model->alias}.{$model->primaryKey}")
  1731. ));
  1732. }
  1733. return $conditions;
  1734. }
  1735. /**
  1736. * Returns an array of SQL JOIN fragments from a model's associations
  1737. *
  1738. * @param Model $model
  1739. * @return array
  1740. */
  1741. protected function _getJoins($model) {
  1742. $join = array();
  1743. $joins = array_merge($model->getAssociated('hasOne'), $model->getAssociated('belongsTo'));
  1744. foreach ($joins as $assoc) {
  1745. if (isset($model->{$assoc}) && $model->useDbConfig == $model->{$assoc}->useDbConfig && $model->{$assoc}->getDataSource()) {
  1746. $assocData = $model->getAssociated($assoc);
  1747. $join[] = $this->buildJoinStatement(array(
  1748. 'table' => $model->{$assoc},
  1749. 'alias' => $assoc,
  1750. 'type' => isset($assocData['type']) ? $assocData['type'] : 'LEFT',
  1751. 'conditions' => trim($this->conditions(
  1752. $this->_mergeConditions($assocData['conditions'], $this->getConstraint($assocData['association'], $model, $model->{$assoc}, $assoc, $assocData)),
  1753. true, false, $model
  1754. ))
  1755. ));
  1756. }
  1757. }
  1758. return $join;
  1759. }
  1760. /**
  1761. * Returns an SQL calculation, i.e. COUNT() or MAX()
  1762. *
  1763. * @param Model $model
  1764. * @param string $func Lowercase name of SQL function, i.e. 'count' or 'max'
  1765. * @param array $params Function parameters (any values must be quoted manually)
  1766. * @return string An SQL calculation function
  1767. */
  1768. public function calculate($model, $func, $params = array()) {
  1769. $params = (array)$params;
  1770. switch (strtolower($func)) {
  1771. case 'count':
  1772. if (!isset($params[0])) {
  1773. $params[0] = '*';
  1774. }
  1775. if (!isset($params[1])) {
  1776. $params[1] = 'count';
  1777. }
  1778. if (is_object($model) && $model->isVirtualField($params[0])){
  1779. $arg = $this->_quoteFields($model->getVirtualField($params[0]));
  1780. } else {
  1781. $arg = $this->name($params[0]);
  1782. }
  1783. return 'COUNT(' . $arg . ') AS ' . $this->name($params[1]);
  1784. case 'max':
  1785. case 'min':
  1786. if (!isset($params[1])) {
  1787. $params[1] = $params[0];
  1788. }
  1789. if (is_object($model) && $model->isVirtualField($params[0])) {
  1790. $arg = $this->_quoteFields($model->getVirtualField($params[0]));
  1791. } else {
  1792. $arg = $this->name($params[0]);
  1793. }
  1794. return strtoupper($func) . '(' . $arg . ') AS ' . $this->name($params[1]);
  1795. break;
  1796. }
  1797. }
  1798. /**
  1799. * Deletes all the records in a table and resets the count of the auto-incrementing
  1800. * primary key, where applicable.
  1801. *
  1802. * @param mixed $table A string or model class representing the table to be truncated
  1803. * @return boolean SQL TRUNCATE TABLE statement, false if not applicable.
  1804. */
  1805. public function truncate($table) {
  1806. return $this->execute('TRUNCATE TABLE ' . $this->fullTableName($table));
  1807. }
  1808. /**
  1809. * Begin a transaction
  1810. *
  1811. * @return boolean True on success, false on fail
  1812. * (i.e. if the database/model does not support transactions,
  1813. * or a transaction has not started).
  1814. */
  1815. public function begin() {
  1816. if ($this->_transactionStarted || $this->_connection->beginTransaction()) {
  1817. $this->_transactionStarted = true;
  1818. $this->_transactionNesting++;
  1819. return true;
  1820. }
  1821. return false;
  1822. }
  1823. /**
  1824. * Commit a transaction
  1825. *
  1826. * @return boolean True on success, false on fail
  1827. * (i.e. if the database/model does not support transactions,
  1828. * or a transaction has not started).
  1829. */
  1830. public function commit() {
  1831. if ($this->_transactionStarted) {
  1832. $this->_transactionNesting--;
  1833. if ($this->_transactionNesting <= 0) {
  1834. $this->_transactionStarted = false;
  1835. $this->_transactionNesting = 0;
  1836. return $this->_connection->commit();
  1837. }
  1838. return true;
  1839. }
  1840. return false;
  1841. }
  1842. /**
  1843. * Rollback a transaction
  1844. *
  1845. * @return boolean True on success, false on fail
  1846. * (i.e. if the database/model does not support transactions,
  1847. * or a transaction has not started).
  1848. */
  1849. public function rollback() {
  1850. if ($this->_transactionStarted && $this->_connection->rollBack()) {
  1851. $this->_transactionStarted = false;
  1852. $this->_transactionNesting = 0;
  1853. return true;
  1854. }
  1855. return false;
  1856. }
  1857. /**
  1858. * Returns the ID generated from the previous INSERT operation.
  1859. *
  1860. * @param mixed $source
  1861. * @return mixed
  1862. */
  1863. public function lastInsertId($source = null) {
  1864. return $this->_connection->lastInsertId();
  1865. }
  1866. /**
  1867. * Creates a default set of conditions from the model if $conditions is null/empty.
  1868. * If conditions are supplied then they will be returned. If a model doesn't exist and no conditions
  1869. * were provided either null or false will be returned based on what was input.
  1870. *
  1871. * @param Model $model
  1872. * @param mixed $conditions Array of conditions, conditions string, null or false. If an array of conditions,
  1873. * or string conditions those conditions will be returned. With other values the model's existance will be checked.
  1874. * If the model doesn't exist a null or false will be returned depending on the input value.
  1875. * @param boolean $useAlias Use model aliases rather than table names when generating conditions
  1876. * @return mixed Either null, false, $conditions or an array of default conditions to use.
  1877. * @see DboSource::update()
  1878. * @see DboSource::conditions()
  1879. */
  1880. public function defaultConditions($model, $conditions, $useAlias = true) {
  1881. if (!empty($conditions)) {
  1882. return $conditions;
  1883. }
  1884. $exists = $model->exists();
  1885. if (!$exists && $conditions !== null) {
  1886. return false;
  1887. } elseif (!$exists) {
  1888. return null;
  1889. }
  1890. $alias = $model->alias;
  1891. if (!$useAlias) {
  1892. $alias = $this->fullTableName($model, false);
  1893. }
  1894. return array("{$alias}.{$model->primaryKey}" => $model->getID());
  1895. }
  1896. /**
  1897. * Returns a key formatted like a string Model.fieldname(i.e. Post.title, or Country.name)
  1898. *
  1899. * @param Model $model
  1900. * @param string $key
  1901. * @param string $assoc
  1902. * @return string
  1903. */
  1904. public function resolveKey(Model $model, $key, $assoc = null) {
  1905. if (empty($assoc)) {
  1906. $assoc = $model->alias;
  1907. }
  1908. if (strpos('.', $key) !== false) {
  1909. return $this->name($model->alias) . '.' . $this->name($key);
  1910. }
  1911. return $key;
  1912. }
  1913. /**
  1914. * Private helper method to remove query metadata in given data array.
  1915. *
  1916. * @param array $data
  1917. * @return array
  1918. */
  1919. protected function _scrubQueryData($data) {
  1920. static $base = null;
  1921. if ($base === null) {
  1922. $base = array_fill_keys(array('conditions', 'fields', 'joins', 'order', 'limit', 'offset', 'group'), array());
  1923. }
  1924. return (array)$data + $base;
  1925. }
  1926. /**
  1927. * Converts model virtual fields into sql expressions to be fetched later
  1928. *
  1929. * @param Model $model
  1930. * @param string $alias Alias tablename
  1931. * @param mixed $fields virtual fields to be used on query
  1932. * @return array
  1933. */
  1934. protected function _constructVirtualFields($model, $alias, $fields) {
  1935. $virtual = array();
  1936. foreach ($fields as $field) {
  1937. $virtualField = $this->name($alias . $this->virtualFieldSeparator . $field);
  1938. $expression = $this->_quoteFields($model->getVirtualField($field));
  1939. $virtual[] = '(' . $expression . ") {$this->alias} {$virtualField}";
  1940. }
  1941. return $virtual;
  1942. }
  1943. /**
  1944. * Generates the fields list of an SQL query.
  1945. *
  1946. * @param Model $model
  1947. * @param string $alias Alias tablename
  1948. * @param mixed $fields
  1949. * @param boolean $quote If false, returns fields array unquoted
  1950. * @return array
  1951. */
  1952. public function fields($model, $alias = null, $fields = array(), $quote = true) {
  1953. if (empty($alias)) {
  1954. $alias = $model->alias;
  1955. }
  1956. $virtualFields = $model->getVirtualField();
  1957. $cacheKey = array(
  1958. $alias,
  1959. get_class($model),
  1960. $model->alias,
  1961. $virtualFields,
  1962. $fields,
  1963. $quote
  1964. );
  1965. $cacheKey = md5(serialize($cacheKey));
  1966. if ($return = $this->cacheMethod(__FUNCTION__, $cacheKey)) {
  1967. return $return;
  1968. }
  1969. $allFields = empty($fields);
  1970. if ($allFields) {
  1971. $fields = array_keys($model->schema());
  1972. } elseif (!is_array($fields)) {
  1973. $fields = String::tokenize($fields);
  1974. }
  1975. $fields = array_values(array_filter($fields));
  1976. $allFields = $allFields || in_array('*', $fields) || in_array($model->alias . '.*', $fields);
  1977. $virtual = array();
  1978. if (!empty($virtualFields)) {
  1979. $virtualKeys = array_keys($virtualFields);
  1980. foreach ($virtualKeys as $field) {
  1981. $virtualKeys[] = $model->alias . '.' . $field;
  1982. }
  1983. $virtual = ($allFields) ? $virtualKeys : array_intersect($virtualKeys, $fields);
  1984. foreach ($virtual as $i => $field) {
  1985. if (strpos($field, '.') !== false) {
  1986. $virtual[$i] = str_replace($model->alias . '.', '', $field);
  1987. }
  1988. $fields = array_diff($fields, array($field));
  1989. }
  1990. $fields = array_values($fields);
  1991. }
  1992. if (!$quote) {
  1993. if (!empty($virtual)) {
  1994. $fields = array_merge($fields, $this->_constructVirtualFields($model, $alias, $virtual));
  1995. }
  1996. return $fields;
  1997. }
  1998. $count = count($fields);
  1999. if ($count >= 1 && !in_array($fields[0], array('*', 'COUNT(*)'))) {
  2000. for ($i = 0; $i < $count; $i++) {
  2001. if (is_string($fields[$i]) && in_array($fields[$i], $virtual)) {
  2002. unset($fields[$i]);
  2003. continue;
  2004. }
  2005. if (is_object($fields[$i]) && isset($fields[$i]->type) && $fields[$i]->type === 'expression') {
  2006. $fields[$i] = $fields[$i]->value;
  2007. } elseif (preg_match('/^\(.*\)\s' . $this->alias . '.*/i', $fields[$i])){
  2008. continue;
  2009. } elseif (!preg_match('/^.+\\(.*\\)/', $fields[$i])) {
  2010. $prepend = '';
  2011. if (strpos($fields[$i], 'DISTINCT') !== false) {
  2012. $prepend = 'DISTINCT ';
  2013. $fields[$i] = trim(str_replace('DISTINCT', '', $fields[$i]));
  2014. }
  2015. $dot = strpos($fields[$i], '.');
  2016. if ($dot === false) {
  2017. $prefix = !(
  2018. strpos($fields[$i], ' ') !== false ||
  2019. strpos($fields[$i], '(') !== false
  2020. );
  2021. $fields[$i] = $this->name(($prefix ? $alias . '.' : '') . $fields[$i]);
  2022. } else {
  2023. $value = array();
  2024. if (strpos($fields[$i], ',') === false) {
  2025. $build = explode('.', $fields[$i]);
  2026. if (!Set::numeric($build)) {
  2027. $fields[$i] = $this->name(implode('.', $build));
  2028. }
  2029. }
  2030. }
  2031. $fields[$i] = $prepend . $fields[$i];
  2032. } elseif (preg_match('/\(([\.\w]+)\)/', $fields[$i], $field)) {
  2033. if (isset($field[1])) {
  2034. if (strpos($field[1], '.') === false) {
  2035. $field[1] = $this->name($alias . '.' . $field[1]);
  2036. } else {
  2037. $field[0] = explode('.', $field[1]);
  2038. if (!Set::numeric($field[0])) {
  2039. $field[0] = implode('.', array_map(array(&$this, 'name'), $field[0]));
  2040. $fields[$i] = preg_replace('/\(' . $field[1] . '\)/', '(' . $field[0] . ')', $fields[$i], 1);
  2041. }
  2042. }
  2043. }
  2044. }
  2045. }
  2046. }
  2047. if (!empty($virtual)) {
  2048. $fields = array_merge($fields, $this->_constructVirtualFields($model, $alias, $virtual));
  2049. }
  2050. return $this->cacheMethod(__FUNCTION__, $cacheKey, array_unique($fields));
  2051. }
  2052. /**
  2053. * Creates a WHERE clause by parsing given conditions data. If an array or string
  2054. * conditions are provided those conditions will be parsed and quoted. If a boolean
  2055. * is given it will be integer cast as condition. Null will return 1 = 1.
  2056. *
  2057. * Results of this method are stored in a memory cache. This improves performance, but
  2058. * because the method uses a simple hashing algorithm it can infrequently have collisions.
  2059. * Setting DboSource::$cacheMethods to false will disable the memory cache.
  2060. *
  2061. * @param mixed $conditions Array or string of conditions, or any value.
  2062. * @param boolean $quoteValues If true, values should be quoted
  2063. * @param boolean $where If true, "WHERE " will be prepended to the return value
  2064. * @param Model $model A reference to the Model instance making the query
  2065. * @return string SQL fragment
  2066. */
  2067. public function conditions($conditions, $quoteValues = true, $where = true, $model = null) {
  2068. $clause = $out = '';
  2069. if ($where) {
  2070. $clause = ' WHERE ';
  2071. }
  2072. if (is_array($conditions) && !empty($conditions)) {
  2073. $out = $this->conditionKeysToString($conditions, $quoteValues, $model);
  2074. if (empty($out)) {
  2075. return $clause . ' 1 = 1';
  2076. }
  2077. return $clause . implode(' AND ', $out);
  2078. }
  2079. if (is_bool($conditions)) {
  2080. return $clause . (int)$conditions . ' = 1';
  2081. }
  2082. if (empty($conditions) || trim($conditions) === '') {
  2083. return $clause . '1 = 1';
  2084. }
  2085. $clauses = '/^WHERE\\x20|^GROUP\\x20BY\\x20|^HAVING\\x20|^ORDER\\x20BY\\x20/i';
  2086. if (preg_match($clauses, $conditions, $match)) {
  2087. $clause = '';
  2088. }
  2089. $conditions = $this->_quoteFields($conditions);
  2090. return $clause . $conditions;
  2091. }
  2092. /**
  2093. * Creates a WHERE clause by parsing given conditions array. Used by DboSource::conditions().
  2094. *
  2095. * @param array $conditions Array or string of conditions
  2096. * @param boolean $quoteValues If true, values should be quoted
  2097. * @param Model $model A reference to the Model instance making the query
  2098. * @return string SQL fragment
  2099. */
  2100. public function conditionKeysToString($conditions, $quoteValues = true, $model = null) {
  2101. $out = array();
  2102. $data = $columnType = null;
  2103. $bool = array('and', 'or', 'not', 'and not', 'or not', 'xor', '||', '&&');
  2104. foreach ($conditions as $key => $value) {
  2105. $join = ' AND ';
  2106. $not = null;
  2107. if (is_array($value)) {
  2108. $valueInsert = (
  2109. !empty($value) &&
  2110. (substr_count($key, '?') === count($value) || substr_count($key, ':') === count($value))
  2111. );
  2112. }
  2113. if (is_numeric($key) && empty($value)) {
  2114. continue;
  2115. } elseif (is_numeric($key) && is_string($value)) {
  2116. $out[] = $not . $this->_quoteFields($value);
  2117. } elseif ((is_numeric($key) && is_array($value)) || in_array(strtolower(trim($key)), $bool)) {
  2118. if (in_array(strtolower(trim($key)), $bool)) {
  2119. $join = ' ' . strtoupper($key) . ' ';
  2120. } else {
  2121. $key = $join;
  2122. }
  2123. $value = $this->conditionKeysToString($value, $quoteValues, $model);
  2124. if (strpos($join, 'NOT') !== false) {
  2125. if (strtoupper(trim($key)) === 'NOT') {
  2126. $key = 'AND ' . trim($key);
  2127. }
  2128. $not = 'NOT ';
  2129. }
  2130. if (empty($value[1])) {
  2131. if ($not) {
  2132. $out[] = $not . '(' . $value[0] . ')';
  2133. } else {
  2134. $out[] = $value[0] ;
  2135. }
  2136. } else {
  2137. $out[] = '(' . $not . '(' . implode(') ' . strtoupper($key) . ' (', $value) . '))';
  2138. }
  2139. } else {
  2140. if (is_object($value) && isset($value->type)) {
  2141. if ($value->type === 'identifier') {
  2142. $data .= $this->name($key) . ' = ' . $this->name($value->value);
  2143. } elseif ($value->type === 'expression') {
  2144. if (is_numeric($key)) {
  2145. $data .= $value->value;
  2146. } else {
  2147. $data .= $this->name($key) . ' = ' . $value->value;
  2148. }
  2149. }
  2150. } elseif (is_array($value) && !empty($value) && !$valueInsert) {
  2151. $keys = array_keys($value);
  2152. if ($keys === array_values($keys)) {
  2153. $count = count($value);
  2154. if ($count === 1) {
  2155. $data = $this->_quoteFields($key) . ' = (';
  2156. } else {
  2157. $data = $this->_quoteFields($key) . ' IN (';
  2158. }
  2159. if ($quoteValues) {
  2160. if (is_object($model)) {
  2161. $columnType = $model->getColumnType($key);
  2162. }
  2163. $data .= implode(', ', $this->value($value, $columnType));
  2164. }
  2165. $data .= ')';
  2166. } else {
  2167. $ret = $this->conditionKeysToString($value, $quoteValues, $model);
  2168. if (count($ret) > 1) {
  2169. $data = '(' . implode(') AND (', $ret) . ')';
  2170. } elseif (isset($ret[0])) {
  2171. $data = $ret[0];
  2172. }
  2173. }
  2174. } elseif (is_numeric($key) && !empty($value)) {
  2175. $data = $this->_quoteFields($value);
  2176. } else {
  2177. $data = $this->_parseKey($model, trim($key), $value);
  2178. }
  2179. if ($data != null) {
  2180. $out[] = $data;
  2181. $data = null;
  2182. }
  2183. }
  2184. }
  2185. return $out;
  2186. }
  2187. /**
  2188. * Extracts a Model.field identifier and an SQL condition operator from a string, formats
  2189. * and inserts values, and composes them into an SQL snippet.
  2190. *
  2191. * @param Model $model Model object initiating the query
  2192. * @param string $key An SQL key snippet containing a field and optional SQL operator
  2193. * @param mixed $value The value(s) to be inserted in the string
  2194. * @return string
  2195. */
  2196. protected function _parseKey($model, $key, $value) {
  2197. $operatorMatch = '/^(((' . implode(')|(', $this->_sqlOps);
  2198. $operatorMatch .= ')\\x20?)|<[>=]?(?![^>]+>)\\x20?|[>=!]{1,3}(?!<)\\x20?)/is';
  2199. $bound = (strpos($key, '?') !== false || (is_array($value) && strpos($key, ':') !== false));
  2200. if (strpos($key, ' ') === false) {
  2201. $operator = '=';
  2202. } else {
  2203. list($key, $operator) = explode(' ', trim($key), 2);
  2204. if (!preg_match($operatorMatch, trim($operator)) && strpos($operator, ' ') !== false) {
  2205. $key = $key . ' ' . $operator;
  2206. $split = strrpos($key, ' ');
  2207. $operator = substr($key, $split);
  2208. $key = substr($key, 0, $split);
  2209. }
  2210. }
  2211. $virtual = false;
  2212. if (is_object($model) && $model->isVirtualField($key)) {
  2213. $key = $this->_quoteFields($model->getVirtualField($key));
  2214. $virtual = true;
  2215. }
  2216. $type = is_object($model) ? $model->getColumnType($key) : null;
  2217. $null = $value === null || (is_array($value) && empty($value));
  2218. if (strtolower($operator) === 'not') {
  2219. $data = $this->conditionKeysToString(
  2220. array($operator => array($key => $value)), true, $model
  2221. );
  2222. return $data[0];
  2223. }
  2224. $value = $this->value($value, $type);
  2225. if (!$virtual && $key !== '?') {
  2226. $isKey = (strpos($key, '(') !== false || strpos($key, ')') !== false);
  2227. $key = $isKey ? $this->_quoteFields($key) : $this->name($key);
  2228. }
  2229. if ($bound) {
  2230. return String::insert($key . ' ' . trim($operator), $value);
  2231. }
  2232. if (!preg_match($operatorMatch, trim($operator))) {
  2233. $operator .= ' =';
  2234. }
  2235. $operator = trim($operator);
  2236. if (is_array($value)) {
  2237. $value = implode(', ', $value);
  2238. switch ($operator) {
  2239. case '=':
  2240. $operator = 'IN';
  2241. break;
  2242. case '!=':
  2243. case '<>':
  2244. $operator = 'NOT IN';
  2245. break;
  2246. }
  2247. $value = "({$value})";
  2248. } elseif ($null || $value === 'NULL') {
  2249. switch ($operator) {
  2250. case '=':
  2251. $operator = 'IS';
  2252. break;
  2253. case '!=':
  2254. case '<>':
  2255. $operator = 'IS NOT';
  2256. break;
  2257. }
  2258. }
  2259. if ($virtual) {
  2260. return "({$key}) {$operator} {$value}";
  2261. }
  2262. return "{$key} {$operator} {$value}";
  2263. }
  2264. /**
  2265. * Quotes Model.fields
  2266. *
  2267. * @param string $conditions
  2268. * @return string or false if no match
  2269. */
  2270. protected function _quoteFields($conditions) {
  2271. $start = $end = null;
  2272. $original = $conditions;
  2273. if (!empty($this->startQuote)) {
  2274. $start = preg_quote($this->startQuote);
  2275. }
  2276. if (!empty($this->endQuote)) {
  2277. $end = preg_quote($this->endQuote);
  2278. }
  2279. $conditions = str_replace(array($start, $end), '', $conditions);
  2280. $conditions = preg_replace_callback('/(?:[\'\"][^\'\"\\\]*(?:\\\.[^\'\"\\\]*)*[\'\"])|([a-z0-9_' . $start . $end . ']*\\.[a-z0-9_' . $start . $end . ']*)/i', array(&$this, '_quoteMatchedField'), $conditions);
  2281. if ($conditions !== null) {
  2282. return $conditions;
  2283. }
  2284. return $original;
  2285. }
  2286. /**
  2287. * Auxiliary function to quote matches `Model.fields` from a preg_replace_callback call
  2288. *
  2289. * @param string $match matched string
  2290. * @return string quoted strig
  2291. */
  2292. protected function _quoteMatchedField($match) {
  2293. if (is_numeric($match[0])) {
  2294. return $match[0];
  2295. }
  2296. return $this->name($match[0]);
  2297. }
  2298. /**
  2299. * Returns a limit statement in the correct format for the particular database.
  2300. *
  2301. * @param integer $limit Limit of results returned
  2302. * @param integer $offset Offset from which to start results
  2303. * @return string SQL limit/offset statement
  2304. */
  2305. public function limit($limit, $offset = null) {
  2306. if ($limit) {
  2307. $rt = '';
  2308. if (!strpos(strtolower($limit), 'limit')) {
  2309. $rt = ' LIMIT';
  2310. }
  2311. if ($offset) {
  2312. $rt .= ' ' . $offset . ',';
  2313. }
  2314. $rt .= ' ' . $limit;
  2315. return $rt;
  2316. }
  2317. return null;
  2318. }
  2319. /**
  2320. * Returns an ORDER BY clause as a string.
  2321. *
  2322. * @param array|string $keys Field reference, as a key (i.e. Post.title)
  2323. * @param string $direction Direction (ASC or DESC)
  2324. * @param Model $model model reference (used to look for virtual field)
  2325. * @return string ORDER BY clause
  2326. */
  2327. public function order($keys, $direction = 'ASC', $model = null) {
  2328. if (!is_array($keys)) {
  2329. $keys = array($keys);
  2330. }
  2331. $keys = array_filter($keys);
  2332. $result = array();
  2333. while (!empty($keys)) {
  2334. list($key, $dir) = each($keys);
  2335. array_shift($keys);
  2336. if (is_numeric($key)) {
  2337. $key = $dir;
  2338. $dir = $direction;
  2339. }
  2340. if (is_string($key) && strpos($key, ',') !== false && !preg_match('/\(.+\,.+\)/', $key)) {
  2341. $key = array_map('trim', explode(',', $key));
  2342. }
  2343. if (is_array($key)) {
  2344. //Flatten the array
  2345. $key = array_reverse($key, true);
  2346. foreach ($key as $k => $v) {
  2347. if (is_numeric($k)) {
  2348. array_unshift($keys, $v);
  2349. } else {
  2350. $keys = array($k => $v) + $keys;
  2351. }
  2352. }
  2353. continue;
  2354. } elseif (is_object($key) && isset($key->type) && $key->type === 'expression') {
  2355. $result[] = $key->value;
  2356. continue;
  2357. }
  2358. if (preg_match('/\\x20(ASC|DESC).*/i', $key, $_dir)) {
  2359. $dir = $_dir[0];
  2360. $key = preg_replace('/\\x20(ASC|DESC).*/i', '', $key);
  2361. }
  2362. $key = trim($key);
  2363. if (is_object($model) && $model->isVirtualField($key)) {
  2364. $key = '(' . $this->_quoteFields($model->getVirtualField($key)) . ')';
  2365. }
  2366. if (strpos($key, '.')) {
  2367. $key = preg_replace_callback('/([a-zA-Z0-9_-]{1,})\\.([a-zA-Z0-9_-]{1,})/', array(&$this, '_quoteMatchedField'), $key);
  2368. }
  2369. if (!preg_match('/\s/', $key) && strpos($key, '.') === false) {
  2370. $key = $this->name($key);
  2371. }
  2372. $key .= ' ' . trim($dir);
  2373. $result[] = $key;
  2374. }
  2375. if (!empty($result)) {
  2376. return ' ORDER BY ' . implode(', ', $result);
  2377. }
  2378. return '';
  2379. }
  2380. /**
  2381. * Create a GROUP BY SQL clause
  2382. *
  2383. * @param string $group Group By Condition
  2384. * @param Model $model
  2385. * @return string string condition or null
  2386. */
  2387. public function group($group, $model = null) {
  2388. if ($group) {
  2389. if (!is_array($group)) {
  2390. $group = array($group);
  2391. }
  2392. foreach($group as $index => $key) {
  2393. if (is_object($model) && $model->isVirtualField($key)) {
  2394. $group[$index] = '(' . $model->getVirtualField($key) . ')';
  2395. }
  2396. }
  2397. $group = implode(', ', $group);
  2398. return ' GROUP BY ' . $this->_quoteFields($group);
  2399. }
  2400. return null;
  2401. }
  2402. /**
  2403. * Disconnects database, kills the connection and says the connection is closed.
  2404. *
  2405. * @return void
  2406. */
  2407. public function close() {
  2408. $this->disconnect();
  2409. }
  2410. /**
  2411. * Checks if the specified table contains any record matching specified SQL
  2412. *
  2413. * @param Model $Model Model to search
  2414. * @param string $sql SQL WHERE clause (condition only, not the "WHERE" part)
  2415. * @return boolean True if the table has a matching record, else false
  2416. */
  2417. public function hasAny($Model, $sql) {
  2418. $sql = $this->conditions($sql);
  2419. $table = $this->fullTableName($Model);
  2420. $alias = $this->alias . $this->name($Model->alias);
  2421. $where = $sql ? "{$sql}" : ' WHERE 1 = 1';
  2422. $id = $Model->escapeField();
  2423. $out = $this->fetchRow("SELECT COUNT({$id}) {$this->alias}count FROM {$table} {$alias}{$where}");
  2424. if (is_array($out)) {
  2425. return $out[0]['count'];
  2426. }
  2427. return false;
  2428. }
  2429. /**
  2430. * Gets the length of a database-native column description, or null if no length
  2431. *
  2432. * @param string $real Real database-layer column type (i.e. "varchar(255)")
  2433. * @return mixed An integer or string representing the length of the column, or null for unknown length.
  2434. */
  2435. public function length($real) {
  2436. if (!preg_match_all('/([\w\s]+)(?:\((\d+)(?:,(\d+))?\))?(\sunsigned)?(\szerofill)?/', $real, $result)) {
  2437. $col = str_replace(array(')', 'unsigned'), '', $real);
  2438. $limit = null;
  2439. if (strpos($col, '(') !== false) {
  2440. list($col, $limit) = explode('(', $col);
  2441. }
  2442. if ($limit !== null) {
  2443. return intval($limit);
  2444. }
  2445. return null;
  2446. }
  2447. $types = array(
  2448. 'int' => 1, 'tinyint' => 1, 'smallint' => 1, 'mediumint' => 1, 'integer' => 1, 'bigint' => 1
  2449. );
  2450. list($real, $type, $length, $offset, $sign, $zerofill) = $result;
  2451. $typeArr = $type;
  2452. $type = $type[0];
  2453. $length = $length[0];
  2454. $offset = $offset[0];
  2455. $isFloat = in_array($type, array('dec', 'decimal', 'float', 'numeric', 'double'));
  2456. if ($isFloat && $offset) {
  2457. return $length . ',' . $offset;
  2458. }
  2459. if (($real[0] == $type) && (count($real) === 1)) {
  2460. return null;
  2461. }
  2462. if (isset($types[$type])) {
  2463. $length += $types[$type];
  2464. if (!empty($sign)) {
  2465. $length--;
  2466. }
  2467. } elseif (in_array($type, array('enum', 'set'))) {
  2468. $length = 0;
  2469. foreach ($typeArr as $key => $enumValue) {
  2470. if ($key === 0) {
  2471. continue;
  2472. }
  2473. $tmpLength = strlen($enumValue);
  2474. if ($tmpLength > $length) {
  2475. $length = $tmpLength;
  2476. }
  2477. }
  2478. }
  2479. return intval($length);
  2480. }
  2481. /**
  2482. * Translates between PHP boolean values and Database (faked) boolean values
  2483. *
  2484. * @param mixed $data Value to be translated
  2485. * @param boolean $quote
  2486. * @return string|boolean Converted boolean value
  2487. */
  2488. public function boolean($data, $quote = false) {
  2489. if ($quote) {
  2490. return !empty($data) ? '1' : '0';
  2491. }
  2492. return !empty($data);
  2493. }
  2494. /**
  2495. * Inserts multiple values into a table
  2496. *
  2497. * @param string $table
  2498. * @param string $fields
  2499. * @param array $values
  2500. * @return boolean
  2501. */
  2502. public function insertMulti($table, $fields, $values) {
  2503. $table = $this->fullTableName($table);
  2504. $holder = implode(',', array_fill(0, count($fields), '?'));
  2505. $fields = implode(', ', array_map(array(&$this, 'name'), $fields));
  2506. $count = count($values);
  2507. $sql = "INSERT INTO {$table} ({$fields}) VALUES ({$holder})";
  2508. $statement = $this->_connection->prepare($sql);
  2509. $this->begin();
  2510. for ($x = 0; $x < $count; $x++) {
  2511. $statement->execute($values[$x]);
  2512. $statement->closeCursor();
  2513. }
  2514. return $this->commit();
  2515. }
  2516. /**
  2517. * Returns an array of the indexes in given datasource name.
  2518. *
  2519. * @param string $model Name of model to inspect
  2520. * @return array Fields in table. Keys are column and unique
  2521. */
  2522. public function index($model) {
  2523. return false;
  2524. }
  2525. /**
  2526. * Generate a database-native schema for the given Schema object
  2527. *
  2528. * @param Model $schema An instance of a subclass of CakeSchema
  2529. * @param string $tableName Optional. If specified only the table name given will be generated.
  2530. * Otherwise, all tables defined in the schema are generated.
  2531. * @return string
  2532. */
  2533. public function createSchema($schema, $tableName = null) {
  2534. if (!is_a($schema, 'CakeSchema')) {
  2535. trigger_error(__d('cake_dev', 'Invalid schema object'), E_USER_WARNING);
  2536. return null;
  2537. }
  2538. $out = '';
  2539. foreach ($schema->tables as $curTable => $columns) {
  2540. if (!$tableName || $tableName == $curTable) {
  2541. $cols = $colList = $indexes = $tableParameters = array();
  2542. $primary = null;
  2543. $table = $this->fullTableName($curTable);
  2544. foreach ($columns as $name => $col) {
  2545. if (is_string($col)) {
  2546. $col = array('type' => $col);
  2547. }
  2548. if (isset($col['key']) && $col['key'] === 'primary') {
  2549. $primary = $name;
  2550. }
  2551. if ($name !== 'indexes' && $name !== 'tableParameters') {
  2552. $col['name'] = $name;
  2553. if (!isset($col['type'])) {
  2554. $col['type'] = 'string';
  2555. }
  2556. $cols[] = $this->buildColumn($col);
  2557. } elseif ($name === 'indexes') {
  2558. $indexes = array_merge($indexes, $this->buildIndex($col, $table));
  2559. } elseif ($name === 'tableParameters') {
  2560. $tableParameters = array_merge($tableParameters, $this->buildTableParameters($col, $table));
  2561. }
  2562. }
  2563. if (empty($indexes) && !empty($primary)) {
  2564. $col = array('PRIMARY' => array('column' => $primary, 'unique' => 1));
  2565. $indexes = array_merge($indexes, $this->buildIndex($col, $table));
  2566. }
  2567. $columns = $cols;
  2568. $out .= $this->renderStatement('schema', compact('table', 'columns', 'indexes', 'tableParameters')) . "\n\n";
  2569. }
  2570. }
  2571. return $out;
  2572. }
  2573. /**
  2574. * Generate a alter syntax from CakeSchema::compare()
  2575. *
  2576. * @param mixed $compare
  2577. * @param string $table
  2578. * @return boolean
  2579. */
  2580. public function alterSchema($compare, $table = null) {
  2581. return false;
  2582. }
  2583. /**
  2584. * Generate a "drop table" statement for the given Schema object
  2585. *
  2586. * @param CakeSchema $schema An instance of a subclass of CakeSchema
  2587. * @param string $table Optional. If specified only the table name given will be generated.
  2588. * Otherwise, all tables defined in the schema are generated.
  2589. * @return string
  2590. */
  2591. public function dropSchema(CakeSchema $schema, $table = null) {
  2592. $out = '';
  2593. foreach ($schema->tables as $curTable => $columns) {
  2594. if (!$table || $table == $curTable) {
  2595. $out .= 'DROP TABLE ' . $this->fullTableName($curTable) . ";\n";
  2596. }
  2597. }
  2598. return $out;
  2599. }
  2600. /**
  2601. * Generate a database-native column schema string
  2602. *
  2603. * @param array $column An array structured like the following: array('name'=>'value', 'type'=>'value'[, options]),
  2604. * where options can be 'default', 'length', or 'key'.
  2605. * @return string
  2606. */
  2607. public function buildColumn($column) {
  2608. $name = $type = null;
  2609. extract(array_merge(array('null' => true), $column));
  2610. if (empty($name) || empty($type)) {
  2611. trigger_error(__d('cake_dev', 'Column name or type not defined in schema'), E_USER_WARNING);
  2612. return null;
  2613. }
  2614. if (!isset($this->columns[$type])) {
  2615. trigger_error(__d('cake_dev', 'Column type %s does not exist', $type), E_USER_WARNING);
  2616. return null;
  2617. }
  2618. $real = $this->columns[$type];
  2619. $out = $this->name($name) . ' ' . $real['name'];
  2620. if (isset($column['length'])) {
  2621. $length = $column['length'];
  2622. } elseif (isset($column['limit'])) {
  2623. $length = $column['limit'];
  2624. } elseif (isset($real['length'])) {
  2625. $length = $real['length'];
  2626. } elseif (isset($real['limit'])) {
  2627. $length = $real['limit'];
  2628. }
  2629. if (isset($length)) {
  2630. $out .= '(' . $length . ')';
  2631. }
  2632. if (($column['type'] === 'integer' || $column['type'] === 'float' ) && isset($column['default']) && $column['default'] === '') {
  2633. $column['default'] = null;
  2634. }
  2635. $out = $this->_buildFieldParameters($out, $column, 'beforeDefault');
  2636. if (isset($column['key']) && $column['key'] === 'primary' && $type === 'integer') {
  2637. $out .= ' ' . $this->columns['primary_key']['name'];
  2638. } elseif (isset($column['key']) && $column['key'] === 'primary') {
  2639. $out .= ' NOT NULL';
  2640. } elseif (isset($column['default']) && isset($column['null']) && $column['null'] === false) {
  2641. $out .= ' DEFAULT ' . $this->value($column['default'], $type) . ' NOT NULL';
  2642. } elseif (isset($column['default'])) {
  2643. $out .= ' DEFAULT ' . $this->value($column['default'], $type);
  2644. } elseif ($type !== 'timestamp' && !empty($column['null'])) {
  2645. $out .= ' DEFAULT NULL';
  2646. } elseif ($type === 'timestamp' && !empty($column['null'])) {
  2647. $out .= ' NULL';
  2648. } elseif (isset($column['null']) && $column['null'] === false) {
  2649. $out .= ' NOT NULL';
  2650. }
  2651. if ($type === 'timestamp' && isset($column['default']) && strtolower($column['default']) === 'current_timestamp') {
  2652. $out = str_replace(array("'CURRENT_TIMESTAMP'", "'current_timestamp'"), 'CURRENT_TIMESTAMP', $out);
  2653. }
  2654. return $this->_buildFieldParameters($out, $column, 'afterDefault');
  2655. }
  2656. /**
  2657. * Build the field parameters, in a position
  2658. *
  2659. * @param string $columnString The partially built column string
  2660. * @param array $columnData The array of column data.
  2661. * @param string $position The position type to use. 'beforeDefault' or 'afterDefault' are common
  2662. * @return string a built column with the field parameters added.
  2663. */
  2664. protected function _buildFieldParameters($columnString, $columnData, $position) {
  2665. foreach ($this->fieldParameters as $paramName => $value) {
  2666. if (isset($columnData[$paramName]) && $value['position'] == $position) {
  2667. if (isset($value['options']) && !in_array($columnData[$paramName], $value['options'])) {
  2668. continue;
  2669. }
  2670. $val = $columnData[$paramName];
  2671. if ($value['quote']) {
  2672. $val = $this->value($val);
  2673. }
  2674. $columnString .= ' ' . $value['value'] . $value['join'] . $val;
  2675. }
  2676. }
  2677. return $columnString;
  2678. }
  2679. /**
  2680. * Format indexes for create table
  2681. *
  2682. * @param array $indexes
  2683. * @param string $table
  2684. * @return array
  2685. */
  2686. public function buildIndex($indexes, $table = null) {
  2687. $join = array();
  2688. foreach ($indexes as $name => $value) {
  2689. $out = '';
  2690. if ($name === 'PRIMARY') {
  2691. $out .= 'PRIMARY ';
  2692. $name = null;
  2693. } else {
  2694. if (!empty($value['unique'])) {
  2695. $out .= 'UNIQUE ';
  2696. }
  2697. $name = $this->startQuote . $name . $this->endQuote;
  2698. }
  2699. if (is_array($value['column'])) {
  2700. $out .= 'KEY ' . $name . ' (' . implode(', ', array_map(array(&$this, 'name'), $value['column'])) . ')';
  2701. } else {
  2702. $out .= 'KEY ' . $name . ' (' . $this->name($value['column']) . ')';
  2703. }
  2704. $join[] = $out;
  2705. }
  2706. return $join;
  2707. }
  2708. /**
  2709. * Read additional table parameters
  2710. *
  2711. * @param string $name
  2712. * @return array
  2713. */
  2714. public function readTableParameters($name) {
  2715. $parameters = array();
  2716. if (method_exists($this, 'listDetailedSources')) {
  2717. $currentTableDetails = $this->listDetailedSources($name);
  2718. foreach ($this->tableParameters as $paramName => $parameter) {
  2719. if (!empty($parameter['column']) && !empty($currentTableDetails[$parameter['column']])) {
  2720. $parameters[$paramName] = $currentTableDetails[$parameter['column']];
  2721. }
  2722. }
  2723. }
  2724. return $parameters;
  2725. }
  2726. /**
  2727. * Format parameters for create table
  2728. *
  2729. * @param array $parameters
  2730. * @param string $table
  2731. * @return array
  2732. */
  2733. public function buildTableParameters($parameters, $table = null) {
  2734. $result = array();
  2735. foreach ($parameters as $name => $value) {
  2736. if (isset($this->tableParameters[$name])) {
  2737. if ($this->tableParameters[$name]['quote']) {
  2738. $value = $this->value($value);
  2739. }
  2740. $result[] = $this->tableParameters[$name]['value'] . $this->tableParameters[$name]['join'] . $value;
  2741. }
  2742. }
  2743. return $result;
  2744. }
  2745. /**
  2746. * Guesses the data type of an array
  2747. *
  2748. * @param string $value
  2749. * @return void
  2750. */
  2751. public function introspectType($value) {
  2752. if (!is_array($value)) {
  2753. if (is_bool($value)) {
  2754. return 'boolean';
  2755. }
  2756. if (is_float($value) && floatval($value) === $value) {
  2757. return 'float';
  2758. }
  2759. if (is_int($value) && intval($value) === $value) {
  2760. return 'integer';
  2761. }
  2762. if (is_string($value) && strlen($value) > 255) {
  2763. return 'text';
  2764. }
  2765. return 'string';
  2766. }
  2767. $isAllFloat = $isAllInt = true;
  2768. $containsFloat = $containsInt = $containsString = false;
  2769. foreach ($value as $key => $valElement) {
  2770. $valElement = trim($valElement);
  2771. if (!is_float($valElement) && !preg_match('/^[\d]+\.[\d]+$/', $valElement)) {
  2772. $isAllFloat = false;
  2773. } else {
  2774. $containsFloat = true;
  2775. continue;
  2776. }
  2777. if (!is_int($valElement) && !preg_match('/^[\d]+$/', $valElement)) {
  2778. $isAllInt = false;
  2779. } else {
  2780. $containsInt = true;
  2781. continue;
  2782. }
  2783. $containsString = true;
  2784. }
  2785. if ($isAllFloat) {
  2786. return 'float';
  2787. }
  2788. if ($isAllInt) {
  2789. return 'integer';
  2790. }
  2791. if ($containsInt && !$containsString) {
  2792. return 'integer';
  2793. }
  2794. return 'string';
  2795. }
  2796. /**
  2797. * Writes a new key for the in memory sql query cache
  2798. *
  2799. * @param string $sql SQL query
  2800. * @param mixed $data result of $sql query
  2801. * @param array $params query params bound as values
  2802. * @return void
  2803. */
  2804. protected function _writeQueryCache($sql, $data, $params = array()) {
  2805. if (preg_match('/^\s*select/i', $sql)) {
  2806. $this->_queryCache[$sql][serialize($params)] = $data;
  2807. }
  2808. }
  2809. /**
  2810. * Returns the result for a sql query if it is already cached
  2811. *
  2812. * @param string $sql SQL query
  2813. * @param array $params query params bound as values
  2814. * @return mixed results for query if it is cached, false otherwise
  2815. */
  2816. public function getQueryCache($sql, $params = array()) {
  2817. if (isset($this->_queryCache[$sql]) && preg_match('/^\s*select/i', $sql)) {
  2818. $serialized = serialize($params);
  2819. if (isset($this->_queryCache[$sql][$serialized])) {
  2820. return $this->_queryCache[$sql][$serialized];
  2821. }
  2822. }
  2823. return false;
  2824. }
  2825. /**
  2826. * Used for storing in cache the results of the in-memory methodCache
  2827. *
  2828. */
  2829. public function __destruct() {
  2830. if ($this->_methodCacheChange) {
  2831. Cache::write('method_cache', self::$methodCache, '_cake_core_');
  2832. }
  2833. }
  2834. }