PageRenderTime 41ms CodeModel.GetById 25ms RepoModel.GetById 1ms app.codeStats 0ms

/Vendor/pear-pear.cakephp.org/CakePHP/Cake/Model/Datasource/DboSource.php

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