PageRenderTime 66ms CodeModel.GetById 17ms RepoModel.GetById 1ms app.codeStats 0ms

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

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