PageRenderTime 37ms CodeModel.GetById 31ms RepoModel.GetById 0ms app.codeStats 1ms

/QuickApps/Cake/Model/Datasource/DboSource.php

http://github.com/QuickAppsCMS/QuickApps-CMS
PHP | 2243 lines | 1398 code | 188 blank | 657 comment | 351 complexity | b3e5b14d1c73b3fc74f8dcc783a507d5 MD5 | raw file
Possible License(s): LGPL-2.1, MPL-2.0-no-copyleft-exception, GPL-3.0
  1. <?php
  2. /**
  3. * Dbo Source
  4. *
  5. * PHP 5
  6. *
  7. * CakePHP(tm) : Rapid Development Framework (http://cakephp.org)
  8. * Copyright 2005-2012, 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-2012, Cake Software Foundation, Inc. (http://cakefoundation.org)
  14. * @link http://cakephp.org CakePHP(tm) Project
  15. * @package Cake.Model.Datasource
  16. * @since CakePHP(tm) v 0.10.0.1076
  17. * @license MIT License (http://www.opensource.org/licenses/mit-license.php)
  18. */
  19. App::uses('DataSource', 'Model/Datasource');
  20. App::uses('String', 'Utility');
  21. App::uses('View', 'View');
  22. /**
  23. * DboSource
  24. *
  25. * Creates DBO-descendant objects from a given db connection configuration
  26. *
  27. * @package Cake.Model.Datasource
  28. */
  29. class DboSource extends DataSource {
  30. /**
  31. * Description string for this Database Data Source.
  32. *
  33. * @var string
  34. */
  35. public $description = "Database Data Source";
  36. /**
  37. * index definition, standard cake, primary, index, unique
  38. *
  39. * @var array
  40. */
  41. public $index = array('PRI' => 'primary', 'MUL' => 'index', 'UNI' => 'unique');
  42. /**
  43. * Database keyword used to assign aliases to identifiers.
  44. *
  45. * @var string
  46. */
  47. public $alias = 'AS ';
  48. /**
  49. * Caches result from query parsing operations. Cached results for both DboSource::name() and
  50. * DboSource::conditions() will be stored here. Method caching uses `crc32()` which is
  51. * fast but can collisions more easily than other hashing algorithms. If you have problems
  52. * with collisions, set DboSource::$cacheMethods to false.
  53. *
  54. * @var array
  55. */
  56. public static $methodCache = array();
  57. /**
  58. * Whether or not to cache the results of DboSource::name() and DboSource::conditions()
  59. * into the memory cache. Set to false to disable the use of the memory cache.
  60. *
  61. * @var boolean.
  62. */
  63. public $cacheMethods = true;
  64. /**
  65. * Flag to support nested transactions. If it is set to false, you will be able to use
  66. * the transaction methods (begin/commit/rollback), but just the global transaction will
  67. * be executed.
  68. *
  69. * @var boolean
  70. */
  71. public $useNestedTransactions = false;
  72. /**
  73. * Print full query debug info?
  74. *
  75. * @var boolean
  76. */
  77. public $fullDebug = false;
  78. /**
  79. * String to hold how many rows were affected by the last SQL operation.
  80. *
  81. * @var string
  82. */
  83. public $affected = null;
  84. /**
  85. * Number of rows in current resultset
  86. *
  87. * @var integer
  88. */
  89. public $numRows = null;
  90. /**
  91. * Time the last query took
  92. *
  93. * @var integer
  94. */
  95. public $took = null;
  96. /**
  97. * Result
  98. *
  99. * @var array
  100. */
  101. protected $_result = null;
  102. /**
  103. * Queries count.
  104. *
  105. * @var integer
  106. */
  107. protected $_queriesCnt = 0;
  108. /**
  109. * Total duration of all queries.
  110. *
  111. * @var integer
  112. */
  113. protected $_queriesTime = null;
  114. /**
  115. * Log of queries executed by this DataSource
  116. *
  117. * @var array
  118. */
  119. protected $_queriesLog = array();
  120. /**
  121. * Maximum number of items in query log
  122. *
  123. * This is to prevent query log taking over too much memory.
  124. *
  125. * @var integer Maximum number of queries in the queries log.
  126. */
  127. protected $_queriesLogMax = 200;
  128. /**
  129. * Caches serialized results of executed queries
  130. *
  131. * @var array Cache of results from executed sql queries.
  132. */
  133. protected $_queryCache = array();
  134. /**
  135. * A reference to the physical connection of this DataSource
  136. *
  137. * @var array
  138. */
  139. protected $_connection = null;
  140. /**
  141. * The DataSource configuration key name
  142. *
  143. * @var string
  144. */
  145. public $configKeyName = null;
  146. /**
  147. * The starting character that this DataSource uses for quoted identifiers.
  148. *
  149. * @var string
  150. */
  151. public $startQuote = null;
  152. /**
  153. * The ending character that this DataSource uses for quoted identifiers.
  154. *
  155. * @var string
  156. */
  157. public $endQuote = null;
  158. /**
  159. * The set of valid SQL operations usable in a WHERE statement
  160. *
  161. * @var array
  162. */
  163. protected $_sqlOps = array('like', 'ilike', 'or', 'not', 'in', 'between', 'regexp', 'similar to');
  164. /**
  165. * Indicates the level of nested transactions
  166. *
  167. * @var integer
  168. */
  169. protected $_transactionNesting = 0;
  170. /**
  171. * Default fields that are used by the DBO
  172. *
  173. * @var array
  174. */
  175. protected $_queryDefaults = array(
  176. 'conditions' => array(),
  177. 'fields' => null,
  178. 'table' => null,
  179. 'alias' => null,
  180. 'order' => null,
  181. 'limit' => null,
  182. 'joins' => array(),
  183. 'group' => null,
  184. 'offset' => null
  185. );
  186. /**
  187. * Separator string for virtualField composition
  188. *
  189. * @var string
  190. */
  191. public $virtualFieldSeparator = '__';
  192. /**
  193. * List of table engine specific parameters used on table creating
  194. *
  195. * @var array
  196. */
  197. public $tableParameters = array();
  198. /**
  199. * List of engine specific additional field parameters used on table creating
  200. *
  201. * @var array
  202. */
  203. public $fieldParameters = array();
  204. /**
  205. * Indicates whether there was a change on the cached results on the methods of this class
  206. * This will be used for storing in a more persistent cache
  207. *
  208. * @var boolean
  209. */
  210. protected $_methodCacheChange = false;
  211. /**
  212. * Constructor
  213. *
  214. * @param array $config Array of configuration information for the Datasource.
  215. * @param boolean $autoConnect Whether or not the datasource should automatically connect.
  216. * @throws MissingConnectionException when a connection cannot be made.
  217. */
  218. public function __construct($config = null, $autoConnect = true) {
  219. if (!isset($config['prefix'])) {
  220. $config['prefix'] = '';
  221. }
  222. parent::__construct($config);
  223. $this->fullDebug = Configure::read('debug') > 1;
  224. if (!$this->enabled()) {
  225. throw new MissingConnectionException(array(
  226. 'class' => get_class($this)
  227. ));
  228. }
  229. if ($autoConnect) {
  230. $this->connect();
  231. }
  232. }
  233. /**
  234. * Reconnects to database server with optional new settings
  235. *
  236. * @param array $config An array defining the new configuration settings
  237. * @return boolean True on success, false on failure
  238. */
  239. public function reconnect($config = array()) {
  240. $this->disconnect();
  241. $this->setConfig($config);
  242. $this->_sources = null;
  243. return $this->connect();
  244. }
  245. /**
  246. * Disconnects from database.
  247. *
  248. * @return boolean True if the database could be disconnected, else false
  249. */
  250. public function disconnect() {
  251. if ($this->_result instanceof PDOStatement) {
  252. $this->_result->closeCursor();
  253. }
  254. unset($this->_connection);
  255. $this->connected = false;
  256. return true;
  257. }
  258. /**
  259. * Get the underlying connection object.
  260. *
  261. * @return PDO
  262. */
  263. public function getConnection() {
  264. return $this->_connection;
  265. }
  266. /**
  267. * Gets the version string of the database server
  268. *
  269. * @return string The database version
  270. */
  271. public function getVersion() {
  272. return $this->_connection->getAttribute(PDO::ATTR_SERVER_VERSION);
  273. }
  274. /**
  275. * Returns a quoted and escaped string of $data for use in an SQL statement.
  276. *
  277. * @param string $data String to be prepared for use in an SQL statement
  278. * @param string $column The column into which this data will be inserted
  279. * @return string Quoted and escaped data
  280. */
  281. public function value($data, $column = null) {
  282. if (is_array($data) && !empty($data)) {
  283. return array_map(
  284. array(&$this, 'value'),
  285. $data, array_fill(0, count($data), $column)
  286. );
  287. } elseif (is_object($data) && isset($data->type, $data->value)) {
  288. if ($data->type == 'identifier') {
  289. return $this->name($data->value);
  290. } elseif ($data->type == 'expression') {
  291. return $data->value;
  292. }
  293. } elseif (in_array($data, array('{$__cakeID__$}', '{$__cakeForeignKey__$}'), true)) {
  294. return $data;
  295. }
  296. if ($data === null || (is_array($data) && empty($data))) {
  297. return 'NULL';
  298. }
  299. if (empty($column)) {
  300. $column = $this->introspectType($data);
  301. }
  302. switch ($column) {
  303. case 'binary':
  304. return $this->_connection->quote($data, PDO::PARAM_LOB);
  305. break;
  306. case 'boolean':
  307. return $this->_connection->quote($this->boolean($data, true), PDO::PARAM_BOOL);
  308. break;
  309. case 'string':
  310. case 'text':
  311. return $this->_connection->quote($data, PDO::PARAM_STR);
  312. default:
  313. if ($data === '') {
  314. return 'NULL';
  315. }
  316. if (is_float($data)) {
  317. return str_replace(',', '.', strval($data));
  318. }
  319. if ((is_int($data) || $data === '0') || (
  320. is_numeric($data) && strpos($data, ',') === false &&
  321. $data[0] != '0' && strpos($data, 'e') === false)
  322. ) {
  323. return $data;
  324. }
  325. return $this->_connection->quote($data);
  326. break;
  327. }
  328. }
  329. /**
  330. * Returns an object to represent a database identifier in a query. Expression objects
  331. * are not sanitized or escaped.
  332. *
  333. * @param string $identifier A SQL expression to be used as an identifier
  334. * @return stdClass An object representing a database identifier to be used in a query
  335. */
  336. public function identifier($identifier) {
  337. $obj = new stdClass();
  338. $obj->type = 'identifier';
  339. $obj->value = $identifier;
  340. return $obj;
  341. }
  342. /**
  343. * Returns an object to represent a database expression in a query. Expression objects
  344. * are not sanitized or escaped.
  345. *
  346. * @param string $expression An arbitrary SQL expression to be inserted into a query.
  347. * @return stdClass An object representing a database expression to be used in a query
  348. */
  349. public function expression($expression) {
  350. $obj = new stdClass();
  351. $obj->type = 'expression';
  352. $obj->value = $expression;
  353. return $obj;
  354. }
  355. /**
  356. * Executes given SQL statement.
  357. *
  358. * @param string $sql SQL statement
  359. * @param array $params Additional options for the query.
  360. * @return boolean
  361. */
  362. public function rawQuery($sql, $params = array()) {
  363. $this->took = $this->numRows = false;
  364. return $this->execute($sql, $params);
  365. }
  366. /**
  367. * Queries the database with given SQL statement, and obtains some metadata about the result
  368. * (rows affected, timing, any errors, number of rows in resultset). The query is also logged.
  369. * If Configure::read('debug') is set, the log is shown all the time, else it is only shown on errors.
  370. *
  371. * ### Options
  372. *
  373. * - log - Whether or not the query should be logged to the memory log.
  374. *
  375. * @param string $sql SQL statement
  376. * @param array $options
  377. * @param array $params values to be bound to the query
  378. * @return mixed Resource or object representing the result set, or false on failure
  379. */
  380. public function execute($sql, $options = array(), $params = array()) {
  381. $options += array('log' => $this->fullDebug);
  382. $t = microtime(true);
  383. $this->_result = $this->_execute($sql, $params);
  384. if ($options['log']) {
  385. $this->took = round((microtime(true) - $t) * 1000, 0);
  386. $this->numRows = $this->affected = $this->lastAffected();
  387. $this->logQuery($sql, $params);
  388. }
  389. return $this->_result;
  390. }
  391. /**
  392. * Executes given SQL statement.
  393. *
  394. * @param string $sql SQL statement
  395. * @param array $params list of params to be bound to query
  396. * @param array $prepareOptions Options to be used in the prepare statement
  397. * @return mixed PDOStatement if query executes with no problem, true as the result of a successful, false on error
  398. * query returning no rows, such as a CREATE statement, false otherwise
  399. * @throws PDOException
  400. */
  401. protected function _execute($sql, $params = array(), $prepareOptions = array()) {
  402. $sql = trim($sql);
  403. if (preg_match('/^(?:CREATE|ALTER|DROP)/i', $sql)) {
  404. $statements = array_filter(explode(';', $sql));
  405. if (count($statements) > 1) {
  406. $result = array_map(array($this, '_execute'), $statements);
  407. return array_search(false, $result) === false;
  408. }
  409. }
  410. try {
  411. $query = $this->_connection->prepare($sql, $prepareOptions);
  412. $query->setFetchMode(PDO::FETCH_LAZY);
  413. if (!$query->execute($params)) {
  414. $this->_results = $query;
  415. $query->closeCursor();
  416. return false;
  417. }
  418. if (!$query->columnCount()) {
  419. $query->closeCursor();
  420. if (!$query->rowCount()) {
  421. return true;
  422. }
  423. }
  424. return $query;
  425. } catch (PDOException $e) {
  426. if (isset($query->queryString)) {
  427. $e->queryString = $query->queryString;
  428. } else {
  429. $e->queryString = $sql;
  430. }
  431. throw $e;
  432. }
  433. }
  434. /**
  435. * Returns a formatted error message from previous database operation.
  436. *
  437. * @param PDOStatement $query the query to extract the error from if any
  438. * @return string Error message with error number
  439. */
  440. public function lastError(PDOStatement $query = null) {
  441. if ($query) {
  442. $error = $query->errorInfo();
  443. } else {
  444. $error = $this->_connection->errorInfo();
  445. }
  446. if (empty($error[2])) {
  447. return null;
  448. }
  449. return $error[1] . ': ' . $error[2];
  450. }
  451. /**
  452. * Returns number of affected rows in previous database operation. If no previous operation exists,
  453. * this returns false.
  454. *
  455. * @param mixed $source
  456. * @return integer Number of affected rows
  457. */
  458. public function lastAffected($source = null) {
  459. if ($this->hasResult()) {
  460. return $this->_result->rowCount();
  461. }
  462. return 0;
  463. }
  464. /**
  465. * Returns number of rows in previous resultset. If no previous resultset exists,
  466. * this returns false.
  467. *
  468. * @param mixed $source Not used
  469. * @return integer Number of rows in resultset
  470. */
  471. public function lastNumRows($source = null) {
  472. return $this->lastAffected();
  473. }
  474. /**
  475. * DataSource Query abstraction
  476. *
  477. * @return resource Result resource identifier.
  478. */
  479. public function query() {
  480. $args = func_get_args();
  481. $fields = null;
  482. $order = null;
  483. $limit = null;
  484. $page = null;
  485. $recursive = null;
  486. if (count($args) === 1) {
  487. return $this->fetchAll($args[0]);
  488. } elseif (count($args) > 1 && (strpos($args[0], 'findBy') === 0 || strpos($args[0], 'findAllBy') === 0)) {
  489. $params = $args[1];
  490. if (substr($args[0], 0, 6) === 'findBy') {
  491. $all = false;
  492. $field = Inflector::underscore(substr($args[0], 6));
  493. } else {
  494. $all = true;
  495. $field = Inflector::underscore(substr($args[0], 9));
  496. }
  497. $or = (strpos($field, '_or_') !== false);
  498. if ($or) {
  499. $field = explode('_or_', $field);
  500. } else {
  501. $field = explode('_and_', $field);
  502. }
  503. $off = count($field) - 1;
  504. if (isset($params[1 + $off])) {
  505. $fields = $params[1 + $off];
  506. }
  507. if (isset($params[2 + $off])) {
  508. $order = $params[2 + $off];
  509. }
  510. if (!array_key_exists(0, $params)) {
  511. return false;
  512. }
  513. $c = 0;
  514. $conditions = array();
  515. foreach ($field as $f) {
  516. $conditions[$args[2]->alias . '.' . $f] = $params[$c++];
  517. }
  518. if ($or) {
  519. $conditions = array('OR' => $conditions);
  520. }
  521. if ($all) {
  522. if (isset($params[3 + $off])) {
  523. $limit = $params[3 + $off];
  524. }
  525. if (isset($params[4 + $off])) {
  526. $page = $params[4 + $off];
  527. }
  528. if (isset($params[5 + $off])) {
  529. $recursive = $params[5 + $off];
  530. }
  531. return $args[2]->find('all', compact('conditions', 'fields', 'order', 'limit', 'page', 'recursive'));
  532. } else {
  533. if (isset($params[3 + $off])) {
  534. $recursive = $params[3 + $off];
  535. }
  536. return $args[2]->find('first', compact('conditions', 'fields', 'order', 'recursive'));
  537. }
  538. } else {
  539. if (isset($args[1]) && $args[1] === true) {
  540. return $this->fetchAll($args[0], true);
  541. } elseif (isset($args[1]) && !is_array($args[1]) ) {
  542. return $this->fetchAll($args[0], false);
  543. } elseif (isset($args[1]) && is_array($args[1])) {
  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. * This is a non-persistent cache, and only lasts for a single request. This option
  583. * defaults to true. If you are directly calling this method, you can disable caching
  584. * by setting $options to `false`
  585. *
  586. * @param string $sql SQL statement
  587. * @param array $params parameters to be bound as values for the SQL statement
  588. * @param array $options additional options for the query.
  589. * @return array Array of resultset rows, or false if no rows matched
  590. */
  591. public function fetchAll($sql, $params = array(), $options = array()) {
  592. if (is_string($options)) {
  593. $options = array('modelName' => $options);
  594. }
  595. if (is_bool($params)) {
  596. $options['cache'] = $params;
  597. $params = array();
  598. }
  599. $options += array('cache' => true);
  600. $cache = $options['cache'];
  601. if ($cache && ($cached = $this->getQueryCache($sql, $params)) !== false) {
  602. return $cached;
  603. }
  604. if ($result = $this->execute($sql, array(), $params)) {
  605. $out = array();
  606. if ($this->hasResult()) {
  607. $first = $this->fetchRow();
  608. if ($first != null) {
  609. $out[] = $first;
  610. }
  611. while ($item = $this->fetchResult()) {
  612. if (isset($item[0])) {
  613. $this->fetchVirtualField($item);
  614. }
  615. $out[] = $item;
  616. }
  617. }
  618. if (!is_bool($result) && $cache) {
  619. $this->_writeQueryCache($sql, $out, $params);
  620. }
  621. if (empty($out) && is_bool($this->_result)) {
  622. return $this->_result;
  623. }
  624. return $out;
  625. }
  626. return false;
  627. }
  628. /**
  629. * Fetches the next row from the current result set
  630. *
  631. * @return boolean
  632. */
  633. public function fetchResult() {
  634. return false;
  635. }
  636. /**
  637. * Modifies $result array to place virtual fields in model entry where they belongs to
  638. *
  639. * @param array $result Reference to the fetched row
  640. * @return void
  641. */
  642. public function fetchVirtualField(&$result) {
  643. if (isset($result[0]) && is_array($result[0])) {
  644. foreach ($result[0] as $field => $value) {
  645. if (strpos($field, $this->virtualFieldSeparator) === false) {
  646. continue;
  647. }
  648. list($alias, $virtual) = explode($this->virtualFieldSeparator, $field);
  649. if (!ClassRegistry::isKeySet($alias)) {
  650. return;
  651. }
  652. $model = ClassRegistry::getObject($alias);
  653. if ($model->isVirtualField($virtual)) {
  654. $result[$alias][$virtual] = $value;
  655. unset($result[0][$field]);
  656. }
  657. }
  658. if (empty($result[0])) {
  659. unset($result[0]);
  660. }
  661. }
  662. }
  663. /**
  664. * Returns a single field of the first of query results for a given SQL query, or false if empty.
  665. *
  666. * @param string $name Name of the field
  667. * @param string $sql SQL query
  668. * @return mixed Value of field read.
  669. */
  670. public function field($name, $sql) {
  671. $data = $this->fetchRow($sql);
  672. if (empty($data[$name])) {
  673. return false;
  674. }
  675. return $data[$name];
  676. }
  677. /**
  678. * Empties the method caches.
  679. * These caches are used by DboSource::name() and DboSource::conditions()
  680. *
  681. * @return void
  682. */
  683. public function flushMethodCache() {
  684. $this->_methodCacheChange = true;
  685. self::$methodCache = array();
  686. }
  687. /**
  688. * Cache a value into the methodCaches. Will respect the value of DboSource::$cacheMethods.
  689. * Will retrieve a value from the cache if $value is null.
  690. *
  691. * If caching is disabled and a write is attempted, the $value will be returned.
  692. * A read will either return the value or null.
  693. *
  694. * @param string $method Name of the method being cached.
  695. * @param string $key The key name for the cache operation.
  696. * @param mixed $value The value to cache into memory.
  697. * @return mixed Either null on failure, or the value if its set.
  698. */
  699. public function cacheMethod($method, $key, $value = null) {
  700. if ($this->cacheMethods === false) {
  701. return $value;
  702. }
  703. if (empty(self::$methodCache)) {
  704. self::$methodCache = Cache::read('method_cache', '_cake_core_');
  705. }
  706. if ($value === null) {
  707. return (isset(self::$methodCache[$method][$key])) ? self::$methodCache[$method][$key] : null;
  708. }
  709. $this->_methodCacheChange = true;
  710. return self::$methodCache[$method][$key] = $value;
  711. }
  712. /**
  713. * Returns a quoted name of $data for use in an SQL statement.
  714. * Strips fields out of SQL functions before quoting.
  715. *
  716. * Results of this method are stored in a memory cache. This improves performance, but
  717. * because the method uses a simple hashing algorithm it can infrequently have collisions.
  718. * Setting DboSource::$cacheMethods to false will disable the memory cache.
  719. *
  720. * @param mixed $data Either a string with a column to quote. An array of columns to quote or an
  721. * object from DboSource::expression() or DboSource::identifier()
  722. * @return string SQL field
  723. */
  724. public function name($data) {
  725. if (is_object($data) && isset($data->type)) {
  726. return $data->value;
  727. }
  728. if ($data === '*') {
  729. return '*';
  730. }
  731. if (is_array($data)) {
  732. foreach ($data as $i => $dataItem) {
  733. $data[$i] = $this->name($dataItem);
  734. }
  735. return $data;
  736. }
  737. $cacheKey = crc32($this->startQuote . $data . $this->endQuote);
  738. if ($return = $this->cacheMethod(__FUNCTION__, $cacheKey)) {
  739. return $return;
  740. }
  741. $data = trim($data);
  742. if (preg_match('/^[\w-]+(?:\.[^ \*]*)*$/', $data)) { // string, string.string
  743. if (strpos($data, '.') === false) { // string
  744. return $this->cacheMethod(__FUNCTION__, $cacheKey, $this->startQuote . $data . $this->endQuote);
  745. }
  746. $items = explode('.', $data);
  747. return $this->cacheMethod(__FUNCTION__, $cacheKey,
  748. $this->startQuote . implode($this->endQuote . '.' . $this->startQuote, $items) . $this->endQuote
  749. );
  750. }
  751. if (preg_match('/^[\w-]+\.\*$/', $data)) { // string.*
  752. return $this->cacheMethod(__FUNCTION__, $cacheKey,
  753. $this->startQuote . str_replace('.*', $this->endQuote . '.*', $data)
  754. );
  755. }
  756. if (preg_match('/^([\w-]+)\((.*)\)$/', $data, $matches)) { // Functions
  757. return $this->cacheMethod(__FUNCTION__, $cacheKey,
  758. $matches[1] . '(' . $this->name($matches[2]) . ')'
  759. );
  760. }
  761. if (
  762. preg_match('/^([\w-]+(\.[\w-]+|\(.*\))*)\s+' . preg_quote($this->alias) . '\s*([\w-]+)$/i', $data, $matches
  763. )) {
  764. return $this->cacheMethod(
  765. __FUNCTION__, $cacheKey,
  766. preg_replace(
  767. '/\s{2,}/', ' ', $this->name($matches[1]) . ' ' . $this->alias . ' ' . $this->name($matches[3])
  768. )
  769. );
  770. }
  771. if (preg_match('/^[\w-_\s]*[\w-_]+/', $data)) {
  772. return $this->cacheMethod(__FUNCTION__, $cacheKey, $this->startQuote . $data . $this->endQuote);
  773. }
  774. return $this->cacheMethod(__FUNCTION__, $cacheKey, $data);
  775. }
  776. /**
  777. * Checks if the source is connected to the database.
  778. *
  779. * @return boolean True if the database is connected, else false
  780. */
  781. public function isConnected() {
  782. return $this->connected;
  783. }
  784. /**
  785. * Checks if the result is valid
  786. *
  787. * @return boolean True if the result is valid else false
  788. */
  789. public function hasResult() {
  790. return is_a($this->_result, 'PDOStatement');
  791. }
  792. /**
  793. * Get the query log as an array.
  794. *
  795. * @param boolean $sorted Get the queries sorted by time taken, defaults to false.
  796. * @param boolean $clear If True the existing log will cleared.
  797. * @return array Array of queries run as an array
  798. */
  799. public function getLog($sorted = false, $clear = true) {
  800. if ($sorted) {
  801. $log = sortByKey($this->_queriesLog, 'took', 'desc', SORT_NUMERIC);
  802. } else {
  803. $log = $this->_queriesLog;
  804. }
  805. if ($clear) {
  806. $this->_queriesLog = array();
  807. }
  808. return array('log' => $log, 'count' => $this->_queriesCnt, 'time' => $this->_queriesTime);
  809. }
  810. /**
  811. * Outputs the contents of the queries log. If in a non-CLI environment the sql_log element
  812. * will be rendered and output. If in a CLI environment, a plain text log is generated.
  813. *
  814. * @param boolean $sorted Get the queries sorted by time taken, defaults to false.
  815. * @return void
  816. */
  817. public function showLog($sorted = false) {
  818. $log = $this->getLog($sorted, false);
  819. if (empty($log['log'])) {
  820. return;
  821. }
  822. if (PHP_SAPI != 'cli') {
  823. $controller = null;
  824. $View = new View($controller, false);
  825. $View->set('logs', array($this->configKeyName => $log));
  826. echo $View->element('sql_dump', array('_forced_from_dbo_' => true));
  827. } else {
  828. foreach ($log['log'] as $k => $i) {
  829. print (($k + 1) . ". {$i['query']}\n");
  830. }
  831. }
  832. }
  833. /**
  834. * Log given SQL query.
  835. *
  836. * @param string $sql SQL statement
  837. * @param array $params Values binded to the query (prepared statements)
  838. * @return void
  839. */
  840. public function logQuery($sql, $params = array()) {
  841. $this->_queriesCnt++;
  842. $this->_queriesTime += $this->took;
  843. $this->_queriesLog[] = array(
  844. 'query' => $sql,
  845. 'params' => $params,
  846. 'affected' => $this->affected,
  847. 'numRows' => $this->numRows,
  848. 'took' => $this->took
  849. );
  850. if (count($this->_queriesLog) > $this->_queriesLogMax) {
  851. array_pop($this->_queriesLog);
  852. }
  853. }
  854. /**
  855. * Gets full table name including prefix
  856. *
  857. * @param mixed $model Either a Model object or a string table name.
  858. * @param boolean $quote Whether you want the table name quoted.
  859. * @param boolean $schema Whether you want the schema name included.
  860. * @return string Full quoted table name
  861. */
  862. public function fullTableName($model, $quote = true, $schema = true) {
  863. if (is_object($model)) {
  864. $schemaName = $model->schemaName;
  865. $table = $model->tablePrefix . $model->table;
  866. } elseif (!empty($this->config['prefix']) && strpos($model, $this->config['prefix']) !== 0) {
  867. $table = $this->config['prefix'] . strval($model);
  868. } else {
  869. $table = strval($model);
  870. }
  871. if ($schema && !isset($schemaName)) {
  872. $schemaName = $this->getSchemaName();
  873. }
  874. if ($quote) {
  875. if ($schema && !empty($schemaName)) {
  876. if (false == strstr($table, '.')) {
  877. return $this->name($schemaName) . '.' . $this->name($table);
  878. }
  879. }
  880. return $this->name($table);
  881. }
  882. if ($schema && !empty($schemaName)) {
  883. if (false == strstr($table, '.')) {
  884. return $schemaName . '.' . $table;
  885. }
  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 $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]));
  911. $fieldInsert[] = $this->name($fields[$i]);
  912. if ($fields[$i] == $model->primaryKey) {
  913. $id = $values[$i];
  914. }
  915. }
  916. $query = array(
  917. 'table' => $this->fullTableName($model),
  918. 'fields' => implode(', ', $fieldInsert),
  919. 'values' => implode(', ', $valueInsert)
  920. );
  921. if ($this->execute($this->renderStatement('create', $query))) {
  922. if (empty($id)) {
  923. $id = $this->lastInsertId($this->fullTableName($model, false, false), $model->primaryKey);
  924. }
  925. $model->setInsertID($id);
  926. $model->id = $id;
  927. return true;
  928. }
  929. $model->onError();
  930. return false;
  931. }
  932. /**
  933. * The "R" in CRUD
  934. *
  935. * Reads record(s) from the database.
  936. *
  937. * @param Model $model A Model object that the query is for.
  938. * @param array $queryData An array of queryData information containing keys similar to Model::find()
  939. * @param integer $recursive Number of levels of association
  940. * @return mixed boolean false on error/failure. An array of results on success.
  941. */
  942. public function read(Model $model, $queryData = array(), $recursive = null) {
  943. $queryData = $this->_scrubQueryData($queryData);
  944. $null = null;
  945. $array = array('callbacks' => $queryData['callbacks']);
  946. $linkedModels = array();
  947. $bypass = false;
  948. if ($recursive === null && isset($queryData['recursive'])) {
  949. $recursive = $queryData['recursive'];
  950. }
  951. if (!is_null($recursive)) {
  952. $_recursive = $model->recursive;
  953. $model->recursive = $recursive;
  954. }
  955. if (!empty($queryData['fields'])) {
  956. $bypass = true;
  957. $queryData['fields'] = $this->fields($model, null, $queryData['fields']);
  958. } else {
  959. $queryData['fields'] = $this->fields($model);
  960. }
  961. $_associations = $model->associations();
  962. if ($model->recursive == -1) {
  963. $_associations = array();
  964. } elseif ($model->recursive == 0) {
  965. unset($_associations[2], $_associations[3]);
  966. }
  967. foreach ($_associations as $type) {
  968. foreach ($model->{$type} as $assoc => $assocData) {
  969. $linkModel = $model->{$assoc};
  970. $external = isset($assocData['external']);
  971. $linkModel->getDataSource();
  972. if ($model->useDbConfig === $linkModel->useDbConfig) {
  973. if ($bypass) {
  974. $assocData['fields'] = false;
  975. }
  976. if (true === $this->generateAssociationQuery($model, $linkModel, $type, $assoc, $assocData, $queryData, $external, $null)) {
  977. $linkedModels[$type . '/' . $assoc] = true;
  978. }
  979. }
  980. }
  981. }
  982. $query = trim($this->generateAssociationQuery($model, null, null, null, null, $queryData, false, $null));
  983. $resultSet = $this->fetchAll($query, $model->cacheQueries);
  984. if ($resultSet === false) {
  985. $model->onError();
  986. return false;
  987. }
  988. $filtered = array();
  989. if ($queryData['callbacks'] === true || $queryData['callbacks'] === 'after') {
  990. $filtered = $this->_filterResults($resultSet, $model);
  991. }
  992. if ($model->recursive > -1) {
  993. foreach ($_associations as $type) {
  994. foreach ($model->{$type} as $assoc => $assocData) {
  995. $linkModel = $model->{$assoc};
  996. if (!isset($linkedModels[$type . '/' . $assoc])) {
  997. if ($model->useDbConfig === $linkModel->useDbConfig) {
  998. $db = $this;
  999. } else {
  1000. $db = ConnectionManager::getDataSource($linkModel->useDbConfig);
  1001. }
  1002. } elseif ($model->recursive > 1 && ($type === 'belongsTo' || $type === 'hasOne')) {
  1003. $db = $this;
  1004. }
  1005. if (isset($db) && method_exists($db, 'queryAssociation')) {
  1006. $stack = array($assoc);
  1007. $db->queryAssociation($model, $linkModel, $type, $assoc, $assocData, $array, true, $resultSet, $model->recursive - 1, $stack);
  1008. unset($db);
  1009. if ($type === 'hasMany') {
  1010. $filtered[] = $assoc;
  1011. }
  1012. }
  1013. }
  1014. }
  1015. if ($queryData['callbacks'] === true || $queryData['callbacks'] === 'after') {
  1016. $this->_filterResults($resultSet, $model, $filtered);
  1017. }
  1018. }
  1019. if (!is_null($recursive)) {
  1020. $model->recursive = $_recursive;
  1021. }
  1022. return $resultSet;
  1023. }
  1024. /**
  1025. * Passes association results thru afterFind filters of corresponding model
  1026. *
  1027. * @param array $results Reference of resultset to be filtered
  1028. * @param Model $model Instance of model to operate against
  1029. * @param array $filtered List of classes already filtered, to be skipped
  1030. * @return array Array of results that have been filtered through $model->afterFind
  1031. */
  1032. protected function _filterResults(&$results, Model $model, $filtered = array()) {
  1033. $current = reset($results);
  1034. if (!is_array($current)) {
  1035. return array();
  1036. }
  1037. $keys = array_diff(array_keys($current), $filtered, array($model->alias));
  1038. $filtering = array();
  1039. foreach ($keys as $className) {
  1040. if (!isset($model->{$className}) || !is_object($model->{$className})) {
  1041. continue;
  1042. }
  1043. $linkedModel = $model->{$className};
  1044. $filtering[] = $className;
  1045. foreach ($results as &$result) {
  1046. $data = $linkedModel->afterFind(array(array($className => $result[$className])), false);
  1047. if (isset($data[0][$className])) {
  1048. $result[$className] = $data[0][$className];
  1049. }
  1050. }
  1051. }
  1052. return $filtering;
  1053. }
  1054. /**
  1055. * Queries associations. Used to fetch results on recursive models.
  1056. *
  1057. * @param Model $model Primary Model object
  1058. * @param Model $linkModel Linked model that
  1059. * @param string $type Association type, one of the model association types ie. hasMany
  1060. * @param string $association
  1061. * @param array $assocData
  1062. * @param array $queryData
  1063. * @param boolean $external Whether or not the association query is on an external datasource.
  1064. * @param array $resultSet Existing results
  1065. * @param integer $recursive Number of levels of association
  1066. * @param array $stack
  1067. * @return mixed
  1068. * @throws CakeException when results cannot be created.
  1069. */
  1070. public function queryAssociation(Model $model, &$linkModel, $type, $association, $assocData, &$queryData, $external, &$resultSet, $recursive, $stack) {
  1071. if ($query = $this->generateAssociationQuery($model, $linkModel, $type, $association, $assocData, $queryData, $external, $resultSet)) {
  1072. if (!is_array($resultSet)) {
  1073. throw new CakeException(__d('cake_dev', 'Error in Model %s', get_class($model)));
  1074. }
  1075. if ($type === 'hasMany' && empty($assocData['limit']) && !empty($assocData['foreignKey'])) {
  1076. $ins = $fetch = array();
  1077. foreach ($resultSet as &$result) {
  1078. if ($in = $this->insertQueryData('{$__cakeID__$}', $result, $association, $assocData, $model, $linkModel, $stack)) {
  1079. $ins[] = $in;
  1080. }
  1081. }
  1082. if (!empty($ins)) {
  1083. $ins = array_unique($ins);
  1084. $fetch = $this->fetchAssociated($model, $query, $ins);
  1085. }
  1086. if (!empty($fetch) && is_array($fetch)) {
  1087. if ($recursive > 0) {
  1088. foreach ($linkModel->associations() as $type1) {
  1089. foreach ($linkModel->{$type1} as $assoc1 => $assocData1) {
  1090. $deepModel = $linkModel->{$assoc1};
  1091. $tmpStack = $stack;
  1092. $tmpStack[] = $assoc1;
  1093. if ($linkModel->useDbConfig === $deepModel->useDbConfig) {
  1094. $db = $this;
  1095. } else {
  1096. $db = ConnectionManager::getDataSource($deepModel->useDbConfig);
  1097. }
  1098. $db->queryAssociation($linkModel, $deepModel, $type1, $assoc1, $assocData1, $queryData, true, $fetch, $recursive - 1, $tmpStack);
  1099. }
  1100. }
  1101. }
  1102. }
  1103. if ($queryData['callbacks'] === true || $queryData['callbacks'] === 'after') {
  1104. $this->_filterResults($fetch, $model);
  1105. }
  1106. return $this->_mergeHasMany($resultSet, $fetch, $association, $model, $linkModel);
  1107. } elseif ($type === 'hasAndBelongsToMany') {
  1108. $ins = $fetch = array();
  1109. foreach ($resultSet as &$result) {
  1110. if ($in = $this->insertQueryData('{$__cakeID__$}', $result, $association, $assocData, $model, $linkModel, $stack)) {
  1111. $ins[] = $in;
  1112. }
  1113. }
  1114. if (!empty($ins)) {
  1115. $ins = array_unique($ins);
  1116. if (count($ins) > 1) {
  1117. $query = str_replace('{$__cakeID__$}', '(' . implode(', ', $ins) . ')', $query);
  1118. $query = str_replace('= (', 'IN (', $query);
  1119. } else {
  1120. $query = str_replace('{$__cakeID__$}', $ins[0], $query);
  1121. }
  1122. $query = str_replace(' WHERE 1 = 1', '', $query);
  1123. }
  1124. $foreignKey = $model->hasAndBelongsToMany[$association]['foreignKey'];
  1125. $joinKeys = array($foreignKey, $model->hasAndBelongsToMany[$association]['associationForeignKey']);
  1126. list($with, $habtmFields) = $model->joinModel($model->hasAndBelongsToMany[$association]['with'], $joinKeys);
  1127. $habtmFieldsCount = count($habtmFields);
  1128. $q = $this->insertQueryData($query, null, $association, $assocData, $model, $linkModel, $stack);
  1129. if ($q !== false) {
  1130. $fetch = $this->fetchAll($q, $model->cacheQueries);
  1131. } else {
  1132. $fetch = null;
  1133. }
  1134. }
  1135. $modelAlias = $model->alias;
  1136. $modelPK = $model->primaryKey;
  1137. foreach ($resultSet as &$row) {
  1138. if ($type !== 'hasAndBelongsToMany') {
  1139. $q = $this->insertQueryData($query, $row, $association, $assocData, $model, $linkModel, $stack);
  1140. if ($q !== false) {
  1141. $fetch = $this->fetchAll($q, $model->cacheQueries);
  1142. } else {
  1143. $fetch = null;
  1144. }
  1145. }
  1146. $selfJoin = $linkModel->name === $model->name;
  1147. if (!empty($fetch) && is_array($fetch)) {
  1148. if ($recursive > 0) {
  1149. foreach ($linkModel->associations() as $type1) {
  1150. foreach ($linkModel->{$type1} as $assoc1 => $assocData1) {
  1151. $deepModel = $linkModel->{$assoc1};
  1152. if ($type1 === 'belongsTo' || ($deepModel->alias === $modelAlias && $type === 'belongsTo') || ($deepModel->alias !== $modelAlias)) {
  1153. $tmpStack = $stack;
  1154. $tmpStack[] = $assoc1;
  1155. if ($linkModel->useDbConfig == $deepModel->useDbConfig) {
  1156. $db = $this;
  1157. } else {
  1158. $db = ConnectionManager::getDataSource($deepModel->useDbConfig);
  1159. }
  1160. $db->queryAssociation($linkModel, $deepModel, $type1, $assoc1, $assocData1, $queryData, true, $fetch, $recursive - 1, $tmpStack);
  1161. }
  1162. }
  1163. }
  1164. }
  1165. if ($type === 'hasAndBelongsToMany') {
  1166. $uniqueIds = $merge = array();
  1167. foreach ($fetch as $j => $data) {
  1168. if (isset($data[$with]) && $data[$with][$foreignKey] === $row[$modelAlias][$modelPK]) {
  1169. if ($habtmFieldsCount <= 2) {
  1170. unset($data[$with]);
  1171. }
  1172. $merge[] = $data;
  1173. }
  1174. }
  1175. if (empty($merge) && !isset($row[$association])) {
  1176. $row[$association] = $merge;
  1177. } else {
  1178. $this->_mergeAssociation($row, $merge, $association, $type);
  1179. }
  1180. } else {
  1181. $this->_mergeAssociation($row, $fetch, $association, $type, $selfJoin);
  1182. }
  1183. if (isset($row[$association])) {
  1184. $row[$association] = $linkModel->afterFind($row[$association], false);
  1185. }
  1186. } else {
  1187. $tempArray[0][$association] = false;
  1188. $this->_mergeAssociation($row, $tempArray, $association, $type, $selfJoin);
  1189. }
  1190. }
  1191. }
  1192. }
  1193. /**
  1194. * A more efficient way to fetch associations. Woohoo!
  1195. *
  1196. * @param Model $model Primary model object
  1197. * @param string $query Association query
  1198. * @param array $ids Array of IDs of associated records
  1199. * @return array Association results
  1200. */
  1201. public function fetchAssociated(Model $model, $query, $ids) {
  1202. $query = str_replace('{$__cakeID__$}', implode(', ', $ids), $query);
  1203. if (count($ids) > 1) {
  1204. $query = str_replace('= (', 'IN (', $query);
  1205. }
  1206. return $this->fetchAll($query, $model->cacheQueries);
  1207. }
  1208. /**
  1209. * mergeHasMany - Merge the results of hasMany relations.
  1210. *
  1211. *
  1212. * @param array $resultSet Data to merge into
  1213. * @param array $merge Data to merge
  1214. * @param string $association Name of Model being Merged
  1215. * @param Model $model Model being merged onto
  1216. * @param Model $linkModel Model being merged
  1217. * @return void
  1218. */
  1219. protected function _mergeHasMany(&$resultSet, $merge, $association, $model, $linkModel) {
  1220. $modelAlias = $model->alias;
  1221. $modelPK = $model->primaryKey;
  1222. $modelFK = $model->hasMany[$association]['foreignKey'];
  1223. foreach ($resultSet as &$result) {
  1224. if (!isset($result[$modelAlias])) {
  1225. continue;
  1226. }
  1227. $merged = array();
  1228. foreach ($merge as $data) {
  1229. if ($result[$modelAlias][$modelPK] === $data[$association][$modelFK]) {
  1230. if (count($data) > 1) {
  1231. $data = array_merge($data[$association], $data);
  1232. unset($data[$association]);
  1233. foreach ($data as $key => $name) {
  1234. if (is_numeric($key)) {
  1235. $data[$association][] = $name;
  1236. unset($data[$key]);
  1237. }
  1238. }
  1239. $merged[] = $data;
  1240. } else {
  1241. $merged[] = $data[$association];
  1242. }
  1243. }
  1244. }
  1245. $result = Hash::mergeDiff($result, array($association => $merged));
  1246. }
  1247. }
  1248. /**
  1249. * Merge association of merge into data
  1250. *
  1251. * @param array $data
  1252. * @param array $merge
  1253. * @param string $association
  1254. * @param string $type
  1255. * @param boolean $selfJoin
  1256. * @return void
  1257. */
  1258. protected function _mergeAssociation(&$data, &$merge, $association, $type, $selfJoin = false) {
  1259. if (isset($merge[0]) && !isset($merge[0][$association])) {
  1260. $association = Inflector::pluralize($association);
  1261. }
  1262. if ($type === 'belongsTo' || $type === 'hasOne') {
  1263. if (isset($merge[$association])) {
  1264. $data[$association] = $merge[$association][0];
  1265. } else {
  1266. if (count($merge[0][$association]) > 1) {
  1267. foreach ($merge[0] as $assoc => $data2) {
  1268. if ($assoc !== $association) {
  1269. $merge[0][$association][$assoc] = $data2;
  1270. }
  1271. }
  1272. }
  1273. if (!isset($data[$association])) {
  1274. if ($merge[0][$association] != null) {
  1275. $data[$association] = $merge[0][$association];
  1276. } else {
  1277. $data[$association] = array();
  1278. }
  1279. } else {
  1280. if (is_array($merge[0][$association])) {
  1281. foreach ($data[$association] as $k => $v) {
  1282. if (!is_array($v)) {
  1283. $dataAssocTmp[$k] = $v;
  1284. }
  1285. }
  1286. foreach ($merge[0][$association] as $k => $v) {
  1287. if (!is_array($v)) {
  1288. $mergeAssocTmp[$k] = $v;
  1289. }
  1290. }
  1291. $dataKeys = array_keys($data);
  1292. $mergeKeys = array_keys($merge[0]);
  1293. if ($mergeKeys[0] === $dataKeys[0] || $mergeKeys === $dataKeys) {
  1294. $data[$association][$association] = $merge[0][$association];
  1295. } else {
  1296. $diff = Hash::diff($dataAssocTmp, $mergeAssocTmp);
  1297. $data[$association] = array_merge($merge[0][$association], $diff);
  1298. }
  1299. } elseif ($selfJoin && array_key_exists($association, $merge[0])) {
  1300. $data[$association] = array_merge($data[$association], array($association => array()));
  1301. }
  1302. }
  1303. }
  1304. } else {
  1305. if (isset($merge[0][$association]) && $merge[0][$association] === false) {
  1306. if (!isset($data[$association])) {
  1307. $data[$association] = array();
  1308. }
  1309. } else {
  1310. foreach ($merge as $i => $row) {
  1311. $insert = array();
  1312. if (count($row) === 1) {
  1313. $insert = $row[$association];
  1314. } elseif (isset($row[$association])) {
  1315. $insert = array_merge($row[$association], $row);
  1316. unset($insert[$association]);
  1317. }
  1318. if (empty($data[$association]) || (isset($data[$association]) && !in_array($insert, $data[$association], true))) {
  1319. $data[$association][] = $insert;
  1320. }
  1321. }
  1322. }
  1323. }
  1324. }
  1325. /**
  1326. * Generates an array representing a query or part of a query from a single model or two associated models
  1327. *
  1328. * @param Model $model
  1329. * @param Model $linkModel
  1330. * @param string $type
  1331. * @param string $association
  1332. * @param array $assocData
  1333. * @param array $queryData
  1334. * @param boolean $external
  1335. * @param array $resultSet
  1336. * @return mixed
  1337. */
  1338. public function generateAssociationQuery(Model $model, $linkModel, $type, $association, $assocData, &$queryData, $external, &$resultSet) {
  1339. $queryData = $this->_scrubQueryData($queryData);
  1340. $assocData = $this->_scrubQueryData($assocData);
  1341. $modelAlias = $model->alias;
  1342. if (empty($queryData['fields'])) {
  1343. $queryData['fields'] = $this->fields($model, $modelAlias);
  1344. } elseif (!empty($model->hasMany) && $model->recursive > -1) {
  1345. $assocFields = $this->fields($model, $modelAlias, array("{$modelAlias}.{$model->primaryKey}"));
  1346. $passedFields = $queryData['fields'];
  1347. if (count($passedFields) === 1) {
  1348. if (strpos($passedFields[0], $assocFields[0]) === false && !preg_match('/^[a-z]+\(/i', $passedFields[0])) {
  1349. $queryData['fields'] = array_merge($passedFields, $assocFields);
  1350. } else {
  1351. $queryData['fields'] = $passedFields;
  1352. }
  1353. } else {
  1354. $queryData['fields'] = array_merge($passedFields, $assocFields);
  1355. }
  1356. unset($assocFields, $passedFields);
  1357. }
  1358. if ($linkModel === null) {
  1359. return $this->buildStatement(
  1360. array(
  1361. 'fields' => array_unique($queryData['fields']),
  1362. 'table' => $this->fullTableName($model),
  1363. 'alias' => $modelAlias,
  1364. 'limit' => $queryData['limit'],
  1365. 'offset' => $queryData['offset'],
  1366. 'joins' => $queryData['joins'],
  1367. 'conditions' => $queryData['conditions'],
  1368. 'order' => $queryData['order'],
  1369. 'group' => $queryData['group']
  1370. ),
  1371. $model
  1372. );
  1373. }
  1374. if ($external && !empty($assocData['finderQuery'])) {
  1375. return $assocData['finderQuery'];
  1376. }
  1377. $self = $model->name === $linkModel->name;
  1378. $fields = array();
  1379. if ($external || (in_array($type, array('hasOne', 'belongsTo')) && $assocData['fields'] !== false)) {
  1380. $fields = $this->fields($linkModel, $association, $assocData['fields']);
  1381. }
  1382. if (empty($assocData['offset']) && !empty($assocData['page'])) {
  1383. $assocData['offset'] = ($assocData['page'] - 1) * $assocData['limit'];
  1384. }
  1385. $assocData['limit'] = $this->limit($assocData['limit'], $assocData['offset']);
  1386. switch ($type) {
  1387. case 'hasOne':
  1388. case 'belongsTo':
  1389. $conditions = $this->_mergeConditions(
  1390. $assocData['conditions'],
  1391. $this->getConstraint($type, $model, $linkModel, $association, array_merge($assocData, compact('external', 'self')))
  1392. );
  1393. if (!$self && $external) {
  1394. foreach ($conditions as $key => $condition) {
  1395. if (is_numeric($key) && strpos($condition, $modelAlias . '.') !== false) {
  1396. unset($conditions[$key]);
  1397. }
  1398. }
  1399. }
  1400. if ($external) {
  1401. $query = array_merge($assocData, array(
  1402. 'conditions' => $conditions,
  1403. 'table' => $this->fullTableName($linkModel),
  1404. 'fields' => $fields,
  1405. 'alias' => $association,
  1406. 'group' => null
  1407. ));
  1408. $query += array('order' => $assocData['order'], 'limit' => $assocData['limit']);
  1409. } else {
  1410. $join = array(
  1411. 'table' => $linkModel,
  1412. 'alias' => $association,
  1413. 'type' => isset($assocData['type']) ? $assocData['type'] : 'LEFT',
  1414. 'conditions' => trim($this->conditions($conditions, true, false, $model))
  1415. );
  1416. $queryData['fields'] = array_merge($queryData['fields'], $fields);
  1417. if (!empty($assocData['order'])) {
  1418. $queryData['order'][] = $assocData['order'];
  1419. }
  1420. if (!in_array($join, $queryData['joins'])) {
  1421. $queryData['joins'][] = $join;
  1422. }
  1423. return true;
  1424. }
  1425. break;
  1426. case 'hasMany':
  1427. $assocData['fields'] = $this->fields($linkModel, $association, $assocData['fields']);
  1428. if (!empty($assocData['foreignKey'])) {
  1429. $assocData['fields'] = array_merge($assocData['fields'], $this->fields($linkModel, $association, array("{$association}.{$assocData['foreignKey']}")));
  1430. }
  1431. $query = array(
  1432. 'conditions' => $this->_mergeConditions($this->getConstraint('hasMany', $model, $linkModel, $association, $assocData), $assocData['conditions']),
  1433. 'fields' => array_unique($assocData['fields']),
  1434. 'table' => $this->fullTableName($linkModel),
  1435. 'alias' => $association,
  1436. 'order' => $assocData['order'],
  1437. 'limit' => $assocData['limit'],
  1438. 'group' => null
  1439. );
  1440. break;
  1441. case 'hasAndBelongsToMany':
  1442. $joinFields = array();
  1443. $joinAssoc = null;
  1444. if (isset($assocData['with']) && !empty($assocData['with'])) {
  1445. $joinKeys = array($assocData['foreignKey'], $assocData['associationForeignKey']);
  1446. list($with, $joinFields) = $model->joinModel($assocData['with'], $joinKeys);
  1447. $joinTbl = $model->{$with};
  1448. $joinAlias = $joinTbl;
  1449. if (is_array($joinFields) && !empty($joinFields)) {
  1450. $joinAssoc = $joinAlias = $model->{$with}->alias;
  1451. $joinFields = $this->fields($model->{$with}, $joinAlias, $joinFields);
  1452. } else {
  1453. $joinFields = array();
  1454. }
  1455. } else {
  1456. $joinTbl = $assocData['joinTable'];
  1457. $joinAlias = $this->fullTableName($assocData['joinTable']);
  1458. }
  1459. $query = array(
  1460. 'conditions' => $assocData['conditions'],
  1461. 'limit' => $assocData['limit'],
  1462. 'table' => $this->fullTableName($linkModel),
  1463. 'alias' => $association,
  1464. 'fields' => array_merge($this->fields($linkModel, $association, $assocData['fields']), $joinFields),
  1465. 'order' => $assocData['order'],
  1466. 'group' => null,
  1467. 'joins' => array(array(
  1468. 'table' => $joinTbl,
  1469. 'alias' => $joinAssoc,
  1470. 'conditions' => $this->getConstraint('hasAndBelongsToMany', $model, $linkModel, $joinAlias, $assocData, $association)
  1471. ))
  1472. );
  1473. break;
  1474. }
  1475. if (isset($query)) {
  1476. return $this->buildStatement($query, $model);
  1477. }
  1478. return null;
  1479. }
  1480. /**
  1481. * Returns a conditions array for the constraint between two models
  1482. *
  1483. * @param string $type Association type
  1484. * @param Model $model Model object
  1485. * @param string $linkModel
  1486. * @param string $alias
  1487. * @param array $assoc
  1488. * @param string $alias2
  1489. * @return array Conditions array defining the constraint between $model and $association
  1490. */
  1491. public function getConstraint($type, $model, $linkModel, $alias, $assoc, $alias2 = null) {
  1492. $assoc += array('external' => false, 'self' => false);
  1493. if (empty($assoc['foreignKey'])) {
  1494. return array();
  1495. }
  1496. switch (true) {
  1497. case ($assoc['external'] && $type === 'hasOne'):
  1498. return array("{$alias}.{$assoc['foreignKey']}" => '{$__cakeID__$}');
  1499. case ($assoc['external'] && $type === 'belongsTo'):
  1500. return array("{$alias}.{$linkModel->primaryKey}" => '{$__cakeForeignKey__$}');
  1501. case (!$assoc['external'] && $type === 'hasOne'):
  1502. return array("{$alias}.{$assoc['foreignKey']}" => $this->identifier("{$model->alias}.{$model->primaryKey}"));
  1503. case (!$assoc['external'] && $type === 'belongsTo'):
  1504. return array("{$model->alias}.{$assoc['foreignKey']}" => $this->identifier("{$alias}.{$linkModel->primaryKey}"));
  1505. case ($type === 'hasMany'):
  1506. return array("{$alias}.{$assoc['foreignKey']}" => array('{$__cakeID__$}'));
  1507. case ($type === 'hasAndBelongsToMany'):
  1508. return array(
  1509. array("{$alias}.{$assoc['foreignKey']}" => '{$__cakeID__$}'),
  1510. array("{$alias}.{$assoc['associationForeignKey']}" => $this->identifier("{$alias2}.{$linkModel->primaryKey}"))
  1511. );
  1512. }
  1513. return array();
  1514. }
  1515. /**
  1516. * Builds and generates a JOIN statement from an array. Handles final clean-up before conversion.
  1517. *
  1518. * @param array $join An array defining a JOIN statement in a query
  1519. * @return string An SQL JOIN statement to be used in a query
  1520. * @see DboSource::renderJoinStatement()
  1521. * @see DboSource::buildStatement()
  1522. */
  1523. public function buildJoinStatement($join) {
  1524. $data = array_merge(array(
  1525. 'type' => null,
  1526. 'alias' => null,
  1527. 'table' => 'join_table',
  1528. 'conditions' => array()
  1529. ), $join);
  1530. if (!empty($data['alias'])) {
  1531. $data['alias'] = $this->alias . $this->name($data['alias']);
  1532. }
  1533. if (!empty($data['conditions'])) {
  1534. $data['conditions'] = trim($this->conditions($data['conditions'], true, false));
  1535. }
  1536. if (!empty($data['table'])) {
  1537. $schema = !(is_string($data['table']) && strpos($data['table'], '(') === 0);
  1538. $data['table'] = $this->fullTableName($data['table'], true, $schema);
  1539. }
  1540. return $this->renderJoinStatement($data);
  1541. }
  1542. /**
  1543. * Builds and generates an SQL statement from an array. Handles final clean-up before conversion.
  1544. *
  1545. * @param array $query An array defining an SQL query
  1546. * @param Model $model The model object which initiated the query
  1547. * @return string An executable SQL statement
  1548. * @see DboSource::renderStatement()
  1549. */
  1550. public function buildStatement($query, $model) {
  1551. $query = array_merge($this->_queryDefaults, $query);
  1552. if (!empty($query['joins'])) {
  1553. $count = count($query['joins']);
  1554. for ($i = 0; $i < $count; $i++) {
  1555. if (is_array($query['joins'][$i])) {
  1556. $query['joins'][$i] = $this->buildJoinStatement($query['joins'][$i]);
  1557. }
  1558. }
  1559. }
  1560. return $this->renderStatement('select', array(
  1561. 'conditions' => $this->conditions($query['conditions'], true, true, $model),
  1562. 'fields' => implode(', ', $query['fields']),
  1563. 'table' => $query['table'],
  1564. 'alias' => $this->alias . $this->name($query['alias']),
  1565. 'order' => $this->order($query['order'], 'ASC', $model),
  1566. 'limit' => $this->limit($query['limit'], $query['offset']),
  1567. 'joins' => implode(' ', $query['joins']),
  1568. 'group' => $this->group($query['group'], $model)
  1569. ));
  1570. }
  1571. /**
  1572. * Renders a final SQL JOIN statement
  1573. *
  1574. * @param array $data
  1575. * @return string
  1576. */
  1577. public function renderJoinStatement($data) {
  1578. extract($data);
  1579. return trim("{$type} JOIN {$table} {$alias} ON ({$conditions})");
  1580. }
  1581. /**
  1582. * Renders a final SQL statement by putting together the component parts in the correct order
  1583. *
  1584. * @param string $type type of query being run. e.g select, create, update, delete, schema, alter.
  1585. * @param array $data Array of data to insert into the query.
  1586. * @return string Rendered SQL expression to be run.
  1587. */
  1588. public function renderStatement($type, $data) {
  1589. extract($data);
  1590. $aliases = null;
  1591. switch (strtolower($type)) {
  1592. case 'select':
  1593. return "SELECT {$fields} FROM {$table} {$alias} {$joins} {$conditions} {$group} {$order} {$limit}";
  1594. case 'create':
  1595. return "INSERT INTO {$table} ({$fields}) VALUES ({$values})";
  1596. case 'update':
  1597. if (!empty($alias)) {
  1598. $aliases = "{$this->alias}{$alias} {$joins} ";
  1599. }
  1600. return "UPDATE {$table} {$aliases}SET {$fields} {$conditions}";
  1601. case 'delete':
  1602. if (!empty($alias)) {
  1603. $aliases = "{$this->alias}{$alias} {$joins} ";
  1604. }
  1605. return "DELETE {$alias} FROM {$table} {$aliases}{$conditions}";
  1606. case 'schema':
  1607. foreach (array('columns', 'indexes', 'tableParameters') as $var) {
  1608. if (is_array(${$var})) {
  1609. ${$var} = "\t" . join(",\n\t", array_filter(${$var}));
  1610. } else {
  1611. ${$var} = '';
  1612. }
  1613. }
  1614. if (trim($indexes) !== '') {
  1615. $columns .= ',';
  1616. }
  1617. return "CREATE TABLE {$table} (\n{$columns}{$indexes}) {$tableParameters};";
  1618. case 'alter':
  1619. return;
  1620. }
  1621. }
  1622. /**
  1623. * Merges a mixed set of string/array conditions
  1624. *
  1625. * @param mixed $query
  1626. * @param mixed $assoc
  1627. * @return array
  1628. */
  1629. protected function _mergeConditions($query, $assoc) {
  1630. if (empty($assoc)) {
  1631. return $query;
  1632. }
  1633. if (is_array($query)) {
  1634. return array_merge((array)$assoc, $query);
  1635. }
  1636. if (!empty($query)) {
  1637. $query = array($query);
  1638. if (is_array($assoc)) {
  1639. $query = array_merge($query, $assoc);
  1640. } else {
  1641. $query[] = $assoc;
  1642. }
  1643. return $query;
  1644. }
  1645. return $assoc;
  1646. }
  1647. /**
  1648. * Generates and executes an SQL UPDATE statement for given model, fields, and values.
  1649. * For databases that do not support aliases in UPDATE queries.
  1650. *
  1651. * @param Model $model
  1652. * @param array $fields
  1653. * @param array $values
  1654. * @param mixed $conditions
  1655. * @return boolean Success
  1656. */
  1657. public function update(Model $model, $fields = array(), $values = null, $conditions = null) {
  1658. if ($values == null) {
  1659. $combined = $fields;
  1660. } else {
  1661. $combined = array_combine($fields, $values);
  1662. }
  1663. $fields = implode(', ', $this->_prepareUpdateFields($model, $combined, empty($conditions)));
  1664. $alias = $joins = null;
  1665. $table = $this->fullTableName($model);
  1666. $conditions = $this->_matchRecords($model, $conditions);
  1667. if ($conditions === false) {
  1668. return false;
  1669. }
  1670. $query = compact('table', 'alias', 'joins', 'fields', 'conditions');
  1671. if (!$this->execute($this->renderStatement('update', $query))) {
  1672. $model->onError();
  1673. return false;
  1674. }
  1675. return true;
  1676. }
  1677. /**
  1678. * Quotes and prepares fields and values for an SQL UPDATE statement
  1679. *
  1680. * @param Model $model
  1681. * @param array $fields
  1682. * @param boolean $quoteValues If values should be quoted, or treated as SQL snippets
  1683. * @param boolean $alias Include the model alias in the field name
  1684. * @return array Fields and values, quoted and prepared
  1685. */
  1686. protected function _prepareUpdateFields(Model $model, $fields, $quoteValues = true, $alias = false) {
  1687. $quotedAlias = $this->startQuote . $model->alias . $this->endQuote;
  1688. $updates = array();
  1689. foreach ($fields as $field => $value) {
  1690. if ($alias && strpos($field, '.') === false) {
  1691. $quoted = $model->escapeField($field);
  1692. } elseif (!$alias && strpos($field, '.') !== false) {
  1693. $quoted = $this->name(str_replace($quotedAlias . '.', '', str_replace(
  1694. $model->alias . '.', '', $field
  1695. )));
  1696. } else {
  1697. $quoted = $this->name($field);
  1698. }
  1699. if ($value === null) {
  1700. $updates[] = $quoted . ' = NULL';
  1701. continue;
  1702. }
  1703. $update = $quoted . ' = ';
  1704. if ($quoteValues) {
  1705. $update .= $this->value($value, $model->getColumnType($field));
  1706. } elseif ($model->getColumnType($field) == 'boolean' && (is_int($value) || is_bool($value))) {
  1707. $update .= $this->boolean($value, true);
  1708. } elseif (!$alias) {
  1709. $update .= str_replace($quotedAlias . '.', '', str_replace(
  1710. $model->alias . '.', '', $value
  1711. ));
  1712. } else {
  1713. $update .= $value;
  1714. }
  1715. $updates[] = $update;
  1716. }
  1717. return $updates;
  1718. }
  1719. /**
  1720. * Generates and executes an SQL DELETE statement.
  1721. * For databases that do not support aliases in UPDATE queries.
  1722. *
  1723. * @param Model $model
  1724. * @param mixed $conditions
  1725. * @return boolean Success
  1726. */
  1727. public function delete(Model $model, $conditions = null) {
  1728. $alias = $joins = null;
  1729. $table = $this->fullTableName($model);
  1730. $conditions = $this->_matchRecords($model, $conditions);
  1731. if ($conditions === false) {
  1732. return false;
  1733. }
  1734. if ($this->execute($this->renderStatement('delete', compact('alias', 'table', 'joins', 'conditions'))) === false) {
  1735. $model->onError();
  1736. return false;
  1737. }
  1738. return true;
  1739. }
  1740. /**
  1741. * Gets a list of record IDs for the given conditions. Used for multi-record updates and deletes
  1742. * in databases that do not support aliases in UPDATE/DELETE queries.
  1743. *
  1744. * @param Model $model
  1745. * @param mixed $conditions
  1746. * @return array List of record IDs
  1747. */
  1748. protected function _matchRecords(Model $model, $conditions = null) {
  1749. if ($conditions === true) {
  1750. $conditions = $this->conditions(true);
  1751. } elseif ($conditions === null) {
  1752. $conditions = $this->conditions($this->defaultConditions($model, $conditions, false), true, true, $model);
  1753. } else {
  1754. $noJoin = true;
  1755. foreach ($conditions as $field => $value) {
  1756. $originalField = $field;
  1757. if (strpos($field, '.') !== false) {
  1758. list($alias, $field) = explode('.', $field);
  1759. $field = ltrim($field, $this->startQuote);
  1760. $field = rtrim($field, $this->endQuote);
  1761. }
  1762. if (!$model->hasField($field)) {
  1763. $noJoin = false;
  1764. break;
  1765. }
  1766. if ($field !== $originalField) {
  1767. $conditions[$field] = $value;
  1768. unset($conditions[$originalField]);
  1769. }
  1770. }
  1771. if ($noJoin === true) {
  1772. return $this->conditions($conditions);
  1773. }
  1774. $idList = $model->find('all', array(
  1775. 'fields' => "{$model->alias}.{$model->primaryKey}",
  1776. 'conditions' => $conditions
  1777. ));
  1778. if (empty($idList)) {
  1779. return false;
  1780. }
  1781. $conditions = $this->conditions(array(
  1782. $model->primaryKey => Hash::extract($idList, "{n}.{$model->alias}.{$model->primaryKey}")
  1783. ));
  1784. }
  1785. return $conditions;
  1786. }
  1787. /**
  1788. * Returns an array of SQL JOIN fragments from a model's associations
  1789. *
  1790. * @param Model $model
  1791. * @return array
  1792. */
  1793. protected function _getJoins(Model $model) {
  1794. $join = array();
  1795. $joins = array_merge($model->getAssociated('hasOne'), $model->getAssociated('belongsTo'));
  1796. foreach ($joins as $assoc) {
  1797. if (isset($model->{$assoc}) && $model->useDbConfig == $model->{$assoc}->useDbConfig && $model->{$assoc}->getDataSource()) {
  1798. $assocData = $model->getAssociated($assoc);
  1799. $join[] = $this->buildJoinStatement(array(
  1800. 'table' => $model->{$assoc},
  1801. 'alias' => $assoc,
  1802. 'type' => isset($assocData['type']) ? $assocData['type'] : 'LEFT',
  1803. 'conditions' => trim($this->conditions(
  1804. $this->_mergeConditions($assocData['conditions'], $this->getConstraint($assocData['association'], $model, $model->{$assoc}, $assoc, $assocData)),
  1805. true, false, $model
  1806. ))
  1807. ));
  1808. }
  1809. }
  1810. return $join;
  1811. }
  1812. /**
  1813. * Returns an SQL calculation, i.e. COUNT() or MAX()
  1814. *
  1815. * @param Model $model
  1816. * @param string $func Lowercase name of SQL function, i.e. 'count' or 'max'
  1817. * @param array $params Function parameters (any values must be quoted manually)
  1818. * @return string An SQL calculation function
  1819. */
  1820. public function calculate(Model $model, $func, $params = array()) {
  1821. $params = (array)$params;
  1822. switch (strtolower($func)) {
  1823. case 'count':
  1824. if (!isset($params[0])) {
  1825. $params[0] = '*';
  1826. }
  1827. if (!isset($params[1])) {
  1828. $params[1] = 'count';
  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 'COUNT(' . $arg . ') AS ' . $this->name($params[1]);
  1836. case 'max':
  1837. case 'min':
  1838. if (!isset($params[1])) {
  1839. $params[1] = $params[0];
  1840. }
  1841. if (is_object($model) && $model->isVirtualField($params[0])) {
  1842. $arg = $this->_quoteFields($model->getVirtualField($params[0]));
  1843. } else {
  1844. $arg = $this->name($params[0]);
  1845. }
  1846. return strtoupper($func) . '(' . $arg . ') AS ' . $this->name($params[1]);
  1847. break;
  1848. }
  1849. }
  1850. /**
  1851. * Deletes all the records in a table and resets the count of the auto-incrementing
  1852. * primary key, where applicable.
  1853. *
  1854. * @param mixed $table A string or model class representing the table to be truncated
  1855. * @return boolean SQL TRUNCATE TABLE statement, false if not applicable.
  1856. */
  1857. public function truncate($table) {
  1858. return $this->execute('TRUNCATE TABLE ' . $this->fullTableName($table));
  1859. }
  1860. /**
  1861. * Check if the server support nested transactions
  1862. *
  1863. * @return boolean
  1864. */
  1865. public function nestedTransactionSupported() {
  1866. return false;
  1867. }
  1868. /**
  1869. * Begin a transaction
  1870. *
  1871. * @return boolean True on success, false on fail
  1872. * (i.e. if the database/model does not support transactions,
  1873. * or a transaction has not started).
  1874. */
  1875. public function begin() {
  1876. if ($this->_transactionStarted) {
  1877. if ($this->nestedTransactionSupported()) {
  1878. return $this->_beginNested();
  1879. }
  1880. $this->_transactionNesting++;
  1881. return $this->_transactionStarted;
  1882. }
  1883. $this->_transactionNesting = 0;
  1884. if ($this->fullDebug) {
  1885. $this->logQuery('BEGIN');
  1886. }
  1887. return $this->_transactionStarted = $this->_connection->beginTransaction();
  1888. }
  1889. /**
  1890. * Begin a nested transaction
  1891. *
  1892. * @return boolean
  1893. */
  1894. protected function _beginNested() {
  1895. $query = 'SAVEPOINT LEVEL' . ++$this->_transactionNesting;
  1896. if ($this->fullDebug) {
  1897. $this->logQuery($query);
  1898. }
  1899. $this->_connection->exec($query);
  1900. return true;
  1901. }
  1902. /**
  1903. * Commit a transaction
  1904. *
  1905. * @return boolean True on success, false on fail
  1906. * (i.e. if the database/model does not support transactions,
  1907. * or a transaction has not started).
  1908. */
  1909. public function commit() {
  1910. if (!$this->_transactionStarted) {
  1911. return false;
  1912. }
  1913. if ($this->_transactionNesting === 0) {
  1914. if ($this->fullDebug) {
  1915. $this->logQuery('COMMIT');
  1916. }
  1917. $this->_transactionStarted = false;
  1918. return $this->_connection->commit();
  1919. }
  1920. if ($this->nestedTransactionSupported()) {
  1921. return $this->_commitNested();
  1922. }
  1923. $this->_transactionNesting--;
  1924. return true;
  1925. }
  1926. /**
  1927. * Commit a nested transaction
  1928. *
  1929. * @return boolean
  1930. */
  1931. protected function _commitNested() {
  1932. $query = 'RELEASE SAVEPOINT LEVEL' . $this->_transactionNesting--;
  1933. if ($this->fullDebug) {
  1934. $this->logQuery($query);
  1935. }
  1936. $this->_connection->exec($query);
  1937. return true;
  1938. }
  1939. /**
  1940. * Rollback a transaction
  1941. *
  1942. * @return boolean True on success, false on fail
  1943. * (i.e. if the database/model does not support transactions,
  1944. * or a transaction has not started).
  1945. */
  1946. public function rollback() {
  1947. if (!$this->_transactionStarted) {
  1948. return false;
  1949. }
  1950. if ($this->_transactionNesting === 0) {
  1951. if ($this->fullDebug) {
  1952. $this->logQuery('ROLLBACK');
  1953. }
  1954. $this->_transactionStarted = false;
  1955. return $this->_connection->rollBack();
  1956. }
  1957. if ($this->nestedTransactionSupported()) {
  1958. return $this->_rollbackNested();
  1959. }
  1960. $this->_transactionNesting--;
  1961. return true;
  1962. }
  1963. /**
  1964. * Rollback a nested transaction
  1965. *
  1966. * @return boolean
  1967. */
  1968. protected function _rollbackNested() {
  1969. $query = 'ROLLBACK TO SAVEPOINT LEVEL' . $this->_transactionNesting--;
  1970. if ($this->fullDebug) {
  1971. $this->logQuery($query);
  1972. }
  1973. $this->_connection->exec($query);
  1974. return true;
  1975. }
  1976. /**
  1977. * Returns the ID generated from the previous INSERT operation.
  1978. *
  1979. * @param mixed $source
  1980. * @return mixed
  1981. */
  1982. public function lastInsertId($source = null) {
  1983. return $this->_connection->lastInsertId();
  1984. }
  1985. /**
  1986. * Creates a default set of conditions from the model if $conditions is null/empty.
  1987. * If conditions are supplied then they will be returned. If a model doesn't exist and no conditions
  1988. * were provided either null or false will be returned based on what was input.
  1989. *
  1990. * @param Model $model
  1991. * @param mixed $conditions Array of conditions, conditions string, null or false. If an array of conditions,
  1992. * or string conditions those conditions will be returned. With other values the model's existence will be checked.
  1993. * If the model doesn't exist a null or false will be returned depending on the input value.
  1994. * @param boolean $useAlias Use model aliases rather than table names when generating conditions
  1995. * @return mixed Either null, false, $conditions or an array of default conditions to use.
  1996. * @see DboSource::update()
  1997. * @see DboSource::conditions()
  1998. */
  1999. public function defaultConditions(Model $model, $conditions, $useAlias = true) {
  2000. if (!empty($conditions)) {
  2001. return $conditions;
  2002. }
  2003. $exists = $model->exists();
  2004. if (!$exists && $conditions !== null) {
  2005. return false;
  2006. } elseif (!$exists) {
  2007. return null;
  2008. }
  2009. $alias = $model->alias;
  2010. if (!$useAlias) {
  2011. $alias = $this->fullTableName($model, false);
  2012. }
  2013. return array("{$alias}.{$model->primaryKey}" => $model->getID());
  2014. }
  2015. /**
  2016. * Returns a key formatted like a string Model.fieldname(i.e. Post.title, or Country.name)
  2017. *
  2018. * @param Model $model
  2019. * @param string $key
  2020. * @param string $assoc
  2021. * @return string
  2022. */
  2023. public function resolveKey(Model $model, $key, $assoc = null) {
  2024. if (strpos('.', $key) !== false) {
  2025. return $this->name($model->alias) . '.' . $this->name($key);
  2026. }
  2027. return $key;
  2028. }
  2029. /**
  2030. * Private helper method to remove query metadata in given data array.
  2031. *
  2032. * @param array $data
  2033. * @return array
  2034. */
  2035. protected function _scrubQueryData($data) {
  2036. static $base = null;
  2037. if ($base === null) {
  2038. $base = array_fill_keys(array('conditions', 'fields', 'joins', 'order', 'limit', 'offset', 'group'), array());
  2039. $base['callbacks'] = null;
  2040. }
  2041. return (array)$data + $base;
  2042. }
  2043. /**
  2044. * Converts model virtual fields into sql expressions to be fetched later
  2045. *
  2046. * @param Model $model
  2047. * @param string $alias Alias table name
  2048. * @param mixed $fields virtual fields to be used on query
  2049. * @return array
  2050. */
  2051. protected function _constructVirtualFields(Model $model, $alias, $fields) {
  2052. $virtual = array();
  2053. foreach ($fields as $field) {
  2054. $virtualField = $this->name($alias . $this->virtualFieldSeparator . $field);
  2055. $expression = $this->_quoteFields($model->getVir