CakeSchema.php 19 KB

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