PageRenderTime 50ms CodeModel.GetById 15ms RepoModel.GetById 0ms app.codeStats 0ms

/lib/Cake/Model/CakeSchema.php

https://github.com/Bancha/cakephp
PHP | 687 lines | 461 code | 66 blank | 160 comment | 132 complexity | e7ee2fce9e5531d7227a3becea34d523 MD5 | raw file
  1. <?php
  2. /**
  3. * Schema database management for CakePHP.
  4. *
  5. * PHP 5
  6. *
  7. * CakePHP(tm) : Rapid Development Framework (http://cakephp.org)
  8. * Copyright 2005-2010, Cake Software Foundation, Inc. (http://cakefoundation.org)
  9. *
  10. * Licensed under The MIT License
  11. * Redistributions of files must retain the above copyright notice.
  12. *
  13. * @copyright Copyright 2005-2010, Cake Software Foundation, Inc. (http://cakefoundation.org)
  14. * @link http://cakephp.org CakePHP(tm) Project
  15. * @package cake.libs.model
  16. * @since CakePHP(tm) v 1.2.0.5550
  17. * @license MIT License (http://www.opensource.org/licenses/mit-license.php)
  18. */
  19. App::uses('Model', 'Model');
  20. App::uses('AppModel', 'Model');
  21. App::uses('ConnectionManager', 'Model');
  22. /**
  23. * Base Class for Schema management
  24. *
  25. * @package cake.libs.model
  26. */
  27. class CakeSchema extends Object {
  28. /**
  29. * Name of the schema
  30. *
  31. * @var string
  32. * @access public
  33. */
  34. public $name = null;
  35. /**
  36. * Path to write location
  37. *
  38. * @var string
  39. * @access public
  40. */
  41. public $path = null;
  42. /**
  43. * File to write
  44. *
  45. * @var string
  46. * @access public
  47. */
  48. public $file = 'schema.php';
  49. /**
  50. * Connection used for read
  51. *
  52. * @var string
  53. * @access public
  54. */
  55. public $connection = 'default';
  56. /**
  57. * plugin name.
  58. *
  59. * @var string
  60. */
  61. public $plugin = null;
  62. /**
  63. * Set of tables
  64. *
  65. * @var array
  66. * @access public
  67. */
  68. public $tables = array();
  69. /**
  70. * Constructor
  71. *
  72. * @param array $options optional load object properties
  73. */
  74. function __construct($options = array()) {
  75. parent::__construct();
  76. if (empty($options['name'])) {
  77. $this->name = preg_replace('/schema$/i', '', get_class($this));
  78. }
  79. if (!empty($options['plugin'])) {
  80. $this->plugin = $options['plugin'];
  81. }
  82. if (strtolower($this->name) === 'cake') {
  83. $this->name = Inflector::camelize(Inflector::slug(Configure::read('App.dir')));
  84. }
  85. if (empty($options['path'])) {
  86. $this->path = APP . 'Config' . DS . 'Schema';
  87. }
  88. $options = array_merge(get_object_vars($this), $options);
  89. $this->build($options);
  90. }
  91. /**
  92. * Builds schema object properties
  93. *
  94. * @param array $data loaded object properties
  95. * @return void
  96. */
  97. public function build($data) {
  98. $file = null;
  99. foreach ($data as $key => $val) {
  100. if (!empty($val)) {
  101. if (!in_array($key, array('plugin', 'name', 'path', 'file', 'connection', 'tables', '_log'))) {
  102. if ($key[0] === '_') {
  103. continue;
  104. }
  105. $this->tables[$key] = $val;
  106. unset($this->{$key});
  107. } elseif ($key !== 'tables') {
  108. if ($key === 'name' && $val !== $this->name && !isset($data['file'])) {
  109. $file = Inflector::underscore($val) . '.php';
  110. }
  111. $this->{$key} = $val;
  112. }
  113. }
  114. }
  115. if (file_exists($this->path . DS . $file) && is_file($this->path . DS . $file)) {
  116. $this->file = $file;
  117. } elseif (!empty($this->plugin)) {
  118. $this->path = CakePlugin::path($this->plugin) . 'Config' . DS . 'Schema';
  119. }
  120. }
  121. /**
  122. * Before callback to be implemented in subclasses
  123. *
  124. * @param array $events schema object properties
  125. * @return boolean Should process continue
  126. */
  127. public function before($event = array()) {
  128. return true;
  129. }
  130. /**
  131. * After callback to be implemented in subclasses
  132. *
  133. * @param array $events schema object properties
  134. */
  135. public function after($event = array()) {
  136. }
  137. /**
  138. * Reads database and creates schema tables
  139. *
  140. * @param array $options schema object properties
  141. * @return array Set of name and tables
  142. */
  143. public function load($options = array()) {
  144. if (is_string($options)) {
  145. $options = array('path' => $options);
  146. }
  147. $this->build($options);
  148. extract(get_object_vars($this));
  149. $class = $name .'Schema';
  150. if (!class_exists($class)) {
  151. if (file_exists($path . DS . $file) && is_file($path . DS . $file)) {
  152. require_once($path . DS . $file);
  153. } elseif (file_exists($path . DS . 'schema.php') && is_file($path . DS . 'schema.php')) {
  154. require_once($path . DS . 'schema.php');
  155. }
  156. }
  157. if (class_exists($class)) {
  158. $Schema = new $class($options);
  159. return $Schema;
  160. }
  161. return false;
  162. }
  163. /**
  164. * Reads database and creates schema tables
  165. *
  166. * Options
  167. *
  168. * - 'connection' - the db connection to use
  169. * - 'name' - name of the schema
  170. * - 'models' - a list of models to use, or false to ignore models
  171. *
  172. * @param array $options schema object properties
  173. * @return array Array indexed by name and tables
  174. */
  175. public function read($options = array()) {
  176. extract(array_merge(
  177. array(
  178. 'connection' => $this->connection,
  179. 'name' => $this->name,
  180. 'models' => true,
  181. ),
  182. $options
  183. ));
  184. $db = ConnectionManager::getDataSource($connection);
  185. if (isset($this->plugin)) {
  186. App::uses(Inflector::camelize($this->plugin) . 'AppModel', $this->plugin . '.Model');
  187. }
  188. $tables = array();
  189. $currentTables = $db->listSources();
  190. $prefix = null;
  191. if (isset($db->config['prefix'])) {
  192. $prefix = $db->config['prefix'];
  193. }
  194. if (!is_array($models) && $models !== false) {
  195. if (isset($this->plugin)) {
  196. $models = App::objects($this->plugin . '.Model', null, false);
  197. } else {
  198. $models = App::objects('Model');
  199. }
  200. }
  201. if (is_array($models)) {
  202. foreach ($models as $model) {
  203. $importModel = $model;
  204. $plugin = null;
  205. if (isset($this->plugin)) {
  206. if ($model == $this->plugin . 'AppModel') {
  207. continue;
  208. }
  209. $importModel = $model;
  210. $plugin = $this->plugin . '.';
  211. }
  212. App::uses($importModel, $plugin . 'Model');
  213. if (!class_exists($importModel)) {
  214. continue;
  215. }
  216. $vars = get_class_vars($model);
  217. if (empty($vars['useDbConfig']) || $vars['useDbConfig'] != $connection) {
  218. continue;
  219. }
  220. $Object = ClassRegistry::init(array('class' => $model, 'ds' => $connection));
  221. $db = $Object->getDataSource();
  222. if (is_object($Object) && $Object->useTable !== false) {
  223. $fulltable = $table = $db->fullTableName($Object, false);
  224. if ($prefix && strpos($table, $prefix) !== 0) {
  225. continue;
  226. }
  227. $table = str_replace($prefix, '', $table);
  228. if (in_array($fulltable, $currentTables)) {
  229. $key = array_search($fulltable, $currentTables);
  230. if (empty($tables[$table])) {
  231. $tables[$table] = $this->__columns($Object);
  232. $tables[$table]['indexes'] = $db->index($Object);
  233. $tables[$table]['tableParameters'] = $db->readTableParameters($fulltable);
  234. unset($currentTables[$key]);
  235. }
  236. if (!empty($Object->hasAndBelongsToMany)) {
  237. foreach ($Object->hasAndBelongsToMany as $Assoc => $assocData) {
  238. if (isset($assocData['with'])) {
  239. $class = $assocData['with'];
  240. }
  241. if (is_object($Object->$class)) {
  242. $withTable = $db->fullTableName($Object->$class, false);
  243. if ($prefix && strpos($withTable, $prefix) !== 0) {
  244. continue;
  245. }
  246. if (in_array($withTable, $currentTables)) {
  247. $key = array_search($withTable, $currentTables);
  248. $noPrefixWith = str_replace($prefix, '', $withTable);
  249. $tables[$noPrefixWith] = $this->__columns($Object->$class);
  250. $tables[$noPrefixWith]['indexes'] = $db->index($Object->$class);
  251. $tables[$noPrefixWith]['tableParameters'] = $db->readTableParameters($withTable);
  252. unset($currentTables[$key]);
  253. }
  254. }
  255. }
  256. }
  257. }
  258. }
  259. }
  260. }
  261. if (!empty($currentTables)) {
  262. foreach ($currentTables as $table) {
  263. if ($prefix) {
  264. if (strpos($table, $prefix) !== 0) {
  265. continue;
  266. }
  267. $table = str_replace($prefix, '', $table);
  268. }
  269. $Object = new AppModel(array(
  270. 'name' => Inflector::classify($table), 'table' => $table, 'ds' => $connection
  271. ));
  272. $systemTables = array(
  273. 'aros', 'acos', 'aros_acos', Configure::read('Session.table'), 'i18n'
  274. );
  275. if (in_array($table, $systemTables)) {
  276. $tables[$Object->table] = $this->__columns($Object);
  277. $tables[$Object->table]['indexes'] = $db->index($Object);
  278. $tables[$Object->table]['tableParameters'] = $db->readTableParameters($table);
  279. } elseif ($models === false) {
  280. $tables[$table] = $this->__columns($Object);
  281. $tables[$table]['indexes'] = $db->index($Object);
  282. $tables[$table]['tableParameters'] = $db->readTableParameters($table);
  283. } else {
  284. $tables['missing'][$table] = $this->__columns($Object);
  285. $tables['missing'][$table]['indexes'] = $db->index($Object);
  286. $tables['missing'][$table]['tableParameters'] = $db->readTableParameters($table);
  287. }
  288. }
  289. }
  290. ksort($tables);
  291. return compact('name', 'tables');
  292. }
  293. /**
  294. * Writes schema file from object or options
  295. *
  296. * @param mixed $object schema object or options array
  297. * @param array $options schema object properties to override object
  298. * @return mixed false or string written to file
  299. */
  300. public function write($object, $options = array()) {
  301. if (is_object($object)) {
  302. $object = get_object_vars($object);
  303. $this->build($object);
  304. }
  305. if (is_array($object)) {
  306. $options = $object;
  307. unset($object);
  308. }
  309. extract(array_merge(
  310. get_object_vars($this), $options
  311. ));
  312. $out = "class {$name}Schema extends CakeSchema {\n";
  313. if ($path !== $this->path) {
  314. $out .= "\tvar \$path = '{$path}';\n\n";
  315. }
  316. if ($file !== $this->file) {
  317. $out .= "\tvar \$file = '{$file}';\n\n";
  318. }
  319. if ($connection !== 'default') {
  320. $out .= "\tvar \$connection = '{$connection}';\n\n";
  321. }
  322. $out .= "\tfunction before(\$event = array()) {\n\t\treturn true;\n\t}\n\n\tfunction after(\$event = array()) {\n\t}\n\n";
  323. if (empty($tables)) {
  324. $this->read();
  325. }
  326. foreach ($tables as $table => $fields) {
  327. if (!is_numeric($table) && $table !== 'missing') {
  328. $out .= $this->generateTable($table, $fields);
  329. }
  330. }
  331. $out .= "}\n";
  332. $file = new SplFileObject($path . DS . $file, 'w+');
  333. $content = "<?php \n/* {$name} schema generated on: " . date('Y-m-d H:i:s') . " : ". time() . "*/\n{$out}?>";
  334. if ($file->fwrite($content)) {
  335. return $content;
  336. }
  337. return false;
  338. }
  339. /**
  340. * Generate the code for a table. Takes a table name and $fields array
  341. * Returns a completed variable declaration to be used in schema classes
  342. *
  343. * @param string $table Table name you want returned.
  344. * @param array $fields Array of field information to generate the table with.
  345. * @return string Variable declaration for a schema class
  346. */
  347. function generateTable($table, $fields) {
  348. $out = "\tvar \${$table} = array(\n";
  349. if (is_array($fields)) {
  350. $cols = array();
  351. foreach ($fields as $field => $value) {
  352. if ($field != 'indexes' && $field != 'tableParameters') {
  353. if (is_string($value)) {
  354. $type = $value;
  355. $value = array('type'=> $type);
  356. }
  357. $col = "\t\t'{$field}' => array('type' => '" . $value['type'] . "', ";
  358. unset($value['type']);
  359. $col .= join(', ', $this->__values($value));
  360. } elseif ($field == 'indexes') {
  361. $col = "\t\t'indexes' => array(";
  362. $props = array();
  363. foreach ((array)$value as $key => $index) {
  364. $props[] = "'{$key}' => array(" . join(', ', $this->__values($index)) . ")";
  365. }
  366. $col .= join(', ', $props);
  367. } elseif ($field == 'tableParameters') {
  368. //@todo add charset, collate and engine here
  369. $col = "\t\t'tableParameters' => array(";
  370. $props = array();
  371. foreach ((array)$value as $key => $param) {
  372. $props[] = "'{$key}' => '$param'";
  373. }
  374. $col .= join(', ', $props);
  375. }
  376. $col .= ")";
  377. $cols[] = $col;
  378. }
  379. $out .= join(",\n", $cols);
  380. }
  381. $out .= "\n\t);\n";
  382. return $out;
  383. }
  384. /**
  385. * Compares two sets of schemas
  386. *
  387. * @param mixed $old Schema object or array
  388. * @param mixed $new Schema object or array
  389. * @return array Tables (that are added, dropped, or changed)
  390. */
  391. public function compare($old, $new = null) {
  392. if (empty($new)) {
  393. $new = $this;
  394. }
  395. if (is_array($new)) {
  396. if (isset($new['tables'])) {
  397. $new = $new['tables'];
  398. }
  399. } else {
  400. $new = $new->tables;
  401. }
  402. if (is_array($old)) {
  403. if (isset($old['tables'])) {
  404. $old = $old['tables'];
  405. }
  406. } else {
  407. $old = $old->tables;
  408. }
  409. $tables = array();
  410. foreach ($new as $table => $fields) {
  411. if ($table == 'missing') {
  412. continue;
  413. }
  414. if (!array_key_exists($table, $old)) {
  415. $tables[$table]['add'] = $fields;
  416. } else {
  417. $diff = $this->_arrayDiffAssoc($fields, $old[$table]);
  418. if (!empty($diff)) {
  419. $tables[$table]['add'] = $diff;
  420. }
  421. $diff = $this->_arrayDiffAssoc($old[$table], $fields);
  422. if (!empty($diff)) {
  423. $tables[$table]['drop'] = $diff;
  424. }
  425. }
  426. foreach ($fields as $field => $value) {
  427. if (isset($old[$table][$field])) {
  428. $diff = $this->_arrayDiffAssoc($value, $old[$table][$field]);
  429. if (!empty($diff) && $field !== 'indexes' && $field !== 'tableParameters') {
  430. $tables[$table]['change'][$field] = array_merge($old[$table][$field], $diff);
  431. }
  432. }
  433. if (isset($add[$table][$field])) {
  434. $wrapper = array_keys($fields);
  435. if ($column = array_search($field, $wrapper)) {
  436. if (isset($wrapper[$column - 1])) {
  437. $tables[$table]['add'][$field]['after'] = $wrapper[$column - 1];
  438. }
  439. }
  440. }
  441. }
  442. if (isset($old[$table]['indexes']) && isset($new[$table]['indexes'])) {
  443. $diff = $this->_compareIndexes($new[$table]['indexes'], $old[$table]['indexes']);
  444. if ($diff) {
  445. if (!isset($tables[$table])) {
  446. $tables[$table] = array();
  447. }
  448. if (isset($diff['drop'])) {
  449. $tables[$table]['drop']['indexes'] = $diff['drop'];
  450. }
  451. if ($diff && isset($diff['add'])) {
  452. $tables[$table]['add']['indexes'] = $diff['add'];
  453. }
  454. }
  455. }
  456. if (isset($old[$table]['tableParameters']) && isset($new[$table]['tableParameters'])) {
  457. $diff = $this->_compareTableParameters($new[$table]['tableParameters'], $old[$table]['tableParameters']);
  458. if ($diff) {
  459. $tables[$table]['change']['tableParameters'] = $diff;
  460. }
  461. }
  462. }
  463. return $tables;
  464. }
  465. /**
  466. * Extended array_diff_assoc noticing change from/to NULL values
  467. *
  468. * It behaves almost the same way as array_diff_assoc except for NULL values: if
  469. * one of the values is not NULL - change is detected. It is useful in situation
  470. * where one value is strval('') ant other is strval(null) - in string comparing
  471. * methods this results as EQUAL, while it is not.
  472. *
  473. * @param array $array1 Base array
  474. * @param array $array2 Corresponding array checked for equality
  475. * @return array Difference as array with array(keys => values) from input array
  476. * where match was not found.
  477. * @access protected
  478. */
  479. function _arrayDiffAssoc($array1, $array2) {
  480. $difference = array();
  481. foreach ($array1 as $key => $value) {
  482. if (!array_key_exists($key, $array2)) {
  483. $difference[$key] = $value;
  484. continue;
  485. }
  486. $correspondingValue = $array2[$key];
  487. if (is_null($value) !== is_null($correspondingValue)) {
  488. $difference[$key] = $value;
  489. continue;
  490. }
  491. if (is_bool($value) !== is_bool($correspondingValue)) {
  492. $difference[$key] = $value;
  493. continue;
  494. }
  495. $compare = strval($value);
  496. $correspondingValue = strval($correspondingValue);
  497. if ($compare === $correspondingValue) {
  498. continue;
  499. }
  500. $difference[$key] = $value;
  501. }
  502. return $difference;
  503. }
  504. /**
  505. * Formats Schema columns from Model Object
  506. *
  507. * @param array $values options keys(type, null, default, key, length, extra)
  508. * @return array Formatted values
  509. */
  510. public function __values($values) {
  511. $vals = array();
  512. if (is_array($values)) {
  513. foreach ($values as $key => $val) {
  514. if (is_array($val)) {
  515. $vals[] = "'{$key}' => array('" . implode("', '", $val) . "')";
  516. } else if (!is_numeric($key)) {
  517. $val = var_export($val, true);
  518. $vals[] = "'{$key}' => {$val}";
  519. }
  520. }
  521. }
  522. return $vals;
  523. }
  524. /**
  525. * Formats Schema columns from Model Object
  526. *
  527. * @param array $Obj model object
  528. * @return array Formatted columns
  529. */
  530. public function __columns(&$Obj) {
  531. $db = $Obj->getDataSource();
  532. $fields = $Obj->schema(true);
  533. $columns = $props = array();
  534. foreach ($fields as $name => $value) {
  535. if ($Obj->primaryKey == $name) {
  536. $value['key'] = 'primary';
  537. }
  538. if (!isset($db->columns[$value['type']])) {
  539. trigger_error(__d('cake_dev', 'Schema generation error: invalid column type %s does not exist in DBO', $value['type']), E_USER_NOTICE);
  540. continue;
  541. } else {
  542. $defaultCol = $db->columns[$value['type']];
  543. if (isset($defaultCol['limit']) && $defaultCol['limit'] == $value['length']) {
  544. unset($value['length']);
  545. } elseif (isset($defaultCol['length']) && $defaultCol['length'] == $value['length']) {
  546. unset($value['length']);
  547. }
  548. unset($value['limit']);
  549. }
  550. if (isset($value['default']) && ($value['default'] === '' || $value['default'] === false)) {
  551. unset($value['default']);
  552. }
  553. if (empty($value['length'])) {
  554. unset($value['length']);
  555. }
  556. if (empty($value['key'])) {
  557. unset($value['key']);
  558. }
  559. $columns[$name] = $value;
  560. }
  561. return $columns;
  562. }
  563. /**
  564. * Compare two schema files table Parameters
  565. *
  566. * @param array $new New indexes
  567. * @param array $old Old indexes
  568. * @return mixed False on failure, or an array of parameters to add & drop.
  569. */
  570. function _compareTableParameters($new, $old) {
  571. if (!is_array($new) || !is_array($old)) {
  572. return false;
  573. }
  574. $change = $this->_arrayDiffAssoc($new, $old);
  575. return $change;
  576. }
  577. /**
  578. * Compare two schema indexes
  579. *
  580. * @param array $new New indexes
  581. * @param array $old Old indexes
  582. * @return mixed false on failure or array of indexes to add and drop
  583. */
  584. function _compareIndexes($new, $old) {
  585. if (!is_array($new) || !is_array($old)) {
  586. return false;
  587. }
  588. $add = $drop = array();
  589. $diff = $this->_arrayDiffAssoc($new, $old);
  590. if (!empty($diff)) {
  591. $add = $diff;
  592. }
  593. $diff = $this->_arrayDiffAssoc($old, $new);
  594. if (!empty($diff)) {
  595. $drop = $diff;
  596. }
  597. foreach ($new as $name => $value) {
  598. if (isset($old[$name])) {
  599. $newUnique = isset($value['unique']) ? $value['unique'] : 0;
  600. $oldUnique = isset($old[$name]['unique']) ? $old[$name]['unique'] : 0;
  601. $newColumn = $value['column'];
  602. $oldColumn = $old[$name]['column'];
  603. $diff = false;
  604. if ($newUnique != $oldUnique) {
  605. $diff = true;
  606. } elseif (is_array($newColumn) && is_array($oldColumn)) {
  607. $diff = ($newColumn !== $oldColumn);
  608. } elseif (is_string($newColumn) && is_string($oldColumn)) {
  609. $diff = ($newColumn != $oldColumn);
  610. } else {
  611. $diff = true;
  612. }
  613. if ($diff) {
  614. $drop[$name] = null;
  615. $add[$name] = $value;
  616. }
  617. }
  618. }
  619. return array_filter(compact('add', 'drop'));
  620. }
  621. }