PageRenderTime 45ms CodeModel.GetById 17ms RepoModel.GetById 0ms app.codeStats 0ms

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

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