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

/code/ryzom/tools/server/www/webtt/cake/libs/model/datasources/dbo_source.php

https://bitbucket.org/SirCotare/ryzom
PHP | 2925 lines | 2076 code | 209 blank | 640 comment | 491 complexity | 2d9fd69e908013b7fb9fc11cfd341864 MD5 | raw file
Possible License(s): AGPL-3.0, GPL-3.0, LGPL-2.1
  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-2010, 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-2010, 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 (strpos(trim(strtolower($sql)), 'select') !== false) {
  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. }
  681. for ($i = 0; $i < $count; $i++) {
  682. $fieldInsert[] = $this->name($fields[$i]);
  683. if ($fields[$i] == $model->primaryKey) {
  684. $id = $values[$i];
  685. }
  686. }
  687. $query = array(
  688. 'table' => $this->fullTableName($model),
  689. 'fields' => implode(', ', $fieldInsert),
  690. 'values' => implode(', ', $valueInsert)
  691. );
  692. if ($this->execute($this->renderStatement('create', $query))) {
  693. if (empty($id)) {
  694. $id = $this->lastInsertId($this->fullTableName($model, false), $model->primaryKey);
  695. }
  696. $model->setInsertID($id);
  697. $model->id = $id;
  698. return true;
  699. } else {
  700. $model->onError();
  701. return false;
  702. }
  703. }
  704. /**
  705. * The "R" in CRUD
  706. *
  707. * Reads record(s) from the database.
  708. *
  709. * @param Model $model A Model object that the query is for.
  710. * @param array $queryData An array of queryData information containing keys similar to Model::find()
  711. * @param integer $recursive Number of levels of association
  712. * @return mixed boolean false on error/failure. An array of results on success.
  713. */
  714. function read(&$model, $queryData = array(), $recursive = null) {
  715. $queryData = $this->__scrubQueryData($queryData);
  716. $null = null;
  717. $array = array();
  718. $linkedModels = array();
  719. $this->__bypass = false;
  720. $this->__booleans = array();
  721. if ($recursive === null && isset($queryData['recursive'])) {
  722. $recursive = $queryData['recursive'];
  723. }
  724. if (!is_null($recursive)) {
  725. $_recursive = $model->recursive;
  726. $model->recursive = $recursive;
  727. }
  728. if (!empty($queryData['fields'])) {
  729. $this->__bypass = true;
  730. $queryData['fields'] = $this->fields($model, null, $queryData['fields']);
  731. } else {
  732. $queryData['fields'] = $this->fields($model);
  733. }
  734. $_associations = $model->__associations;
  735. if ($model->recursive == -1) {
  736. $_associations = array();
  737. } else if ($model->recursive == 0) {
  738. unset($_associations[2], $_associations[3]);
  739. }
  740. foreach ($_associations as $type) {
  741. foreach ($model->{$type} as $assoc => $assocData) {
  742. $linkModel =& $model->{$assoc};
  743. $external = isset($assocData['external']);
  744. if ($model->useDbConfig == $linkModel->useDbConfig) {
  745. if (true === $this->generateAssociationQuery($model, $linkModel, $type, $assoc, $assocData, $queryData, $external, $null)) {
  746. $linkedModels[$type . '/' . $assoc] = true;
  747. }
  748. }
  749. }
  750. }
  751. $query = $this->generateAssociationQuery($model, $null, null, null, null, $queryData, false, $null);
  752. $resultSet = $this->fetchAll($query, $model->cacheQueries, $model->alias);
  753. if ($resultSet === false) {
  754. $model->onError();
  755. return false;
  756. }
  757. $filtered = $this->__filterResults($resultSet, $model);
  758. if ($model->recursive > -1) {
  759. foreach ($_associations as $type) {
  760. foreach ($model->{$type} as $assoc => $assocData) {
  761. $linkModel =& $model->{$assoc};
  762. if (empty($linkedModels[$type . '/' . $assoc])) {
  763. if ($model->useDbConfig == $linkModel->useDbConfig) {
  764. $db =& $this;
  765. } else {
  766. $db =& ConnectionManager::getDataSource($linkModel->useDbConfig);
  767. }
  768. } elseif ($model->recursive > 1 && ($type == 'belongsTo' || $type == 'hasOne')) {
  769. $db =& $this;
  770. }
  771. if (isset($db) && method_exists($db, 'queryAssociation')) {
  772. $stack = array($assoc);
  773. $db->queryAssociation($model, $linkModel, $type, $assoc, $assocData, $array, true, $resultSet, $model->recursive - 1, $stack);
  774. unset($db);
  775. if ($type === 'hasMany') {
  776. $filtered []= $assoc;
  777. }
  778. }
  779. }
  780. }
  781. $this->__filterResults($resultSet, $model, $filtered);
  782. }
  783. if (!is_null($recursive)) {
  784. $model->recursive = $_recursive;
  785. }
  786. return $resultSet;
  787. }
  788. /**
  789. * Passes association results thru afterFind filters of corresponding model
  790. *
  791. * @param array $results Reference of resultset to be filtered
  792. * @param object $model Instance of model to operate against
  793. * @param array $filtered List of classes already filtered, to be skipped
  794. * @return array Array of results that have been filtered through $model->afterFind
  795. * @access private
  796. */
  797. function __filterResults(&$results, &$model, $filtered = array()) {
  798. $filtering = array();
  799. $count = count($results);
  800. for ($i = 0; $i < $count; $i++) {
  801. if (is_array($results[$i])) {
  802. $classNames = array_keys($results[$i]);
  803. $count2 = count($classNames);
  804. for ($j = 0; $j < $count2; $j++) {
  805. $className = $classNames[$j];
  806. if ($model->alias != $className && !in_array($className, $filtered)) {
  807. if (!in_array($className, $filtering)) {
  808. $filtering[] = $className;
  809. }
  810. if (isset($model->{$className}) && is_object($model->{$className})) {
  811. $data = $model->{$className}->afterFind(array(array($className => $results[$i][$className])), false);
  812. }
  813. if (isset($data[0][$className])) {
  814. $results[$i][$className] = $data[0][$className];
  815. }
  816. }
  817. }
  818. }
  819. }
  820. return $filtering;
  821. }
  822. /**
  823. * Queries associations. Used to fetch results on recursive models.
  824. *
  825. * @param Model $model Primary Model object
  826. * @param Model $linkModel Linked model that
  827. * @param string $type Association type, one of the model association types ie. hasMany
  828. * @param unknown_type $association
  829. * @param unknown_type $assocData
  830. * @param array $queryData
  831. * @param boolean $external Whether or not the association query is on an external datasource.
  832. * @param array $resultSet Existing results
  833. * @param integer $recursive Number of levels of association
  834. * @param array $stack
  835. */
  836. function queryAssociation(&$model, &$linkModel, $type, $association, $assocData, &$queryData, $external = false, &$resultSet, $recursive, $stack) {
  837. if ($query = $this->generateAssociationQuery($model, $linkModel, $type, $association, $assocData, $queryData, $external, $resultSet)) {
  838. if (!isset($resultSet) || !is_array($resultSet)) {
  839. if (Configure::read() > 0) {
  840. echo '<div style = "font: Verdana bold 12px; color: #FF0000">' . sprintf(__('SQL Error in model %s:', true), $model->alias) . ' ';
  841. if (isset($this->error) && $this->error != null) {
  842. echo $this->error;
  843. }
  844. echo '</div>';
  845. }
  846. return null;
  847. }
  848. $count = count($resultSet);
  849. if ($type === 'hasMany' && empty($assocData['limit']) && !empty($assocData['foreignKey'])) {
  850. $ins = $fetch = array();
  851. for ($i = 0; $i < $count; $i++) {
  852. if ($in = $this->insertQueryData('{$__cakeID__$}', $resultSet[$i], $association, $assocData, $model, $linkModel, $stack)) {
  853. $ins[] = $in;
  854. }
  855. }
  856. if (!empty($ins)) {
  857. $ins = array_unique($ins);
  858. $fetch = $this->fetchAssociated($model, $query, $ins);
  859. }
  860. if (!empty($fetch) && is_array($fetch)) {
  861. if ($recursive > 0) {
  862. foreach ($linkModel->__associations as $type1) {
  863. foreach ($linkModel->{$type1} as $assoc1 => $assocData1) {
  864. $deepModel =& $linkModel->{$assoc1};
  865. $tmpStack = $stack;
  866. $tmpStack[] = $assoc1;
  867. if ($linkModel->useDbConfig === $deepModel->useDbConfig) {
  868. $db =& $this;
  869. } else {
  870. $db =& ConnectionManager::getDataSource($deepModel->useDbConfig);
  871. }
  872. $db->queryAssociation($linkModel, $deepModel, $type1, $assoc1, $assocData1, $queryData, true, $fetch, $recursive - 1, $tmpStack);
  873. }
  874. }
  875. }
  876. }
  877. $this->__filterResults($fetch, $model);
  878. return $this->__mergeHasMany($resultSet, $fetch, $association, $model, $linkModel, $recursive);
  879. } elseif ($type === 'hasAndBelongsToMany') {
  880. $ins = $fetch = array();
  881. for ($i = 0; $i < $count; $i++) {
  882. if ($in = $this->insertQueryData('{$__cakeID__$}', $resultSet[$i], $association, $assocData, $model, $linkModel, $stack)) {
  883. $ins[] = $in;
  884. }
  885. }
  886. if (!empty($ins)) {
  887. $ins = array_unique($ins);
  888. if (count($ins) > 1) {
  889. $query = str_replace('{$__cakeID__$}', '(' .implode(', ', $ins) .')', $query);
  890. $query = str_replace('= (', 'IN (', $query);
  891. } else {
  892. $query = str_replace('{$__cakeID__$}',$ins[0], $query);
  893. }
  894. $query = str_replace(' WHERE 1 = 1', '', $query);
  895. }
  896. $foreignKey = $model->hasAndBelongsToMany[$association]['foreignKey'];
  897. $joinKeys = array($foreignKey, $model->hasAndBelongsToMany[$association]['associationForeignKey']);
  898. list($with, $habtmFields) = $model->joinModel($model->hasAndBelongsToMany[$association]['with'], $joinKeys);
  899. $habtmFieldsCount = count($habtmFields);
  900. $q = $this->insertQueryData($query, null, $association, $assocData, $model, $linkModel, $stack);
  901. if ($q != false) {
  902. $fetch = $this->fetchAll($q, $model->cacheQueries, $model->alias);
  903. } else {
  904. $fetch = null;
  905. }
  906. }
  907. for ($i = 0; $i < $count; $i++) {
  908. $row =& $resultSet[$i];
  909. if ($type !== 'hasAndBelongsToMany') {
  910. $q = $this->insertQueryData($query, $resultSet[$i], $association, $assocData, $model, $linkModel, $stack);
  911. if ($q != false) {
  912. $fetch = $this->fetchAll($q, $model->cacheQueries, $model->alias);
  913. } else {
  914. $fetch = null;
  915. }
  916. }
  917. $selfJoin = false;
  918. if ($linkModel->name === $model->name) {
  919. $selfJoin = true;
  920. }
  921. if (!empty($fetch) && is_array($fetch)) {
  922. if ($recursive > 0) {
  923. foreach ($linkModel->__associations as $type1) {
  924. foreach ($linkModel->{$type1} as $assoc1 => $assocData1) {
  925. $deepModel =& $linkModel->{$assoc1};
  926. if (($type1 === 'belongsTo') || ($deepModel->alias === $model->alias && $type === 'belongsTo') || ($deepModel->alias != $model->alias)) {
  927. $tmpStack = $stack;
  928. $tmpStack[] = $assoc1;
  929. if ($linkModel->useDbConfig == $deepModel->useDbConfig) {
  930. $db =& $this;
  931. } else {
  932. $db =& ConnectionManager::getDataSource($deepModel->useDbConfig);
  933. }
  934. $db->queryAssociation($linkModel, $deepModel, $type1, $assoc1, $assocData1, $queryData, true, $fetch, $recursive - 1, $tmpStack);
  935. }
  936. }
  937. }
  938. }
  939. if ($type == 'hasAndBelongsToMany') {
  940. $uniqueIds = $merge = array();
  941. foreach ($fetch as $j => $data) {
  942. if (
  943. (isset($data[$with]) && $data[$with][$foreignKey] === $row[$model->alias][$model->primaryKey])
  944. ) {
  945. if ($habtmFieldsCount <= 2) {
  946. unset($data[$with]);
  947. }
  948. $merge[] = $data;
  949. }
  950. }
  951. if (empty($merge) && !isset($row[$association])) {
  952. $row[$association] = $merge;
  953. } else {
  954. $this->__mergeAssociation($resultSet[$i], $merge, $association, $type);
  955. }
  956. } else {
  957. $this->__mergeAssociation($resultSet[$i], $fetch, $association, $type, $selfJoin);
  958. }
  959. if (isset($resultSet[$i][$association])) {
  960. $resultSet[$i][$association] = $linkModel->afterFind($resultSet[$i][$association], false);
  961. }
  962. } else {
  963. $tempArray[0][$association] = false;
  964. $this->__mergeAssociation($resultSet[$i], $tempArray, $association, $type, $selfJoin);
  965. }
  966. }
  967. }
  968. }
  969. /**
  970. * A more efficient way to fetch associations. Woohoo!
  971. *
  972. * @param model $model Primary model object
  973. * @param string $query Association query
  974. * @param array $ids Array of IDs of associated records
  975. * @return array Association results
  976. * @access public
  977. */
  978. function fetchAssociated($model, $query, $ids) {
  979. $query = str_replace('{$__cakeID__$}', implode(', ', $ids), $query);
  980. if (count($ids) > 1) {
  981. $query = str_replace('= (', 'IN (', $query);
  982. }
  983. return $this->fetchAll($query, $model->cacheQueries, $model->alias);
  984. }
  985. /**
  986. * mergeHasMany - Merge the results of hasMany relations.
  987. *
  988. *
  989. * @param array $resultSet Data to merge into
  990. * @param array $merge Data to merge
  991. * @param string $association Name of Model being Merged
  992. * @param object $model Model being merged onto
  993. * @param object $linkModel Model being merged
  994. * @return void
  995. */
  996. function __mergeHasMany(&$resultSet, $merge, $association, &$model, &$linkModel) {
  997. foreach ($resultSet as $i => $value) {
  998. $count = 0;
  999. $merged[$association] = array();
  1000. foreach ($merge as $j => $data) {
  1001. if (isset($value[$model->alias]) && $value[$model->alias][$model->primaryKey] === $data[$association][$model->hasMany[$association]['foreignKey']]) {
  1002. if (count($data) > 1) {
  1003. $data = array_merge($data[$association], $data);
  1004. unset($data[$association]);
  1005. foreach ($data as $key => $name) {
  1006. if (is_numeric($key)) {
  1007. $data[$association][] = $name;
  1008. unset($data[$key]);
  1009. }
  1010. }
  1011. $merged[$association][] = $data;
  1012. } else {
  1013. $merged[$association][] = $data[$association];
  1014. }
  1015. }
  1016. $count++;
  1017. }
  1018. if (isset($value[$model->alias])) {
  1019. $resultSet[$i] = Set::pushDiff($resultSet[$i], $merged);
  1020. unset($merged);
  1021. }
  1022. }
  1023. }
  1024. /**
  1025. * Enter description here...
  1026. *
  1027. * @param unknown_type $data
  1028. * @param unknown_type $merge
  1029. * @param unknown_type $association
  1030. * @param unknown_type $type
  1031. * @param boolean $selfJoin
  1032. * @access private
  1033. */
  1034. function __mergeAssociation(&$data, $merge, $association, $type, $selfJoin = false) {
  1035. if (isset($merge[0]) && !isset($merge[0][$association])) {
  1036. $association = Inflector::pluralize($association);
  1037. }
  1038. if ($type == 'belongsTo' || $type == 'hasOne') {
  1039. if (isset($merge[$association])) {
  1040. $data[$association] = $merge[$association][0];
  1041. } else {
  1042. if (count($merge[0][$association]) > 1) {
  1043. foreach ($merge[0] as $assoc => $data2) {
  1044. if ($assoc != $association) {
  1045. $merge[0][$association][$assoc] = $data2;
  1046. }
  1047. }
  1048. }
  1049. if (!isset($data[$association])) {
  1050. if ($merge[0][$association] != null) {
  1051. $data[$association] = $merge[0][$association];
  1052. } else {
  1053. $data[$association] = array();
  1054. }
  1055. } else {
  1056. if (is_array($merge[0][$association])) {
  1057. foreach ($data[$association] as $k => $v) {
  1058. if (!is_array($v)) {
  1059. $dataAssocTmp[$k] = $v;
  1060. }
  1061. }
  1062. foreach ($merge[0][$association] as $k => $v) {
  1063. if (!is_array($v)) {
  1064. $mergeAssocTmp[$k] = $v;
  1065. }
  1066. }
  1067. $dataKeys = array_keys($data);
  1068. $mergeKeys = array_keys($merge[0]);
  1069. if ($mergeKeys[0] === $dataKeys[0] || $mergeKeys === $dataKeys) {
  1070. $data[$association][$association] = $merge[0][$association];
  1071. } else {
  1072. $diff = Set::diff($dataAssocTmp, $mergeAssocTmp);
  1073. $data[$association] = array_merge($merge[0][$association], $diff);
  1074. }
  1075. } elseif ($selfJoin && array_key_exists($association, $merge[0])) {
  1076. $data[$association] = array_merge($data[$association], array($association => array()));
  1077. }
  1078. }
  1079. }
  1080. } else {
  1081. if (isset($merge[0][$association]) && $merge[0][$association] === false) {
  1082. if (!isset($data[$association])) {
  1083. $data[$association] = array();
  1084. }
  1085. } else {
  1086. foreach ($merge as $i => $row) {
  1087. if (count($row) == 1) {
  1088. if (empty($data[$association]) || (isset($data[$association]) && !in_array($row[$association], $data[$association]))) {
  1089. $data[$association][] = $row[$association];
  1090. }
  1091. } else if (!empty($row)) {
  1092. $tmp = array_merge($row[$association], $row);
  1093. unset($tmp[$association]);
  1094. $data[$association][] = $tmp;
  1095. }
  1096. }
  1097. }
  1098. }
  1099. }
  1100. /**
  1101. * Generates an array representing a query or part of a query from a single model or two associated models
  1102. *
  1103. * @param Model $model
  1104. * @param Model $linkModel
  1105. * @param string $type
  1106. * @param string $association
  1107. * @param array $assocData
  1108. * @param array $queryData
  1109. * @param boolean $external
  1110. * @param array $resultSet
  1111. * @return mixed
  1112. * @access public
  1113. */
  1114. function generateAssociationQuery(&$model, &$linkModel, $type, $association = null, $assocData = array(), &$queryData, $external = false, &$resultSet) {
  1115. $queryData = $this->__scrubQueryData($queryData);
  1116. $assocData = $this->__scrubQueryData($assocData);
  1117. if (empty($queryData['fields'])) {
  1118. $queryData['fields'] = $this->fields($model, $model->alias);
  1119. } elseif (!empty($model->hasMany) && $model->recursive > -1) {
  1120. $assocFields = $this->fields($model, $model->alias, array("{$model->alias}.{$model->primaryKey}"));
  1121. $passedFields = $this->fields($model, $model->alias, $queryData['fields']);
  1122. if (count($passedFields) === 1) {
  1123. $match = strpos($passedFields[0], $assocFields[0]);
  1124. $match1 = (bool)preg_match('/^[a-z]+\(/i', $passedFields[0]);
  1125. if ($match === false && $match1 === false) {
  1126. $queryData['fields'] = array_merge($passedFields, $assocFields);
  1127. } else {
  1128. $queryData['fields'] = $passedFields;
  1129. }
  1130. } else {
  1131. $queryData['fields'] = array_merge($passedFields, $assocFields);
  1132. }
  1133. unset($assocFields, $passedFields);
  1134. }
  1135. if ($linkModel == null) {
  1136. return $this->buildStatement(
  1137. array(
  1138. 'fields' => array_unique($queryData['fields']),
  1139. 'table' => $this->fullTableName($model),
  1140. 'alias' => $model->alias,
  1141. 'limit' => $queryData['limit'],
  1142. 'offset' => $queryData['offset'],
  1143. 'joins' => $queryData['joins'],
  1144. 'conditions' => $queryData['conditions'],
  1145. 'order' => $queryData['order'],
  1146. 'group' => $queryData['group']
  1147. ),
  1148. $model
  1149. );
  1150. }
  1151. if ($external && !empty($assocData['finderQuery'])) {
  1152. return $assocData['finderQuery'];
  1153. }
  1154. $alias = $association;
  1155. $self = ($model->name == $linkModel->name);
  1156. $fields = array();
  1157. if ((!$external && in_array($type, array('hasOne', 'belongsTo')) && $this->__bypass === false) || $external) {
  1158. $fields = $this->fields($linkModel, $alias, $assocData['fields']);
  1159. }
  1160. if (empty($assocData['offset']) && !empty($assocData['page'])) {
  1161. $assocData['offset'] = ($assocData['page'] - 1) * $assocData['limit'];
  1162. }
  1163. $assocData['limit'] = $this->limit($assocData['limit'], $assocData['offset']);
  1164. switch ($type) {
  1165. case 'hasOne':
  1166. case 'belongsTo':
  1167. $conditions = $this->__mergeConditions(
  1168. $assocData['conditions'],
  1169. $this->getConstraint($type, $model, $linkModel, $alias, array_merge($assocData, compact('external', 'self')))
  1170. );
  1171. if (!$self && $external) {
  1172. foreach ($conditions as $key => $condition) {
  1173. if (is_numeric($key) && strpos($condition, $model->alias . '.') !== false) {
  1174. unset($conditions[$key]);
  1175. }
  1176. }
  1177. }
  1178. if ($external) {
  1179. $query = array_merge($assocData, array(
  1180. 'conditions' => $conditions,
  1181. 'table' => $this->fullTableName($linkModel),
  1182. 'fields' => $fields,
  1183. 'alias' => $alias,
  1184. 'group' => null
  1185. ));
  1186. $query = array_merge(array('order' => $assocData['order'], 'limit' => $assocData['limit']), $query);
  1187. } else {
  1188. $join = array(
  1189. 'table' => $this->fullTableName($linkModel),
  1190. 'alias' => $alias,
  1191. 'type' => isset($assocData['type']) ? $assocData['type'] : 'LEFT',
  1192. 'conditions' => trim($this->conditions($conditions, true, false, $model))
  1193. );
  1194. $queryData['fields'] = array_merge($queryData['fields'], $fields);
  1195. if (!empty($assocData['order'])) {
  1196. $queryData['order'][] = $assocData['order'];
  1197. }
  1198. if (!in_array($join, $queryData['joins'])) {
  1199. $queryData['joins'][] = $join;
  1200. }
  1201. return true;
  1202. }
  1203. break;
  1204. case 'hasMany':
  1205. $assocData['fields'] = $this->fields($linkModel, $alias, $assocData['fields']);
  1206. if (!empty($assocData['foreignKey'])) {
  1207. $assocData['fields'] = array_merge($assocData['fields'], $this->fields($linkModel, $alias, array("{$alias}.{$assocData['foreignKey']}")));
  1208. }
  1209. $query = array(
  1210. 'conditions' => $this->__mergeConditions($this->getConstraint('hasMany', $model, $linkModel, $alias, $assocData), $assocData['conditions']),
  1211. 'fields' => array_unique($assocData['fields']),
  1212. 'table' => $this->fullTableName($linkModel),
  1213. 'alias' => $alias,
  1214. 'order' => $assocData['order'],
  1215. 'limit' => $assocData['limit'],
  1216. 'group' => null
  1217. );
  1218. break;
  1219. case 'hasAndBelongsToMany':
  1220. $joinFields = array();
  1221. $joinAssoc = null;
  1222. if (isset($assocData['with']) && !empty($assocData['with'])) {
  1223. $joinKeys = array($assocData['foreignKey'], $assocData['associationForeignKey']);
  1224. list($with, $joinFields) = $model->joinModel($assocData['with'], $joinKeys);
  1225. $joinTbl = $this->fullTableName($model->{$with});
  1226. $joinAlias = $joinTbl;
  1227. if (is_array($joinFields) && !empty($joinFields)) {
  1228. $joinFields = $this->fields($model->{$with}, $model->{$with}->alias, $joinFields);
  1229. $joinAssoc = $joinAlias = $model->{$with}->alias;
  1230. } else {
  1231. $joinFields = array();
  1232. }
  1233. } else {
  1234. $joinTbl = $this->fullTableName($assocData['joinTable']);
  1235. $joinAlias = $joinTbl;
  1236. }
  1237. $query = array(
  1238. 'conditions' => $assocData['conditions'],
  1239. 'limit' => $assocData['limit'],
  1240. 'table' => $this->fullTableName($linkModel),
  1241. 'alias' => $alias,
  1242. 'fields' => array_merge($this->fields($linkModel, $alias, $assocData['fields']), $joinFields),
  1243. 'order' => $assocData['order'],
  1244. 'group' => null,
  1245. 'joins' => array(array(
  1246. 'table' => $joinTbl,
  1247. 'alias' => $joinAssoc,
  1248. 'conditions' => $this->getConstraint('hasAndBelongsToMany', $model, $linkModel, $joinAlias, $assocData, $alias)
  1249. ))
  1250. );
  1251. break;
  1252. }
  1253. if (isset($query)) {
  1254. return $this->buildStatement($query, $model);
  1255. }
  1256. return null;
  1257. }
  1258. /**
  1259. * Returns a conditions array for the constraint between two models
  1260. *
  1261. * @param string $type Association type
  1262. * @param object $model Model object
  1263. * @param array $association Association array
  1264. * @return array Conditions array defining the constraint between $model and $association
  1265. * @access public
  1266. */
  1267. function getConstraint($type, $model, $linkModel, $alias, $assoc, $alias2 = null) {
  1268. $assoc = array_merge(array('external' => false, 'self' => false), $assoc);
  1269. if (array_key_exists('foreignKey', $assoc) && empty($assoc['foreignKey'])) {
  1270. return array();
  1271. }
  1272. switch (true) {
  1273. case ($assoc['external'] && $type == 'hasOne'):
  1274. return array("{$alias}.{$assoc['foreignKey']}" => '{$__cakeID__$}');
  1275. break;
  1276. case ($assoc['external'] && $type == 'belongsTo'):
  1277. return array("{$alias}.{$linkModel->primaryKey}" => '{$__cakeForeignKey__$}');
  1278. break;
  1279. case (!$assoc['external'] && $type == 'hasOne'):
  1280. return array("{$alias}.{$assoc['foreignKey']}" => $this->identifier("{$model->alias}.{$model->primaryKey}"));
  1281. break;
  1282. case (!$assoc['external'] && $type == 'belongsTo'):
  1283. return array("{$model->alias}.{$assoc['foreignKey']}" => $this->identifier("{$alias}.{$linkModel->primaryKey}"));
  1284. break;
  1285. case ($type == 'hasMany'):
  1286. return array("{$alias}.{$assoc['foreignKey']}" => array('{$__cakeID__$}'));
  1287. break;
  1288. case ($type == 'hasAndBelongsToMany'):
  1289. return array(
  1290. array("{$alias}.{$assoc['foreignKey']}" => '{$__cakeID__$}'),
  1291. array("{$alias}.{$assoc['associationForeignKey']}" => $this->identifier("{$alias2}.{$linkModel->primaryKey}"))
  1292. );
  1293. break;
  1294. }
  1295. return array();
  1296. }
  1297. /**
  1298. * Builds and generates a JOIN statement from an array. Handles final clean-up before conversion.
  1299. *
  1300. * @param array $join An array defining a JOIN statement in a query
  1301. * @return string An SQL JOIN statement to be used in a query
  1302. * @access public
  1303. * @see DboSource::renderJoinStatement()
  1304. * @see DboSource::buildStatement()
  1305. */
  1306. function buildJoinStatement($join) {
  1307. $data = array_merge(array(
  1308. 'type' => null,
  1309. 'alias' => null,
  1310. 'table' => 'join_table',
  1311. 'conditions' => array()
  1312. ), $join);
  1313. if (!empty($data['alias'])) {
  1314. $data['alias'] = $this->alias . $this->name($data['alias']);
  1315. }
  1316. if (!empty($data['conditions'])) {
  1317. $data['conditions'] = trim($this->conditions($data['conditions'], true, false));
  1318. }
  1319. return $this->renderJoinStatement($data);
  1320. }
  1321. /**
  1322. * Builds and generates an SQL statement from an array. Handles final clean-up before conversion.
  1323. *
  1324. * @param array $query An array defining an SQL query
  1325. * @param object $model The model object which initiated the query
  1326. * @return string An executable SQL statement
  1327. * @access public
  1328. * @see DboSource::renderStatement()
  1329. */
  1330. function buildStatement($query, &$model) {
  1331. $query = array_merge(array('offset' => null, 'joins' => array()), $query);
  1332. if (!empty($query['joins'])) {
  1333. $count = count($query['joins']);
  1334. for ($i = 0; $i < $count; $i++) {
  1335. if (is_array($query['joins'][$i])) {
  1336. $query['joins'][$i] = $this->buildJoinStatement($query['joins'][$i]);
  1337. }
  1338. }
  1339. }
  1340. return $this->renderStatement('select', array(
  1341. 'conditions' => $this->conditions($query['conditions'], true, true, $model),
  1342. 'fields' => implode(', ', $query['fields']),
  1343. 'table' => $query['table'],
  1344. 'alias' => $this->alias . $this->name($query['alias']),
  1345. 'order' => $this->order($query['order'], 'ASC', $model),
  1346. 'limit' => $this->limit($query['limit'], $query['offset']),
  1347. 'joins' => implode(' ', $query['joins']),
  1348. 'group' => $this->group($query['group'], $model)
  1349. ));
  1350. }
  1351. /**
  1352. * Renders a final SQL JOIN statement
  1353. *
  1354. * @param array $data
  1355. * @return string
  1356. * @access public
  1357. */
  1358. function renderJoinStatement($data) {
  1359. extract($data);
  1360. return trim("{$type} JOIN {$table} {$alias} ON ({$conditions})");
  1361. }
  1362. /**
  1363. * Renders a final SQL statement by putting together the component parts in the correct order
  1364. *
  1365. * @param string $type type of query being run. e.g select, create, update, delete, schema, alter.
  1366. * @param array $data Array of data to insert into the query.
  1367. * @return string Rendered SQL expression to be run.
  1368. * @access public
  1369. */
  1370. function renderStatement($type, $data) {
  1371. extract($data);
  1372. $aliases = null;
  1373. switch (strtolower($type)) {
  1374. case 'select':
  1375. return "SELECT {$fields} FROM {$table} {$alias} {$joins} {$conditions} {$group} {$order} {$limit}";
  1376. break;
  1377. case 'create':
  1378. return "INSERT INTO {$table} ({$fields}) VALUES ({$values})";
  1379. break;
  1380. case 'update':
  1381. if (!empty($alias)) {
  1382. $aliases = "{$this->alias}{$alias} {$joins} ";
  1383. }
  1384. return "UPDATE {$table} {$aliases}SET {$fields} {$conditions}";
  1385. break;
  1386. case 'delete':
  1387. if (!empty($alias)) {
  1388. $aliases = "{$this->alias}{$alias} {$joins} ";
  1389. }
  1390. return "DELETE {$alias} FROM {$table} {$aliases}{$conditions}";
  1391. break;
  1392. case 'schema':
  1393. foreach (array('columns', 'indexes', 'tableParameters') as $var) {
  1394. if (is_array(${$var})) {
  1395. ${$var} = "\t" . join(",\n\t", array_filter(${$var}));
  1396. } else {
  1397. ${$var} = '';
  1398. }
  1399. }
  1400. if (trim($indexes) != '') {
  1401. $columns .= ',';
  1402. }
  1403. return "CREATE TABLE {$table} (\n{$columns}{$indexes}){$tableParameters};";
  1404. break;
  1405. case 'alter':
  1406. break;
  1407. }
  1408. }
  1409. /**
  1410. * Merges a mixed set of string/array conditions
  1411. *
  1412. * @return array
  1413. * @access private
  1414. */
  1415. function __mergeConditions($query, $assoc) {
  1416. if (empty($assoc)) {
  1417. return $query;
  1418. }
  1419. if (is_array($query)) {
  1420. return array_merge((array)$assoc, $query);
  1421. }
  1422. if (!empty($query)) {
  1423. $query = array($query);
  1424. if (is_array($assoc)) {
  1425. $query = array_merge($query, $assoc);
  1426. } else {
  1427. $query[] = $assoc;
  1428. }
  1429. return $query;
  1430. }
  1431. return $assoc;
  1432. }
  1433. /**
  1434. * Generates and executes an SQL UPDATE statement for given model, fields, and values.
  1435. * For databases that do not support aliases in UPDATE queries.
  1436. *
  1437. * @param Model $model
  1438. * @param array $fields
  1439. * @param array $values
  1440. * @param mixed $conditions
  1441. * @return boolean Success
  1442. * @access public
  1443. */
  1444. function update(&$model, $fields = array(), $values = null, $conditions = null) {
  1445. if ($values == null) {
  1446. $combined = $fields;
  1447. } else {
  1448. $combined = array_combine($fields, $values);
  1449. }
  1450. $fields = implode(', ', $this->_prepareUpdateFields($model, $combined, empty($conditions)));
  1451. $alias = $joins = null;
  1452. $table = $this->fullTableName($model);
  1453. $conditions = $this->_matchRecords($model, $conditions);
  1454. if ($conditions === false) {
  1455. return false;
  1456. }
  1457. $query = compact('table', 'alias', 'joins', 'fields', 'conditions');
  1458. if (!$this->execute($this->renderStatement('update', $query))) {
  1459. $model->onError();
  1460. return false;
  1461. }
  1462. return true;
  1463. }
  1464. /**
  1465. * Quotes and prepares fields and values for an SQL UPDATE statement
  1466. *
  1467. * @param Model $model
  1468. * @param array $fields
  1469. * @param boolean $quoteValues If values should be quoted, or treated as SQL snippets
  1470. * @param boolean $alias Include the model alias in the field name
  1471. * @return array Fields and values, quoted and preparted
  1472. * @access protected
  1473. */
  1474. function _prepareUpdateFields(&$model, $fields, $quoteValues = true, $alias = false) {
  1475. $quotedAlias = $this->startQuote . $model->alias . $this->endQuote;
  1476. $updates = array();
  1477. foreach ($fields as $field => $value) {
  1478. if ($alias && strpos($field, '.') === false) {
  1479. $quoted = $model->escapeField($field);
  1480. } elseif (!$alias && strpos($field, '.') !== false) {
  1481. $quoted = $this->name(str_replace($quotedAlias . '.', '', str_replace(
  1482. $model->alias . '.', '', $field
  1483. )));
  1484. } else {
  1485. $quoted = $this->name($field);
  1486. }
  1487. if ($value === null) {
  1488. $updates[] = $quoted . ' = NULL';
  1489. continue;
  1490. }
  1491. $update = $quoted . ' = ';
  1492. if ($quoteValues) {
  1493. $update .= $this->value($value, $model->getColumnType($field), false);
  1494. } elseif (!$alias) {
  1495. $update .= str_replace($quotedAlias . '.', '', str_replace(
  1496. $model->alias . '.', '', $value
  1497. ));
  1498. } else {
  1499. $update .= $value;
  1500. }
  1501. $updates[] = $update;
  1502. }
  1503. return $updates;
  1504. }
  1505. /**
  1506. * Generates and executes an SQL DELETE statement.
  1507. * For databases that do not support aliases in UPDATE queries.
  1508. *
  1509. * @param Model $model
  1510. * @param mixed $conditions
  1511. * @return boolean Success
  1512. * @access public
  1513. */
  1514. function delete(&$model, $conditions = null) {
  1515. $alias = $joins = null;
  1516. $table = $this->fullTableName($model);
  1517. $conditions = $this->_matchRecords($model, $conditions);
  1518. if ($conditions === false) {
  1519. return false;
  1520. }
  1521. if ($this->execute($this->renderStatement('delete', compact('alias', 'table', 'joins', 'conditions'))) === false) {
  1522. $model->onError();
  1523. return false;
  1524. }
  1525. return true;
  1526. }
  1527. /**
  1528. * Gets a list of record IDs for the given conditions. Used for multi-record updates and deletes
  1529. * in databases that do not support aliases in UPDATE/DELETE queries.
  1530. *
  1531. * @param Model $model
  1532. * @param mixed $conditions
  1533. * @return array List of record IDs
  1534. * @access protected
  1535. */
  1536. function _matchRecords(&$model, $conditions = null) {
  1537. if ($conditions === true) {
  1538. $conditions = $this->conditions(true);
  1539. } elseif ($conditions === null) {
  1540. $conditions = $this->conditions($this->defaultConditions($model, $conditions, false), true, true, $model);
  1541. } else {
  1542. $noJoin = true;
  1543. foreach ($conditions as $field => $value) {
  1544. $originalField = $field;
  1545. if (strpos($field, '.') !== false) {
  1546. list($alias, $field) = explode('.', $field);
  1547. $field = ltrim($field, $this->startQuote);
  1548. $field = rtrim($field, $this->endQuote);
  1549. }
  1550. if (!$model->hasField($field)) {
  1551. $noJoin = false;
  1552. break;
  1553. }
  1554. if ($field !== $originalField) {
  1555. $conditions[$field] = $value;
  1556. unset($conditions[$originalField]);
  1557. }
  1558. }
  1559. if ($noJoin === true) {
  1560. return $this->conditions($conditions);
  1561. }
  1562. $idList = $model->find('all', array(
  1563. 'fields' => "{$model->alias}.{$model->primaryKey}",
  1564. 'conditions' => $conditions
  1565. ));
  1566. if (empty($idList)) {
  1567. return false;
  1568. }
  1569. $conditions = $this->conditions(array(
  1570. $model->primaryKey => Set::extract($idList, "{n}.{$model->alias}.{$model->primaryKey}")
  1571. ));
  1572. }
  1573. return $conditions;
  1574. }
  1575. /**
  1576. * Returns an array of SQL JOIN fragments from a model's associations
  1577. *
  1578. * @param object $model
  1579. * @return array
  1580. * @access protected
  1581. */
  1582. function _getJoins($model) {
  1583. $join = array();
  1584. $joins = array_merge($model->getAssociated('hasOne'), $model->getAssociated('belongsTo'));
  1585. foreach ($joins as $assoc) {
  1586. if (isset($model->{$assoc}) && $model->useDbConfig == $model->{$assoc}->useDbConfig) {
  1587. $assocData = $model->getAssociated($assoc);
  1588. $join[] = $this->buildJoinStatement(array(
  1589. 'table' => $this->fullTableName($model->{$assoc}),
  1590. 'alias' => $assoc,
  1591. 'type' => isset($assocData['type']) ? $assocData['type'] : 'LEFT',
  1592. 'conditions' => trim($this->conditions(
  1593. $this->__mergeConditions($assocData['conditions'], $this->getConstraint($assocData['association'], $model, $model->{$assoc}, $assoc, $assocData)),
  1594. true, false, $model
  1595. ))
  1596. ));
  1597. }
  1598. }
  1599. return $join;
  1600. }
  1601. /**
  1602. * Returns an SQL calculation, i.e. COUNT() or MAX()
  1603. *
  1604. * @param model $model
  1605. * @param string $func Lowercase name of SQL function, i.e. 'count' or 'max'
  1606. * @param array $params Function parameters (any values must be quoted manually)
  1607. * @return string An SQL calculation function
  1608. * @access public
  1609. */
  1610. function calculate(&$model, $func, $params = array()) {
  1611. $params = (array)$params;
  1612. switch (strtolower($func)) {
  1613. case 'count':
  1614. if (!isset($params[0])) {
  1615. $params[0] = '*';
  1616. }
  1617. if (!isset($params[1])) {
  1618. $params[1] = 'count';
  1619. }
  1620. if (is_object($model) && $model->isVirtualField($params[0])){
  1621. $arg = $this->__quoteFields($model->getVirtualField($params[0]));
  1622. } else {
  1623. $arg = $this->name($params[0]);
  1624. }
  1625. return 'COUNT(' . $arg . ') AS ' . $this->name($params[1]);
  1626. case 'max':
  1627. case 'min':
  1628. if (!isset($params[1])) {
  1629. $params[1] = $params[0];
  1630. }
  1631. if (is_object($model) && $model->isVirtualField($params[0])) {
  1632. $arg = $this->__quoteFields($model->getVirtualField($params[0]));
  1633. } else {
  1634. $arg = $this->name($params[0]);
  1635. }
  1636. return strtoupper($func) . '(' . $arg . ') AS ' . $this->name($params[1]);
  1637. break;
  1638. }
  1639. }
  1640. /**
  1641. * Deletes all the records in a table and resets the count of the auto-incrementing
  1642. * primary key, where applicable.
  1643. *
  1644. * @param mixed $table A string or model class representing the table to be truncated
  1645. * @return boolean SQL TRUNCATE TABLE statement, false if not applicable.
  1646. * @access public
  1647. */
  1648. function truncate($table) {
  1649. return $this->execute('TRUNCATE TABLE ' . $this->fullTableName($table));
  1650. }
  1651. /**
  1652. * Begin a transaction
  1653. *
  1654. * @param model $model
  1655. * @return boolean True on success, false on fail
  1656. * (i.e. if the database/model does not support transactions,
  1657. * or a transaction has not started).
  1658. * @access public
  1659. */
  1660. function begin(&$model) {
  1661. if (parent::begin($model) && $this->execute($this->_commands['begin'])) {
  1662. $this->_transactionStarted = true;
  1663. return true;
  1664. }
  1665. return false;
  1666. }
  1667. /**
  1668. * Commit a transaction
  1669. *
  1670. * @param model $model
  1671. * @return boolean True on success, false on fail
  1672. * (i.e. if the database/model does not support transactions,
  1673. * or a transaction has not started).
  1674. * @access public
  1675. */
  1676. function commit(&$model) {
  1677. if (parent::commit($model) && $this->execute($this->_commands['commit'])) {
  1678. $this->_transactionStarted = false;
  1679. return true;
  1680. }
  1681. return false;
  1682. }
  1683. /**
  1684. * Rollback a transaction
  1685. *
  1686. * @param model $model
  1687. * @return boolean True on success, false on fail
  1688. * (i.e. if the database/model does not support transactions,
  1689. * or a transaction has not started).
  1690. * @access public
  1691. */
  1692. function rollback(&$model) {
  1693. if (parent::rollback($model) && $this->execute($this->_commands['rollback'])) {
  1694. $this->_transactionStarted = false;
  1695. return true;
  1696. }
  1697. return false;
  1698. }
  1699. /**
  1700. * Creates a default set of conditions from the model if $conditions is null/empty.
  1701. * If conditions are supplied then they will be returned. If a model doesn't exist and no conditions
  1702. * were provided either null or false will be returned based on what was input.
  1703. *
  1704. * @param object $model
  1705. * @param mixed $conditions Array of conditions, conditions string, null or false. If an array of conditions,
  1706. * or string conditions those conditions will be returned. With other values the model's existance will be checked.
  1707. * If the model doesn't exist a null or false will be returned depending on the input value.
  1708. * @param boolean $useAlias Use model aliases rather than table names when generating conditions
  1709. * @return mixed Either null, false, $conditions or an array of default conditions to use.
  1710. * @see DboSource::update()
  1711. * @see DboSource::conditions()
  1712. * @access public
  1713. */
  1714. function defaultConditions(&$model, $conditions, $useAlias = true) {
  1715. if (!empty($conditions)) {
  1716. return $conditions;
  1717. }
  1718. $exists = $model->exists();
  1719. if (!$exists && $conditions !== null) {
  1720. return false;
  1721. } elseif (!$exists) {
  1722. return null;
  1723. }
  1724. $alias = $model->alias;
  1725. if (!$useAlias) {
  1726. $alias = $this->fullTableName($model, false);
  1727. }
  1728. return array("{$alias}.{$model->primaryKey}" => $model->getID());
  1729. }
  1730. /**
  1731. * Returns a key formatted like a string Model.fieldname(i.e. Post.title, or Country.name)
  1732. *
  1733. * @param unknown_type $model
  1734. * @param unknown_type $key
  1735. * @param unknown_type $assoc
  1736. * @return string
  1737. * @access public
  1738. */
  1739. function resolveKey($model, $key, $assoc = null) {
  1740. if (empty($assoc)) {
  1741. $assoc = $model->alias;
  1742. }
  1743. if (!strpos('.', $key)) {
  1744. return $this->name($model->alias) . '.' . $this->name($key);
  1745. }
  1746. return $key;
  1747. }
  1748. /**
  1749. * Private helper method to remove query metadata in given data array.
  1750. *
  1751. * @param array $data
  1752. * @return array
  1753. * @access public
  1754. */
  1755. function __scrubQueryData($data) {
  1756. foreach (array('conditions', 'fields', 'joins', 'order', 'limit', 'offset', 'group') as $key) {
  1757. if (empty($data[$key])) {
  1758. $data[$key] = array();
  1759. }
  1760. }
  1761. return $data;
  1762. }
  1763. /**
  1764. * Converts model virtual fields into sql expressions to be fetched later
  1765. *
  1766. * @param Model $model
  1767. * @param string $alias Alias tablename
  1768. * @param mixed $fields virtual fields to be used on query
  1769. * @return array
  1770. */
  1771. function _constructVirtualFields(&$model, $alias, $fields) {
  1772. $virtual = array();
  1773. foreach ($fields as $field) {
  1774. $virtualField = $this->name($alias . $this->virtualFieldSeparator . $field);
  1775. $expression = $this->__quoteFields($model->getVirtualField($field));
  1776. $virtual[] = '(' . $expression . ") {$this->alias} {$virtualField}";
  1777. }
  1778. return $virtual;
  1779. }
  1780. /**
  1781. * Generates the fields list of an SQL query.
  1782. *
  1783. * @param Model $model
  1784. * @param string $alias Alias tablename
  1785. * @param mixed $fields
  1786. * @param boolean $quote If false, returns fields array unquoted
  1787. * @return array
  1788. * @access public
  1789. */
  1790. function fields(&$model, $alias = null, $fields = array(), $quote = true) {
  1791. if (empty($alias)) {
  1792. $alias = $model->alias;
  1793. }
  1794. $cacheKey = array(
  1795. $model->useDbConfig,
  1796. $model->table,
  1797. array_keys($model->schema()),
  1798. $model->name,
  1799. $model->getVirtualField(),
  1800. $alias,
  1801. $fields,
  1802. $quote
  1803. );
  1804. $cacheKey = crc32(serialize($cacheKey));
  1805. if ($return = $this->cacheMethod(__FUNCTION__, $cacheKey)) {
  1806. return $return;
  1807. }
  1808. $allFields = empty($fields);
  1809. if ($allFields) {
  1810. $fields = array_keys($model->schema());
  1811. } elseif (!is_array($fields)) {
  1812. $fields = String::tokenize($fields);
  1813. }
  1814. $fields = array_values(array_filter($fields));
  1815. $allFields = $allFields || in_array('*', $fields) || in_array($model->alias . '.*', $fields);
  1816. $virtual = array();
  1817. $virtualFields = $model->getVirtualField();
  1818. if (!empty($virtualFields)) {
  1819. $virtualKeys = array_keys($virtualFields);
  1820. foreach ($virtualKeys as $field) {
  1821. $virtualKeys[] = $model->alias . '.' . $field;
  1822. }
  1823. $virtual = ($allFields) ? $virtualKeys : array_intersect($virtualKeys, $fields);
  1824. foreach ($virtual as $i => $field) {
  1825. if (strpos($field, '.') !== false) {
  1826. $virtual[$i] = str_replace($model->alias . '.', '', $field);
  1827. }
  1828. $fields = array_diff($fields, array($field));
  1829. }
  1830. $fields = array_values($fields);
  1831. }
  1832. if (!$quote) {
  1833. if (!empty($virtual)) {
  1834. $fields = array_merge($fields, $this->_constructVirtualFields($model, $alias, $virtual));
  1835. }
  1836. return $fields;
  1837. }
  1838. $count = count($fields);
  1839. if ($count >= 1 && !in_array($fields[0], array('*', 'COUNT(*)'))) {
  1840. for ($i = 0; $i < $count; $i++) {
  1841. if (is_string($fields[$i]) && in_array($fields[$i], $virtual)) {
  1842. unset($fields[$i]);
  1843. continue;
  1844. }
  1845. if (is_object($fields[$i]) && isset($fields[$i]->type) && $fields[$i]->type === 'expression') {
  1846. $fields[$i] = $fields[$i]->value;
  1847. } elseif (preg_match('/^\(.*\)\s' . $this->alias . '.*/i', $fields[$i])){
  1848. continue;
  1849. } elseif (!preg_match('/^.+\\(.*\\)/', $fields[$i])) {
  1850. $prepend = '';
  1851. if (strpos($fields[$i], 'DISTINCT') !== false) {
  1852. $prepend = 'DISTINCT ';
  1853. $fields[$i] = trim(str_replace('DISTINCT', '', $fields[$i]));
  1854. }
  1855. $dot = strpos($fields[$i], '.');
  1856. if ($dot === false) {
  1857. $prefix = !(
  1858. strpos($fields[$i], ' ') !== false ||
  1859. strpos($fields[$i], '(') !== false
  1860. );
  1861. $fields[$i] = $this->name(($prefix ? $alias . '.' : '') . $fields[$i]);
  1862. } else {
  1863. $value = array();
  1864. $comma = strpos($fields[$i], ',');
  1865. if ($comma === false) {
  1866. $build = explode('.', $fields[$i]);
  1867. if (!Set::numeric($build)) {
  1868. $fields[$i] = $this->name(implode('.', $build));
  1869. }
  1870. }
  1871. }
  1872. $fields[$i] = $prepend . $fields[$i];
  1873. } elseif (preg_match('/\(([\.\w]+)\)/', $fields[$i], $field)) {
  1874. if (isset($field[1])) {
  1875. if (strpos($field[1], '.') === false) {
  1876. $field[1] = $this->name($alias . '.' . $field[1]);
  1877. } else {
  1878. $field[0] = explode('.', $field[1]);
  1879. if (!Set::numeric($field[0])) {
  1880. $field[0] = implode('.', array_map(array(&$this, 'name'), $field[0]));
  1881. $fields[$i] = preg_replace('/\(' . $field[1] . '\)/', '(' . $field[0] . ')', $fields[$i], 1);
  1882. }
  1883. }
  1884. }
  1885. }
  1886. }
  1887. }
  1888. if (!empty($virtual)) {
  1889. $fields = array_merge($fields, $this->_constructVirtualFields($model, $alias, $virtual));
  1890. }
  1891. return $this->cacheMethod(__FUNCTION__, $cacheKey, array_unique($fields));
  1892. }
  1893. /**
  1894. * Creates a WHERE clause by parsing given conditions data. If an array or string
  1895. * conditions are provided those conditions will be parsed and quoted. If a boolean
  1896. * is given it will be integer cast as condition. Null will return 1 = 1.
  1897. *
  1898. * Results of this method are stored in a memory cache. This improves performance, but
  1899. * because the method uses a simple hashing algorithm it can infrequently have collisions.
  1900. * Setting DboSource::$cacheMethods to false will disable the memory cache.
  1901. *
  1902. * @param mixed $conditions Array or string of conditions, or any value.
  1903. * @param boolean $quoteValues If true, values should be quoted
  1904. * @param boolean $where If true, "WHERE " will be prepended to the return value
  1905. * @param Model $model A reference to the Model instance making the query
  1906. * @return string SQL fragment
  1907. * @access public
  1908. */
  1909. function conditions($conditions, $quoteValues = true, $where = true, $model = null) {
  1910. if (is_object($model)) {
  1911. $cacheKey = array(
  1912. $model->useDbConfig,
  1913. $model->table,
  1914. $model->schema(),
  1915. $model->name,
  1916. $model->getVirtualField(),
  1917. $conditions,
  1918. $quoteValues,
  1919. $where
  1920. );
  1921. } else {
  1922. $cacheKey = array($conditions, $quoteValues, $where);
  1923. }
  1924. $cacheKey = crc32(serialize($cacheKey));
  1925. if ($return = $this->cacheMethod(__FUNCTION__, $cacheKey)) {
  1926. return $return;
  1927. }
  1928. $clause = $out = '';
  1929. if ($where) {
  1930. $clause = ' WHERE ';
  1931. }
  1932. if (is_array($conditions) && !empty($conditions)) {
  1933. $out = $this->conditionKeysToString($conditions, $quoteValues, $model);
  1934. if (empty($out)) {
  1935. return $this->cacheMethod(__FUNCTION__, $cacheKey, $clause . ' 1 = 1');
  1936. }
  1937. return $this->cacheMethod(__FUNCTION__, $cacheKey, $clause . implode(' AND ', $out));
  1938. }
  1939. if ($conditions === false || $conditions === true) {
  1940. return $this->cacheMethod(__FUNCTION__, $cacheKey, $clause . (int)$conditions . ' = 1');
  1941. }
  1942. if (empty($conditions) || trim($conditions) == '') {
  1943. return $this->cacheMethod(__FUNCTION__, $cacheKey, $clause . '1 = 1');
  1944. }
  1945. $clauses = '/^WHERE\\x20|^GROUP\\x20BY\\x20|^HAVING\\x20|^ORDER\\x20BY\\x20/i';
  1946. if (preg_match($clauses, $conditions, $match)) {
  1947. $clause = '';
  1948. }
  1949. if (trim($conditions) == '') {
  1950. $conditions = ' 1 = 1';
  1951. } else {
  1952. $conditions = $this->__quoteFields($conditions);
  1953. }
  1954. return $this->cacheMethod(__FUNCTION__, $cacheKey, $clause . $conditions);
  1955. }
  1956. /**
  1957. * Creates a WHERE clause by parsing given conditions array. Used by DboSource::conditions().
  1958. *
  1959. * @param array $conditions Array or string of conditions
  1960. * @param boolean $quoteValues If true, values should be quoted
  1961. * @param Model $model A reference to the Model instance making the query
  1962. * @return string SQL fragment
  1963. * @access public
  1964. */
  1965. function conditionKeysToString($conditions, $quoteValues = true, $model = null) {
  1966. $c = 0;
  1967. $out = array();
  1968. $data = $columnType = null;
  1969. $bool = array('and', 'or', 'not', 'and not', 'or not', 'xor', '||', '&&');
  1970. foreach ($conditions as $key => $value) {
  1971. $join = ' AND ';
  1972. $not = null;
  1973. if (is_array($value)) {
  1974. $valueInsert = (
  1975. !empty($value) &&
  1976. (substr_count($key, '?') == count($value) || substr_count($key, ':') == count($value))
  1977. );
  1978. }
  1979. if (is_numeric($key) && empty($value)) {
  1980. continue;
  1981. } elseif (is_numeric($key) && is_string($value)) {
  1982. $out[] = $not . $this->__quoteFields($value);
  1983. } elseif ((is_numeric($key) && is_array($value)) || in_array(strtolower(trim($key)), $bool)) {
  1984. if (in_array(strtolower(trim($key)), $bool)) {
  1985. $join = ' ' . strtoupper($key) . ' ';
  1986. } else {
  1987. $key = $join;
  1988. }
  1989. $value = $this->conditionKeysToString($value, $quoteValues, $model);
  1990. if (strpos($join, 'NOT') !== false) {
  1991. if (strtoupper(trim($key)) == 'NOT') {
  1992. $key = 'AND ' . trim($key);
  1993. }
  1994. $not = 'NOT ';
  1995. }
  1996. if (empty($value[1])) {
  1997. if ($not) {
  1998. $out[] = $not . '(' . $value[0] . ')';
  1999. } else {
  2000. $out[] = $value[0] ;
  2001. }
  2002. } else {
  2003. $out[] = '(' . $not . '(' . implode(') ' . strtoupper($key) . ' (', $value) . '))';
  2004. }
  2005. } else {
  2006. if (is_object($value) && isset($value->type)) {
  2007. if ($value->type == 'identifier') {
  2008. $data .= $this->name($key) . ' = ' . $this->name($value->value);
  2009. } elseif ($value->type == 'expression') {
  2010. if (is_numeric($key)) {
  2011. $data .= $value->value;
  2012. } else {
  2013. $data .= $this->name($key) . ' = ' . $value->value;
  2014. }
  2015. }
  2016. } elseif (is_array($value) && !empty($value) && !$valueInsert) {
  2017. $keys = array_keys($value);
  2018. if ($keys === array_values($keys)) {
  2019. $count = count($value);
  2020. if ($count === 1) {
  2021. $data = $this->__quoteFields($key) . ' = (';
  2022. } else {
  2023. $data = $this->__quoteFields($key) . ' IN (';
  2024. }
  2025. if ($quoteValues) {
  2026. if (is_object($model)) {
  2027. $columnType = $model->getColumnType($key);
  2028. }
  2029. $data .= implode(', ', $this->value($value, $columnType));
  2030. }
  2031. $data .= ')';
  2032. } else {
  2033. $ret = $this->conditionKeysToString($value, $quoteValues, $model);
  2034. if (count($ret) > 1) {
  2035. $data = '(' . implode(') AND (', $ret) . ')';
  2036. } elseif (isset($ret[0])) {
  2037. $data = $ret[0];
  2038. }
  2039. }
  2040. } elseif (is_numeric($key) && !empty($value)) {
  2041. $data = $this->__quoteFields($value);
  2042. } else {
  2043. $data = $this->__parseKey($model, trim($key), $value);
  2044. }
  2045. if ($data != null) {
  2046. $out[] = $data;
  2047. $data = null;
  2048. }
  2049. }
  2050. $c++;
  2051. }
  2052. return $out;
  2053. }
  2054. /**
  2055. * Extracts a Model.field identifier and an SQL condition operator from a string, formats
  2056. * and inserts values, and composes them into an SQL snippet.
  2057. *
  2058. * @param Model $model Model object initiating the query
  2059. * @param string $key An SQL key snippet containing a field and optional SQL operator
  2060. * @param mixed $value The value(s) to be inserted in the string
  2061. * @return string
  2062. * @access private
  2063. */
  2064. function __parseKey(&$model, $key, $value) {
  2065. $operatorMatch = '/^((' . implode(')|(', $this->__sqlOps);
  2066. $operatorMatch .= '\\x20)|<[>=]?(?![^>]+>)\\x20?|[>=!]{1,3}(?!<)\\x20?)/is';
  2067. $bound = (strpos($key, '?') !== false || (is_array($value) && strpos($key, ':') !== false));
  2068. if (!strpos($key, ' ')) {
  2069. $operator = '=';
  2070. } else {
  2071. list($key, $operator) = explode(' ', trim($key), 2);
  2072. if (!preg_match($operatorMatch, trim($operator)) && strpos($operator, ' ') !== false) {
  2073. $key = $key . ' ' . $operator;
  2074. $split = strrpos($key, ' ');
  2075. $operator = substr($key, $split);
  2076. $key = substr($key, 0, $split);
  2077. }
  2078. }
  2079. $virtual = false;
  2080. if (is_object($model) && $model->isVirtualField($key)) {
  2081. $key = $this->__quoteFields($model->getVirtualField($key));
  2082. $virtual = true;
  2083. }
  2084. $type = (is_object($model) ? $model->getColumnType($key) : null);
  2085. $null = ($value === null || (is_array($value) && empty($value)));
  2086. if (strtolower($operator) === 'not') {
  2087. $data = $this->conditionKeysToString(
  2088. array($operator => array($key => $value)), true, $model
  2089. );
  2090. return $data[0];
  2091. }
  2092. $value = $this->value($value, $type);
  2093. if (!$virtual && $key !== '?') {
  2094. $isKey = (strpos($key, '(') !== false || strpos($key, ')') !== false);
  2095. $key = $isKey ? $this->__quoteFields($key) : $this->name($key);
  2096. }
  2097. if ($bound) {
  2098. return String::insert($key . ' ' . trim($operator), $value);
  2099. }
  2100. if (!preg_match($operatorMatch, trim($operator))) {
  2101. $operator .= ' =';
  2102. }
  2103. $operator = trim($operator);
  2104. if (is_array($value)) {
  2105. $value = implode(', ', $value);
  2106. switch ($operator) {
  2107. case '=':
  2108. $operator = 'IN';
  2109. break;
  2110. case '!=':
  2111. case '<>':
  2112. $operator = 'NOT IN';
  2113. break;
  2114. }
  2115. $value = "({$value})";
  2116. } elseif ($null) {
  2117. switch ($operator) {
  2118. case '=':
  2119. $operator = 'IS';
  2120. break;
  2121. case '!=':
  2122. case '<>':
  2123. $operator = 'IS NOT';
  2124. break;
  2125. }
  2126. }
  2127. if ($virtual) {
  2128. return "({$key}) {$operator} {$value}";
  2129. }
  2130. return "{$key} {$operator} {$value}";
  2131. }
  2132. /**
  2133. * Quotes Model.fields
  2134. *
  2135. * @param string $conditions
  2136. * @return string or false if no match
  2137. * @access private
  2138. */
  2139. function __quoteFields($conditions) {
  2140. $start = $end = null;
  2141. $original = $conditions;
  2142. if (!empty($this->startQuote)) {
  2143. $start = preg_quote($this->startQuote);
  2144. }
  2145. if (!empty($this->endQuote)) {
  2146. $end = preg_quote($this->endQuote);
  2147. }
  2148. $conditions = str_replace(array($start, $end), '', $conditions);
  2149. $conditions = preg_replace_callback('/(?:[\'\"][^\'\"\\\]*(?:\\\.[^\'\"\\\]*)*[\'\"])|([a-z0-9_' . $start . $end . ']*\\.[a-z0-9_' . $start . $end . ']*)/i', array(&$this, '__quoteMatchedField'), $conditions);
  2150. if ($conditions !== null) {
  2151. return $conditions;
  2152. }
  2153. return $original;
  2154. }
  2155. /**
  2156. * Auxiliary function to quote matches `Model.fields` from a preg_replace_callback call
  2157. *
  2158. * @param string matched string
  2159. * @return string quoted strig
  2160. * @access private
  2161. */
  2162. function __quoteMatchedField($match) {
  2163. if (is_numeric($match[0])) {
  2164. return $match[0];
  2165. }
  2166. return $this->name($match[0]);
  2167. }
  2168. /**
  2169. * Returns a limit statement in the correct format for the particular database.
  2170. *
  2171. * @param integer $limit Limit of results returned
  2172. * @param integer $offset Offset from which to start results
  2173. * @return string SQL limit/offset statement
  2174. * @access public
  2175. */
  2176. function limit($limit, $offset = null) {
  2177. if ($limit) {
  2178. $rt = '';
  2179. if (!strpos(strtolower($limit), 'limit') || strpos(strtolower($limit), 'limit') === 0) {
  2180. $rt = ' LIMIT';
  2181. }
  2182. if ($offset) {
  2183. $rt .= ' ' . $offset . ',';
  2184. }
  2185. $rt .= ' ' . $limit;
  2186. return $rt;
  2187. }
  2188. return null;
  2189. }
  2190. /**
  2191. * Returns an ORDER BY clause as a string.
  2192. *
  2193. * @param string $key Field reference, as a key (i.e. Post.title)
  2194. * @param string $direction Direction (ASC or DESC)
  2195. * @param object $model model reference (used to look for virtual field)
  2196. * @return string ORDER BY clause
  2197. * @access public
  2198. */
  2199. function order($keys, $direction = 'ASC', $model = null) {
  2200. if (!is_array($keys)) {
  2201. $keys = array($keys);
  2202. }
  2203. $keys = array_filter($keys);
  2204. $result = array();
  2205. while (!empty($keys)) {
  2206. list($key, $dir) = each($keys);
  2207. array_shift($keys);
  2208. if (is_numeric($key)) {
  2209. $key = $dir;
  2210. $dir = $direction;
  2211. }
  2212. if (is_string($key) && strpos($key, ',') && !preg_match('/\(.+\,.+\)/', $key)) {
  2213. $key = array_map('trim', explode(',', $key));
  2214. }
  2215. if (is_array($key)) {
  2216. //Flatten the array
  2217. $key = array_reverse($key, true);
  2218. foreach ($key as $k => $v) {
  2219. if (is_numeric($k)) {
  2220. array_unshift($keys, $v);
  2221. } else {
  2222. $keys = array($k => $v) + $keys;
  2223. }
  2224. }
  2225. continue;
  2226. } elseif (is_object($key) && isset($key->type) && $key->type === 'expression') {
  2227. $result[] = $key->value;
  2228. continue;
  2229. }
  2230. if (preg_match('/\\x20(ASC|DESC).*/i', $key, $_dir)) {
  2231. $dir = $_dir[0];
  2232. $key = preg_replace('/\\x20(ASC|DESC).*/i', '', $key);
  2233. }
  2234. $key = trim($key);
  2235. if (is_object($model) && $model->isVirtualField($key)) {
  2236. $key = '(' . $this->__quoteFields($model->getVirtualField($key)) . ')';
  2237. }
  2238. if (strpos($key, '.')) {
  2239. $key = preg_replace_callback('/([a-zA-Z0-9_-]{1,})\\.([a-zA-Z0-9_-]{1,})/', array(&$this, '__quoteMatchedField'), $key);
  2240. }
  2241. if (!preg_match('/\s/', $key) && !strpos($key, '.')) {
  2242. $key = $this->name($key);
  2243. }
  2244. $key .= ' ' . trim($dir);
  2245. $result[] = $key;
  2246. }
  2247. if (!empty($result)) {
  2248. return ' ORDER BY ' . implode(', ', $result);
  2249. }
  2250. return '';
  2251. }
  2252. /**
  2253. * Create a GROUP BY SQL clause
  2254. *
  2255. * @param string $group Group By Condition
  2256. * @return mixed string condition or null
  2257. * @access public
  2258. */
  2259. function group($group, $model = null) {
  2260. if ($group) {
  2261. if (!is_array($group)) {
  2262. $group = array($group);
  2263. }
  2264. foreach($group as $index => $key) {
  2265. if (is_object($model) && $model->isVirtualField($key)) {
  2266. $group[$index] = '(' . $model->getVirtualField($key) . ')';
  2267. }
  2268. }
  2269. $group = implode(', ', $group);
  2270. return ' GROUP BY ' . $this->__quoteFields($group);
  2271. }
  2272. return null;
  2273. }
  2274. /**
  2275. * Disconnects database, kills the connection and says the connection is closed.
  2276. *
  2277. * @return void
  2278. * @access public
  2279. */
  2280. function close() {
  2281. $this->disconnect();
  2282. }
  2283. /**
  2284. * Checks if the specified table contains any record matching specified SQL
  2285. *
  2286. * @param Model $model Model to search
  2287. * @param string $sql SQL WHERE clause (condition only, not the "WHERE" part)
  2288. * @return boolean True if the table has a matching record, else false
  2289. * @access public
  2290. */
  2291. function hasAny(&$Model, $sql) {
  2292. $sql = $this->conditions($sql);
  2293. $table = $this->fullTableName($Model);
  2294. $alias = $this->alias . $this->name($Model->alias);
  2295. $where = $sql ? "{$sql}" : ' WHERE 1 = 1';
  2296. $id = $Model->escapeField();
  2297. $out = $this->fetchRow("SELECT COUNT({$id}) {$this->alias}count FROM {$table} {$alias}{$where}");
  2298. if (is_array($out)) {
  2299. return $out[0]['count'];
  2300. }
  2301. return false;
  2302. }
  2303. /**
  2304. * Gets the length of a database-native column description, or null if no length
  2305. *
  2306. * @param string $real Real database-layer column type (i.e. "varchar(255)")
  2307. * @return mixed An integer or string representing the length of the column
  2308. * @access public
  2309. */
  2310. function length($real) {
  2311. if (!preg_match_all('/([\w\s]+)(?:\((\d+)(?:,(\d+))?\))?(\sunsigned)?(\szerofill)?/', $real, $result)) {
  2312. trigger_error(__("FIXME: Can't parse field: " . $real, true), E_USER_WARNING);
  2313. $col = str_replace(array(')', 'unsigned'), '', $real);
  2314. $limit = null;
  2315. if (strpos($col, '(') !== false) {
  2316. list($col, $limit) = explode('(', $col);
  2317. }
  2318. if ($limit != null) {
  2319. return intval($limit);
  2320. }
  2321. return null;
  2322. }
  2323. $types = array(
  2324. 'int' => 1, 'tinyint' => 1, 'smallint' => 1, 'mediumint' => 1, 'integer' => 1, 'bigint' => 1
  2325. );
  2326. list($real, $type, $length, $offset, $sign, $zerofill) = $result;
  2327. $typeArr = $type;
  2328. $type = $type[0];
  2329. $length = $length[0];
  2330. $offset = $offset[0];
  2331. $isFloat = in_array($type, array('dec', 'decimal', 'float', 'numeric', 'double'));
  2332. if ($isFloat && $offset) {
  2333. return $length.','.$offset;
  2334. }
  2335. if (($real[0] == $type) && (count($real) == 1)) {
  2336. return null;
  2337. }
  2338. if (isset($types[$type])) {
  2339. $length += $types[$type];
  2340. if (!empty($sign)) {
  2341. $length--;
  2342. }
  2343. } elseif (in_array($type, array('enum', 'set'))) {
  2344. $length = 0;
  2345. foreach ($typeArr as $key => $enumValue) {
  2346. if ($key == 0) {
  2347. continue;
  2348. }
  2349. $tmpLength = strlen($enumValue);
  2350. if ($tmpLength > $length) {
  2351. $length = $tmpLength;
  2352. }
  2353. }
  2354. }
  2355. return intval($length);
  2356. }
  2357. /**
  2358. * Translates between PHP boolean values and Database (faked) boolean values
  2359. *
  2360. * @param mixed $data Value to be translated
  2361. * @return mixed Converted boolean value
  2362. * @access public
  2363. */
  2364. function boolean($data) {
  2365. if ($data === true || $data === false) {
  2366. if ($data === true) {
  2367. return 1;
  2368. }
  2369. return 0;
  2370. } else {
  2371. return !empty($data);
  2372. }
  2373. }
  2374. /**
  2375. * Inserts multiple values into a table
  2376. *
  2377. * @param string $table
  2378. * @param string $fields
  2379. * @param array $values
  2380. * @access protected
  2381. */
  2382. function insertMulti($table, $fields, $values) {
  2383. $table = $this->fullTableName($table);
  2384. if (is_array($fields)) {
  2385. $fields = implode(', ', array_map(array(&$this, 'name'), $fields));
  2386. }
  2387. $count = count($values);
  2388. for ($x = 0; $x < $count; $x++) {
  2389. $this->query("INSERT INTO {$table} ({$fields}) VALUES {$values[$x]}");
  2390. }
  2391. }
  2392. /**
  2393. * Returns an array of the indexes in given datasource name.
  2394. *
  2395. * @param string $model Name of model to inspect
  2396. * @return array Fields in table. Keys are column and unique
  2397. * @access public
  2398. */
  2399. function index($model) {
  2400. return false;
  2401. }
  2402. /**
  2403. * Generate a database-native schema for the given Schema object
  2404. *
  2405. * @param object $schema An instance of a subclass of CakeSchema
  2406. * @param string $tableName Optional. If specified only the table name given will be generated.
  2407. * Otherwise, all tables defined in the schema are generated.
  2408. * @return string
  2409. * @access public
  2410. */
  2411. function createSchema($schema, $tableName = null) {
  2412. if (!is_a($schema, 'CakeSchema')) {
  2413. trigger_error(__('Invalid schema object', true), E_USER_WARNING);
  2414. return null;
  2415. }
  2416. $out = '';
  2417. foreach ($schema->tables as $curTable => $columns) {
  2418. if (!$tableName || $tableName == $curTable) {
  2419. $cols = $colList = $indexes = $tableParameters = array();
  2420. $primary = null;
  2421. $table = $this->fullTableName($curTable);
  2422. foreach ($columns as $name => $col) {
  2423. if (is_string($col)) {
  2424. $col = array('type' => $col);
  2425. }
  2426. if (isset($col['key']) && $col['key'] == 'primary') {
  2427. $primary = $name;
  2428. }
  2429. if ($name !== 'indexes' && $name !== 'tableParameters') {
  2430. $col['name'] = $name;
  2431. if (!isset($col['type'])) {
  2432. $col['type'] = 'string';
  2433. }
  2434. $cols[] = $this->buildColumn($col);
  2435. } elseif ($name == 'indexes') {
  2436. $indexes = array_merge($indexes, $this->buildIndex($col, $table));
  2437. } elseif ($name == 'tableParameters') {
  2438. $tableParameters = array_merge($tableParameters, $this->buildTableParameters($col, $table));
  2439. }
  2440. }
  2441. if (empty($indexes) && !empty($primary)) {
  2442. $col = array('PRIMARY' => array('column' => $primary, 'unique' => 1));
  2443. $indexes = array_merge($indexes, $this->buildIndex($col, $table));
  2444. }
  2445. $columns = $cols;
  2446. $out .= $this->renderStatement('schema', compact('table', 'columns', 'indexes', 'tableParameters')) . "\n\n";
  2447. }
  2448. }
  2449. return $out;
  2450. }
  2451. /**
  2452. * Generate a alter syntax from CakeSchema::compare()
  2453. *
  2454. * @param unknown_type $schema
  2455. * @return boolean
  2456. */
  2457. function alterSchema($compare, $table = null) {
  2458. return false;
  2459. }
  2460. /**
  2461. * Generate a "drop table" statement for the given Schema object
  2462. *
  2463. * @param object $schema An instance of a subclass of CakeSchema
  2464. * @param string $table Optional. If specified only the table name given will be generated.
  2465. * Otherwise, all tables defined in the schema are generated.
  2466. * @return string
  2467. * @access public
  2468. */
  2469. function dropSchema($schema, $table = null) {
  2470. if (!is_a($schema, 'CakeSchema')) {
  2471. trigger_error(__('Invalid schema object', true), E_USER_WARNING);
  2472. return null;
  2473. }
  2474. $out = '';
  2475. foreach ($schema->tables as $curTable => $columns) {
  2476. if (!$table || $table == $curTable) {
  2477. $out .= 'DROP TABLE ' . $this->fullTableName($curTable) . ";\n";
  2478. }
  2479. }
  2480. return $out;
  2481. }
  2482. /**
  2483. * Generate a database-native column schema string
  2484. *
  2485. * @param array $column An array structured like the following: array('name'=>'value', 'type'=>'value'[, options]),
  2486. * where options can be 'default', 'length', or 'key'.
  2487. * @return string
  2488. * @access public
  2489. */
  2490. function buildColumn($column) {
  2491. $name = $type = null;
  2492. extract(array_merge(array('null' => true), $column));
  2493. if (empty($name) || empty($type)) {
  2494. trigger_error(__('Column name or type not defined in schema', true), E_USER_WARNING);
  2495. return null;
  2496. }
  2497. if (!isset($this->columns[$type])) {
  2498. trigger_error(sprintf(__('Column type %s does not exist', true), $type), E_USER_WARNING);
  2499. return null;
  2500. }
  2501. $real = $this->columns[$type];
  2502. $out = $this->name($name) . ' ' . $real['name'];
  2503. if (isset($real['limit']) || isset($real['length']) || isset($column['limit']) || isset($column['length'])) {
  2504. if (isset($column['length'])) {
  2505. $length = $column['length'];
  2506. } elseif (isset($column['limit'])) {
  2507. $length = $column['limit'];
  2508. } elseif (isset($real['length'])) {
  2509. $length = $real['length'];
  2510. } else {
  2511. $length = $real['limit'];
  2512. }
  2513. $out .= '(' . $length . ')';
  2514. }
  2515. if (($column['type'] == 'integer' || $column['type'] == 'float' ) && isset($column['default']) && $column['default'] === '') {
  2516. $column['default'] = null;
  2517. }
  2518. $out = $this->_buildFieldParameters($out, $column, 'beforeDefault');
  2519. if (isset($column['key']) && $column['key'] == 'primary' && $type == 'integer') {
  2520. $out .= ' ' . $this->columns['primary_key']['name'];
  2521. } elseif (isset($column['key']) && $column['key'] == 'primary') {
  2522. $out .= ' NOT NULL';
  2523. } elseif (isset($column['default']) && isset($column['null']) && $column['null'] == false) {
  2524. $out .= ' DEFAULT ' . $this->value($column['default'], $type) . ' NOT NULL';
  2525. } elseif (isset($column['default'])) {
  2526. $out .= ' DEFAULT ' . $this->value($column['default'], $type);
  2527. } elseif ($type !== 'timestamp' && !empty($column['null'])) {
  2528. $out .= ' DEFAULT NULL';
  2529. } elseif ($type === 'timestamp' && !empty($column['null'])) {
  2530. $out .= ' NULL';
  2531. } elseif (isset($column['null']) && $column['null'] == false) {
  2532. $out .= ' NOT NULL';
  2533. }
  2534. if ($type == 'timestamp' && isset($column['default']) && strtolower($column['default']) == 'current_timestamp') {
  2535. $out = str_replace(array("'CURRENT_TIMESTAMP'", "'current_timestamp'"), 'CURRENT_TIMESTAMP', $out);
  2536. }
  2537. $out = $this->_buildFieldParameters($out, $column, 'afterDefault');
  2538. return $out;
  2539. }
  2540. /**
  2541. * Build the field parameters, in a position
  2542. *
  2543. * @param string $columnString The partially built column string
  2544. * @param array $columnData The array of column data.
  2545. * @param string $position The position type to use. 'beforeDefault' or 'afterDefault' are common
  2546. * @return string a built column with the field parameters added.
  2547. * @access public
  2548. */
  2549. function _buildFieldParameters($columnString, $columnData, $position) {
  2550. foreach ($this->fieldParameters as $paramName => $value) {
  2551. if (isset($columnData[$paramName]) && $value['position'] == $position) {
  2552. if (isset($value['options']) && !in_array($columnData[$paramName], $value['options'])) {
  2553. continue;
  2554. }
  2555. $val = $columnData[$paramName];
  2556. if ($value['quote']) {
  2557. $val = $this->value($val);
  2558. }
  2559. $columnString .= ' ' . $value['value'] . $value['join'] . $val;
  2560. }
  2561. }
  2562. return $columnString;
  2563. }
  2564. /**
  2565. * Format indexes for create table
  2566. *
  2567. * @param array $indexes
  2568. * @param string $table
  2569. * @return array
  2570. * @access public
  2571. */
  2572. function buildIndex($indexes, $table = null) {
  2573. $join = array();
  2574. foreach ($indexes as $name => $value) {
  2575. $out = '';
  2576. if ($name == 'PRIMARY') {
  2577. $out .= 'PRIMARY ';
  2578. $name = null;
  2579. } else {
  2580. if (!empty($value['unique'])) {
  2581. $out .= 'UNIQUE ';
  2582. }
  2583. $name = $this->startQuote . $name . $this->endQuote;
  2584. }
  2585. if (is_array($value['column'])) {
  2586. $out .= 'KEY ' . $name . ' (' . implode(', ', array_map(array(&$this, 'name'), $value['column'])) . ')';
  2587. } else {
  2588. $out .= 'KEY ' . $name . ' (' . $this->name($value['column']) . ')';
  2589. }
  2590. $join[] = $out;
  2591. }
  2592. return $join;
  2593. }
  2594. /**
  2595. * Read additional table parameters
  2596. *
  2597. * @param array $parameters
  2598. * @param string $table
  2599. * @return array
  2600. * @access public
  2601. */
  2602. function readTableParameters($name) {
  2603. $parameters = array();
  2604. if ($this->isInterfaceSupported('listDetailedSources')) {
  2605. $currentTableDetails = $this->listDetailedSources($name);
  2606. foreach ($this->tableParameters as $paramName => $parameter) {
  2607. if (!empty($parameter['column']) && !empty($currentTableDetails[$parameter['column']])) {
  2608. $parameters[$paramName] = $currentTableDetails[$parameter['column']];
  2609. }
  2610. }
  2611. }
  2612. return $parameters;
  2613. }
  2614. /**
  2615. * Format parameters for create table
  2616. *
  2617. * @param array $parameters
  2618. * @param string $table
  2619. * @return array
  2620. * @access public
  2621. */
  2622. function buildTableParameters($parameters, $table = null) {
  2623. $result = array();
  2624. foreach ($parameters as $name => $value) {
  2625. if (isset($this->tableParameters[$name])) {
  2626. if ($this->tableParameters[$name]['quote']) {
  2627. $value = $this->value($value);
  2628. }
  2629. $result[] = $this->tableParameters[$name]['value'] . $this->tableParameters[$name]['join'] . $value;
  2630. }
  2631. }
  2632. return $result;
  2633. }
  2634. /**
  2635. * Guesses the data type of an array
  2636. *
  2637. * @param string $value
  2638. * @return void
  2639. * @access public
  2640. */
  2641. function introspectType($value) {
  2642. if (!is_array($value)) {
  2643. if ($value === true || $value === false) {
  2644. return 'boolean';
  2645. }
  2646. if (is_float($value) && floatval($value) === $value) {
  2647. return 'float';
  2648. }
  2649. if (is_int($value) && intval($value) === $value) {
  2650. return 'integer';
  2651. }
  2652. if (is_string($value) && strlen($value) > 255) {
  2653. return 'text';
  2654. }
  2655. return 'string';
  2656. }
  2657. $isAllFloat = $isAllInt = true;
  2658. $containsFloat = $containsInt = $containsString = false;
  2659. foreach ($value as $key => $valElement) {
  2660. $valElement = trim($valElement);
  2661. if (!is_float($valElement) && !preg_match('/^[\d]+\.[\d]+$/', $valElement)) {
  2662. $isAllFloat = false;
  2663. } else {
  2664. $containsFloat = true;
  2665. continue;
  2666. }
  2667. if (!is_int($valElement) && !preg_match('/^[\d]+$/', $valElement)) {
  2668. $isAllInt = false;
  2669. } else {
  2670. $containsInt = true;
  2671. continue;
  2672. }
  2673. $containsString = true;
  2674. }
  2675. if ($isAllFloat) {
  2676. return 'float';
  2677. }
  2678. if ($isAllInt) {
  2679. return 'integer';
  2680. }
  2681. if ($containsInt && !$containsString) {
  2682. return 'integer';
  2683. }
  2684. return 'string';
  2685. }
  2686. }