PageRenderTime 46ms CodeModel.GetById 15ms RepoModel.GetById 1ms app.codeStats 0ms

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

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