PageRenderTime 70ms CodeModel.GetById 20ms RepoModel.GetById 0ms app.codeStats 1ms

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

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