PageRenderTime 70ms CodeModel.GetById 24ms RepoModel.GetById 0ms app.codeStats 0ms

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

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