CakeSchema.php 18 KB

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