PageRenderTime 34ms CodeModel.GetById 21ms RepoModel.GetById 0ms app.codeStats 1ms

/baser/models/datasources/dbo_source.php

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