PageRenderTime 57ms CodeModel.GetById 11ms RepoModel.GetById 0ms app.codeStats 1ms

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

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