PageRenderTime 38ms CodeModel.GetById 1ms RepoModel.GetById 0ms app.codeStats 0ms

/cake/libs/model/datasources/dbo_source.php

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