PageRenderTime 54ms CodeModel.GetById 24ms RepoModel.GetById 0ms app.codeStats 0ms

/lib/Cake/Model/CakeSchema.php

https://bitbucket.org/udeshika/fake_twitter
PHP | 706 lines | 473 code | 72 blank | 161 comment | 138 complexity | 8066c4622e70965ac741fd8a4e5821d3 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-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. try {
  220. $Object = ClassRegistry::init(array('class' => $model, 'ds' => $connection));
  221. } catch (CakeException $e) {
  222. continue;
  223. }
  224. $db = $Object->getDataSource();
  225. if (is_object($Object) && $Object->useTable !== false) {
  226. $fulltable = $table = $db->fullTableName($Object, false);
  227. if ($prefix && strpos($table, $prefix) !== 0) {
  228. continue;
  229. }
  230. $table = $this->_noPrefixTable($prefix, $table);
  231. if (in_array($fulltable, $currentTables)) {
  232. $key = array_search($fulltable, $currentTables);
  233. if (empty($tables[$table])) {
  234. $tables[$table] = $this->_columns($Object);
  235. $tables[$table]['indexes'] = $db->index($Object);
  236. $tables[$table]['tableParameters'] = $db->readTableParameters($fulltable);
  237. unset($currentTables[$key]);
  238. }
  239. if (!empty($Object->hasAndBelongsToMany)) {
  240. foreach ($Object->hasAndBelongsToMany as $Assoc => $assocData) {
  241. if (isset($assocData['with'])) {
  242. $class = $assocData['with'];
  243. }
  244. if (is_object($Object->$class)) {
  245. $withTable = $db->fullTableName($Object->$class, false);
  246. if ($prefix && strpos($withTable, $prefix) !== 0) {
  247. continue;
  248. }
  249. if (in_array($withTable, $currentTables)) {
  250. $key = array_search($withTable, $currentTables);
  251. $noPrefixWith = $this->_noPrefixTable($prefix, $withTable);
  252. $tables[$noPrefixWith] = $this->_columns($Object->$class);
  253. $tables[$noPrefixWith]['indexes'] = $db->index($Object->$class);
  254. $tables[$noPrefixWith]['tableParameters'] = $db->readTableParameters($withTable);
  255. unset($currentTables[$key]);
  256. }
  257. }
  258. }
  259. }
  260. }
  261. }
  262. }
  263. }
  264. if (!empty($currentTables)) {
  265. foreach ($currentTables as $table) {
  266. if ($prefix) {
  267. if (strpos($table, $prefix) !== 0) {
  268. continue;
  269. }
  270. $table = $this->_noPrefixTable($prefix, $table);
  271. }
  272. $Object = new AppModel(array(
  273. 'name' => Inflector::classify($table), 'table' => $table, 'ds' => $connection
  274. ));
  275. $systemTables = array(
  276. 'aros', 'acos', 'aros_acos', Configure::read('Session.table'), 'i18n'
  277. );
  278. $fulltable = $db->fullTableName($Object, false);
  279. if (in_array($table, $systemTables)) {
  280. $tables[$Object->table] = $this->_columns($Object);
  281. $tables[$Object->table]['indexes'] = $db->index($Object);
  282. $tables[$Object->table]['tableParameters'] = $db->readTableParameters($fulltable);
  283. } elseif ($models === false) {
  284. $tables[$table] = $this->_columns($Object);
  285. $tables[$table]['indexes'] = $db->index($Object);
  286. $tables[$table]['tableParameters'] = $db->readTableParameters($fulltable);
  287. } else {
  288. $tables['missing'][$table] = $this->_columns($Object);
  289. $tables['missing'][$table]['indexes'] = $db->index($Object);
  290. $tables['missing'][$table]['tableParameters'] = $db->readTableParameters($fulltable);
  291. }
  292. }
  293. }
  294. ksort($tables);
  295. return compact('name', 'tables');
  296. }
  297. /**
  298. * Writes schema file from object or options
  299. *
  300. * @param mixed $object schema object or options array
  301. * @param array $options schema object properties to override object
  302. * @return mixed false or string written to file
  303. */
  304. public function write($object, $options = array()) {
  305. if (is_object($object)) {
  306. $object = get_object_vars($object);
  307. $this->build($object);
  308. }
  309. if (is_array($object)) {
  310. $options = $object;
  311. unset($object);
  312. }
  313. extract(array_merge(
  314. get_object_vars($this), $options
  315. ));
  316. $out = "class {$name}Schema extends CakeSchema {\n\n";
  317. if ($path !== $this->path) {
  318. $out .= "\tpublic \$path = '{$path}';\n\n";
  319. }
  320. if ($file !== $this->file) {
  321. $out .= "\tpublic \$file = '{$file}';\n\n";
  322. }
  323. if ($connection !== 'default') {
  324. $out .= "\tpublic \$connection = '{$connection}';\n\n";
  325. }
  326. $out .= "\tpublic function before(\$event = array()) {\n\t\treturn true;\n\t}\n\n\tpublic function after(\$event = array()) {\n\t}\n\n";
  327. if (empty($tables)) {
  328. $this->read();
  329. }
  330. foreach ($tables as $table => $fields) {
  331. if (!is_numeric($table) && $table !== 'missing') {
  332. $out .= $this->generateTable($table, $fields);
  333. }
  334. }
  335. $out .= "}\n";
  336. $file = new SplFileObject($path . DS . $file, 'w+');
  337. $content = "<?php \n/* generated on: " . date('Y-m-d H:i:s') . " : ". time() . " */\n{$out}";
  338. if ($file->fwrite($content)) {
  339. return $content;
  340. }
  341. return false;
  342. }
  343. /**
  344. * Generate the code for a table. Takes a table name and $fields array
  345. * Returns a completed variable declaration to be used in schema classes
  346. *
  347. * @param string $table Table name you want returned.
  348. * @param array $fields Array of field information to generate the table with.
  349. * @return string Variable declaration for a schema class
  350. */
  351. public function generateTable($table, $fields) {
  352. $out = "\tpublic \${$table} = array(\n";
  353. if (is_array($fields)) {
  354. $cols = array();
  355. foreach ($fields as $field => $value) {
  356. if ($field != 'indexes' && $field != 'tableParameters') {
  357. if (is_string($value)) {
  358. $type = $value;
  359. $value = array('type' => $type);
  360. }
  361. $col = "\t\t'{$field}' => array('type' => '" . $value['type'] . "', ";
  362. unset($value['type']);
  363. $col .= join(', ', $this->_values($value));
  364. } elseif ($field == 'indexes') {
  365. $col = "\t\t'indexes' => array(";
  366. $props = array();
  367. foreach ((array)$value as $key => $index) {
  368. $props[] = "'{$key}' => array(" . join(', ', $this->_values($index)) . ")";
  369. }
  370. $col .= join(', ', $props);
  371. } elseif ($field == 'tableParameters') {
  372. $col = "\t\t'tableParameters' => array(";
  373. $props = array();
  374. foreach ((array)$value as $key => $param) {
  375. $props[] = "'{$key}' => '$param'";
  376. }
  377. $col .= join(', ', $props);
  378. }
  379. $col .= ")";
  380. $cols[] = $col;
  381. }
  382. $out .= join(",\n", $cols);
  383. }
  384. $out .= "\n\t);\n";
  385. return $out;
  386. }
  387. /**
  388. * Compares two sets of schemas
  389. *
  390. * @param mixed $old Schema object or array
  391. * @param mixed $new Schema object or array
  392. * @return array Tables (that are added, dropped, or changed)
  393. */
  394. public function compare($old, $new = null) {
  395. if (empty($new)) {
  396. $new = $this;
  397. }
  398. if (is_array($new)) {
  399. if (isset($new['tables'])) {
  400. $new = $new['tables'];
  401. }
  402. } else {
  403. $new = $new->tables;
  404. }
  405. if (is_array($old)) {
  406. if (isset($old['tables'])) {
  407. $old = $old['tables'];
  408. }
  409. } else {
  410. $old = $old->tables;
  411. }
  412. $tables = array();
  413. foreach ($new as $table => $fields) {
  414. if ($table == 'missing') {
  415. continue;
  416. }
  417. if (!array_key_exists($table, $old)) {
  418. $tables[$table]['add'] = $fields;
  419. } else {
  420. $diff = $this->_arrayDiffAssoc($fields, $old[$table]);
  421. if (!empty($diff)) {
  422. $tables[$table]['add'] = $diff;
  423. }
  424. $diff = $this->_arrayDiffAssoc($old[$table], $fields);
  425. if (!empty($diff)) {
  426. $tables[$table]['drop'] = $diff;
  427. }
  428. }
  429. foreach ($fields as $field => $value) {
  430. if (!empty($old[$table][$field])) {
  431. $diff = $this->_arrayDiffAssoc($value, $old[$table][$field]);
  432. if (!empty($diff) && $field !== 'indexes' && $field !== 'tableParameters') {
  433. $tables[$table]['change'][$field] = array_merge($old[$table][$field], $diff);
  434. }
  435. }
  436. if (isset($tables[$table]['add'][$field]) && $field !== 'indexes' && $field !== 'tableParameters') {
  437. $wrapper = array_keys($fields);
  438. if ($column = array_search($field, $wrapper)) {
  439. if (isset($wrapper[$column - 1])) {
  440. $tables[$table]['add'][$field]['after'] = $wrapper[$column - 1];
  441. }
  442. }
  443. }
  444. }
  445. if (isset($old[$table]['indexes']) && isset($new[$table]['indexes'])) {
  446. $diff = $this->_compareIndexes($new[$table]['indexes'], $old[$table]['indexes']);
  447. if ($diff) {
  448. if (!isset($tables[$table])) {
  449. $tables[$table] = array();
  450. }
  451. if (isset($diff['drop'])) {
  452. $tables[$table]['drop']['indexes'] = $diff['drop'];
  453. }
  454. if ($diff && isset($diff['add'])) {
  455. $tables[$table]['add']['indexes'] = $diff['add'];
  456. }
  457. }
  458. }
  459. if (isset($old[$table]['tableParameters']) && isset($new[$table]['tableParameters'])) {
  460. $diff = $this->_compareTableParameters($new[$table]['tableParameters'], $old[$table]['tableParameters']);
  461. if ($diff) {
  462. $tables[$table]['change']['tableParameters'] = $diff;
  463. }
  464. }
  465. }
  466. return $tables;
  467. }
  468. /**
  469. * Extended array_diff_assoc noticing change from/to NULL values
  470. *
  471. * It behaves almost the same way as array_diff_assoc except for NULL values: if
  472. * one of the values is not NULL - change is detected. It is useful in situation
  473. * where one value is strval('') ant other is strval(null) - in string comparing
  474. * methods this results as EQUAL, while it is not.
  475. *
  476. * @param array $array1 Base array
  477. * @param array $array2 Corresponding array checked for equality
  478. * @return array Difference as array with array(keys => values) from input array
  479. * where match was not found.
  480. */
  481. protected function _arrayDiffAssoc($array1, $array2) {
  482. $difference = array();
  483. foreach ($array1 as $key => $value) {
  484. if (!array_key_exists($key, $array2)) {
  485. $difference[$key] = $value;
  486. continue;
  487. }
  488. $correspondingValue = $array2[$key];
  489. if (is_null($value) !== is_null($correspondingValue)) {
  490. $difference[$key] = $value;
  491. continue;
  492. }
  493. if (is_bool($value) !== is_bool($correspondingValue)) {
  494. $difference[$key] = $value;
  495. continue;
  496. }
  497. if (is_array($value) && is_array($correspondingValue)) {
  498. continue;
  499. }
  500. if ($value === $correspondingValue) {
  501. continue;
  502. }
  503. $difference[$key] = $value;
  504. }
  505. return $difference;
  506. }
  507. /**
  508. * Formats Schema columns from Model Object
  509. *
  510. * @param array $values options keys(type, null, default, key, length, extra)
  511. * @return array Formatted values
  512. */
  513. protected function _values($values) {
  514. $vals = array();
  515. if (is_array($values)) {
  516. foreach ($values as $key => $val) {
  517. if (is_array($val)) {
  518. $vals[] = "'{$key}' => array('" . implode("', '", $val) . "')";
  519. } else if (!is_numeric($key)) {
  520. $val = var_export($val, true);
  521. $vals[] = "'{$key}' => {$val}";
  522. }
  523. }
  524. }
  525. return $vals;
  526. }
  527. /**
  528. * Formats Schema columns from Model Object
  529. *
  530. * @param array $Obj model object
  531. * @return array Formatted columns
  532. */
  533. protected function _columns(&$Obj) {
  534. $db = $Obj->getDataSource();
  535. $fields = $Obj->schema(true);
  536. $columns = $props = array();
  537. foreach ($fields as $name => $value) {
  538. if ($Obj->primaryKey == $name) {
  539. $value['key'] = 'primary';
  540. }
  541. if (!isset($db->columns[$value['type']])) {
  542. 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);
  543. continue;
  544. } else {
  545. $defaultCol = $db->columns[$value['type']];
  546. if (isset($defaultCol['limit']) && $defaultCol['limit'] == $value['length']) {
  547. unset($value['length']);
  548. } elseif (isset($defaultCol['length']) && $defaultCol['length'] == $value['length']) {
  549. unset($value['length']);
  550. }
  551. unset($value['limit']);
  552. }
  553. if (isset($value['default']) && ($value['default'] === '' || $value['default'] === false)) {
  554. unset($value['default']);
  555. }
  556. if (empty($value['length'])) {
  557. unset($value['length']);
  558. }
  559. if (empty($value['key'])) {
  560. unset($value['key']);
  561. }
  562. $columns[$name] = $value;
  563. }
  564. return $columns;
  565. }
  566. /**
  567. * Compare two schema files table Parameters
  568. *
  569. * @param array $new New indexes
  570. * @param array $old Old indexes
  571. * @return mixed False on failure, or an array of parameters to add & drop.
  572. */
  573. protected function _compareTableParameters($new, $old) {
  574. if (!is_array($new) || !is_array($old)) {
  575. return false;
  576. }
  577. $change = $this->_arrayDiffAssoc($new, $old);
  578. return $change;
  579. }
  580. /**
  581. * Compare two schema indexes
  582. *
  583. * @param array $new New indexes
  584. * @param array $old Old indexes
  585. * @return mixed false on failure or array of indexes to add and drop
  586. */
  587. protected function _compareIndexes($new, $old) {
  588. if (!is_array($new) || !is_array($old)) {
  589. return false;
  590. }
  591. $add = $drop = array();
  592. $diff = $this->_arrayDiffAssoc($new, $old);
  593. if (!empty($diff)) {
  594. $add = $diff;
  595. }
  596. $diff = $this->_arrayDiffAssoc($old, $new);
  597. if (!empty($diff)) {
  598. $drop = $diff;
  599. }
  600. foreach ($new as $name => $value) {
  601. if (isset($old[$name])) {
  602. $newUnique = isset($value['unique']) ? $value['unique'] : 0;
  603. $oldUnique = isset($old[$name]['unique']) ? $old[$name]['unique'] : 0;
  604. $newColumn = $value['column'];
  605. $oldColumn = $old[$name]['column'];
  606. $diff = false;
  607. if ($newUnique != $oldUnique) {
  608. $diff = true;
  609. } elseif (is_array($newColumn) && is_array($oldColumn)) {
  610. $diff = ($newColumn !== $oldColumn);
  611. } elseif (is_string($newColumn) && is_string($oldColumn)) {
  612. $diff = ($newColumn != $oldColumn);
  613. } else {
  614. $diff = true;
  615. }
  616. if ($diff) {
  617. $drop[$name] = null;
  618. $add[$name] = $value;
  619. }
  620. }
  621. }
  622. return array_filter(compact('add', 'drop'));
  623. }
  624. /**
  625. * Trim the table prefix from the full table name, and return the prefix-less table
  626. *
  627. * @param string $prefix Table prefix
  628. * @param string $table Full table name
  629. * @return string Prefix-less table name
  630. */
  631. protected function _noPrefixTable($prefix, $table) {
  632. return preg_replace('/^' . preg_quote($prefix) . '/', '', $table);
  633. }
  634. }