PageRenderTime 51ms CodeModel.GetById 22ms RepoModel.GetById 0ms app.codeStats 1ms

/cake/libs/model/schema.php

https://github.com/jobzesage/Adres
PHP | 556 lines | 372 code | 43 blank | 141 comment | 105 complexity | a241712c37eba2ea9520d34f7c8ffc48 MD5 | raw file
Possible License(s): Apache-2.0, BSD-3-Clause-No-Nuclear-License-2014, BSD-3-Clause, LGPL-2.1
  1. <?php
  2. /* SVN FILE: $Id$ */
  3. /**
  4. * Schema database management for CakePHP.
  5. *
  6. * PHP versions 4 and 5
  7. *
  8. * CakePHP(tm) : Rapid Development Framework (http://www.cakephp.org)
  9. * Copyright 2005-2010, Cake Software Foundation, Inc. (http://www.cakefoundation.org)
  10. *
  11. * Licensed under The MIT License
  12. * Redistributions of files must retain the above copyright notice.
  13. *
  14. * @filesource
  15. * @copyright Copyright 2005-2010, Cake Software Foundation, Inc. (http://www.cakefoundation.org)
  16. * @link http://www.cakefoundation.org/projects/info/cakephp CakePHP(tm) Project
  17. * @package cake
  18. * @subpackage cake.cake.libs.model
  19. * @since CakePHP(tm) v 1.2.0.5550
  20. * @version $Revision$
  21. * @modifiedby $LastChangedBy$
  22. * @lastmodified $Date$
  23. * @license http://www.opensource.org/licenses/mit-license.php The MIT License
  24. */
  25. App::import('Model', 'ConnectionManager');
  26. /**
  27. * Base Class for Schema management
  28. *
  29. * @package cake
  30. * @subpackage cake.cake.libs.model
  31. */
  32. class CakeSchema extends Object {
  33. /**
  34. * Name of the App Schema
  35. *
  36. * @var string
  37. * @access public
  38. */
  39. var $name = null;
  40. /**
  41. * Path to write location
  42. *
  43. * @var string
  44. * @access public
  45. */
  46. var $path = null;
  47. /**
  48. * File to write
  49. *
  50. * @var string
  51. * @access public
  52. */
  53. var $file = 'schema.php';
  54. /**
  55. * Connection used for read
  56. *
  57. * @var string
  58. * @access public
  59. */
  60. var $connection = 'default';
  61. /**
  62. * Set of tables
  63. *
  64. * @var array
  65. * @access public
  66. */
  67. var $tables = array();
  68. /**
  69. * Constructor
  70. *
  71. * @param array $options optional load object properties
  72. */
  73. function __construct($options = array()) {
  74. parent::__construct();
  75. if (empty($options['name'])) {
  76. $this->name = preg_replace('/schema$/i', '', get_class($this));
  77. }
  78. if (strtolower($this->name) === 'cake') {
  79. $this->name = Inflector::camelize(Inflector::slug(Configure::read('App.dir')));
  80. }
  81. if (empty($options['path'])) {
  82. $this->path = CONFIGS . 'sql';
  83. }
  84. $options = array_merge(get_object_vars($this), $options);
  85. $this->_build($options);
  86. }
  87. /**
  88. * Builds schema object properties
  89. *
  90. * @param array $data loaded object properties
  91. * @return void
  92. * @access protected
  93. */
  94. function _build($data) {
  95. $file = null;
  96. foreach ($data as $key => $val) {
  97. if (!empty($val)) {
  98. if (!in_array($key, array('name', 'path', 'file', 'connection', 'tables', '_log'))) {
  99. $this->tables[$key] = $val;
  100. unset($this->{$key});
  101. } elseif ($key !== 'tables') {
  102. if ($key === 'name' && $val !== $this->name && !isset($data['file'])) {
  103. $file = Inflector::underscore($val) . '.php';
  104. }
  105. $this->{$key} = $val;
  106. }
  107. }
  108. }
  109. if (file_exists($this->path . DS . $file) && is_file($this->path . DS . $file)) {
  110. $this->file = $file;
  111. }
  112. }
  113. /**
  114. * Before callback to be implemented in subclasses
  115. *
  116. * @param array $events schema object properties
  117. * @return boolean Should process continue
  118. * @access public
  119. */
  120. function before($event = array()) {
  121. return true;
  122. }
  123. /**
  124. * After callback to be implemented in subclasses
  125. *
  126. * @param array $events schema object properties
  127. * @access public
  128. */
  129. function after($event = array()) {
  130. }
  131. /**
  132. * Reads database and creates schema tables
  133. *
  134. * @param array $options schema object properties
  135. * @return array Set of name and tables
  136. * @access public
  137. */
  138. function load($options = array()) {
  139. if (is_string($options)) {
  140. $options = array('path' => $options);
  141. }
  142. $this->_build($options);
  143. extract(get_object_vars($this));
  144. $class = $name .'Schema';
  145. if (!class_exists($class)) {
  146. if (file_exists($path . DS . $file) && is_file($path . DS . $file)) {
  147. require_once($path . DS . $file);
  148. } elseif (file_exists($path . DS . 'schema.php') && is_file($path . DS . 'schema.php')) {
  149. require_once($path . DS . 'schema.php');
  150. }
  151. }
  152. if (class_exists($class)) {
  153. $Schema =& new $class($options);
  154. return $Schema;
  155. }
  156. return false;
  157. }
  158. /**
  159. * Reads database and creates schema tables
  160. *
  161. * Options
  162. *
  163. * - 'connection' - the db connection to use
  164. * - 'name' - name of the schema
  165. * - 'models' - a list of models to use, or false to ignore models
  166. *
  167. * @param array $options schema object properties
  168. * @return array Array indexed by name and tables
  169. * @access public
  170. */
  171. 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. App::import('Model', 'AppModel');
  182. $tables = array();
  183. $currentTables = $db->listSources();
  184. $prefix = null;
  185. if (isset($db->config['prefix'])) {
  186. $prefix = $db->config['prefix'];
  187. }
  188. if (!is_array($models) && $models !== false) {
  189. $models = Configure::listObjects('model');
  190. }
  191. if (is_array($models)) {
  192. foreach ($models as $model) {
  193. if (PHP5) {
  194. $Object = ClassRegistry::init(array('class' => $model, 'ds' => $connection));
  195. } else {
  196. $Object =& ClassRegistry::init(array('class' => $model, 'ds' => $connection));
  197. }
  198. if (is_object($Object) && $Object->useTable !== false) {
  199. $Object->setDataSource($connection);
  200. $table = $db->fullTableName($Object, false);
  201. if (in_array($table, $currentTables)) {
  202. $key = array_search($table, $currentTables);
  203. if (empty($tables[$Object->table])) {
  204. $tables[$Object->table] = $this->__columns($Object);
  205. $tables[$Object->table]['indexes'] = $db->index($Object);
  206. unset($currentTables[$key]);
  207. }
  208. if (!empty($Object->hasAndBelongsToMany)) {
  209. foreach ($Object->hasAndBelongsToMany as $Assoc => $assocData) {
  210. if (isset($assocData['with'])) {
  211. $class = $assocData['with'];
  212. } elseif ($assocData['_with']) {
  213. $class = $assocData['_with'];
  214. }
  215. if (is_object($Object->$class)) {
  216. $table = $db->fullTableName($Object->$class, false);
  217. if (in_array($table, $currentTables)) {
  218. $key = array_search($table, $currentTables);
  219. $tables[$Object->$class->table] = $this->__columns($Object->$class);
  220. $tables[$Object->$class->table]['indexes'] = $db->index($Object->$class);
  221. unset($currentTables[$key]);
  222. }
  223. }
  224. }
  225. }
  226. }
  227. }
  228. }
  229. }
  230. if (!empty($currentTables)) {
  231. foreach ($currentTables as $table) {
  232. if ($prefix) {
  233. if (strpos($table, $prefix) !== 0) {
  234. continue;
  235. }
  236. $table = str_replace($prefix, '', $table);
  237. }
  238. $Object = new AppModel(array(
  239. 'name' => Inflector::classify($table), 'table' => $table, 'ds' => $connection
  240. ));
  241. $systemTables = array(
  242. 'aros', 'acos', 'aros_acos', Configure::read('Session.table'), 'i18n'
  243. );
  244. if (in_array($table, $systemTables)) {
  245. $tables[$Object->table] = $this->__columns($Object);
  246. $tables[$Object->table]['indexes'] = $db->index($Object);
  247. } elseif ($models === false) {
  248. $tables[$table] = $this->__columns($Object);
  249. $tables[$table]['indexes'] = $db->index($Object);
  250. } else {
  251. $tables['missing'][$table] = $this->__columns($Object);
  252. $tables['missing'][$table]['indexes'] = $db->index($Object);
  253. }
  254. }
  255. }
  256. ksort($tables);
  257. return compact('name', 'tables');
  258. }
  259. /**
  260. * Writes schema file from object or options
  261. *
  262. * @param mixed $object schema object or options array
  263. * @param array $options schema object properties to override object
  264. * @return mixed false or string written to file
  265. * @access public
  266. */
  267. function write($object, $options = array()) {
  268. if (is_object($object)) {
  269. $object = get_object_vars($object);
  270. $this->_build($object);
  271. }
  272. if (is_array($object)) {
  273. $options = $object;
  274. unset($object);
  275. }
  276. extract(array_merge(
  277. get_object_vars($this), $options
  278. ));
  279. $out = "class {$name}Schema extends CakeSchema {\n";
  280. $out .= "\tvar \$name = '{$name}';\n\n";
  281. if ($path !== $this->path) {
  282. $out .= "\tvar \$path = '{$path}';\n\n";
  283. }
  284. if ($file !== $this->file) {
  285. $out .= "\tvar \$file = '{$file}';\n\n";
  286. }
  287. if ($connection !== 'default') {
  288. $out .= "\tvar \$connection = '{$connection}';\n\n";
  289. }
  290. $out .= "\tfunction before(\$event = array()) {\n\t\treturn true;\n\t}\n\n\tfunction after(\$event = array()) {\n\t}\n\n";
  291. if (empty($tables)) {
  292. $this->read();
  293. }
  294. foreach ($tables as $table => $fields) {
  295. if (!is_numeric($table) && $table !== 'missing') {
  296. $out .= "\tvar \${$table} = array(\n";
  297. if (is_array($fields)) {
  298. $cols = array();
  299. foreach ($fields as $field => $value) {
  300. if ($field != 'indexes') {
  301. if (is_string($value)) {
  302. $type = $value;
  303. $value = array('type'=> $type);
  304. }
  305. $col = "\t\t'{$field}' => array('type' => '" . $value['type'] . "', ";
  306. unset($value['type']);
  307. $col .= implode(', ', $this->__values($value));
  308. } else {
  309. $col = "\t\t'indexes' => array(";
  310. $props = array();
  311. foreach ((array)$value as $key => $index) {
  312. $props[] = "'{$key}' => array(" . implode(', ', $this->__values($index)) . ")";
  313. }
  314. $col .= implode(', ', $props);
  315. }
  316. $col .= ")";
  317. $cols[] = $col;
  318. }
  319. $out .= implode(",\n", $cols);
  320. }
  321. $out .= "\n\t);\n";
  322. }
  323. }
  324. $out .="}\n";
  325. $File =& new File($path . DS . $file, true);
  326. $header = '$Id';
  327. $content = "<?php \n/* SVN FILE: {$header}$ */\n/* {$name} schema generated on: " . date('Y-m-d H:m:s') . " : ". time() . "*/\n{$out}?>";
  328. $content = $File->prepare($content);
  329. if ($File->write($content)) {
  330. return $content;
  331. }
  332. return false;
  333. }
  334. /**
  335. * Compares two sets of schemas
  336. *
  337. * @param mixed $old Schema object or array
  338. * @param mixed $new Schema object or array
  339. * @return array Tables (that are added, dropped, or changed)
  340. * @access public
  341. */
  342. function compare($old, $new = null) {
  343. if (empty($new)) {
  344. $new = $this;
  345. }
  346. if (is_array($new)) {
  347. if (isset($new['tables'])) {
  348. $new = $new['tables'];
  349. }
  350. } else {
  351. $new = $new->tables;
  352. }
  353. if (is_array($old)) {
  354. if (isset($old['tables'])) {
  355. $old = $old['tables'];
  356. }
  357. } else {
  358. $old = $old->tables;
  359. }
  360. $tables = array();
  361. foreach ($new as $table => $fields) {
  362. if ($table == 'missing') {
  363. break;
  364. }
  365. if (!array_key_exists($table, $old)) {
  366. $tables[$table]['add'] = $fields;
  367. } else {
  368. $diff = array_diff_assoc($fields, $old[$table]);
  369. if (!empty($diff)) {
  370. $tables[$table]['add'] = $diff;
  371. }
  372. $diff = array_diff_assoc($old[$table], $fields);
  373. if (!empty($diff)) {
  374. $tables[$table]['drop'] = $diff;
  375. }
  376. }
  377. foreach ($fields as $field => $value) {
  378. if (isset($old[$table][$field])) {
  379. $diff = array_diff_assoc($value, $old[$table][$field]);
  380. if (!empty($diff) && $field !== 'indexes') {
  381. $tables[$table]['change'][$field] = array_merge($old[$table][$field], $diff);
  382. }
  383. }
  384. if (isset($add[$table][$field])) {
  385. $wrapper = array_keys($fields);
  386. if ($column = array_search($field, $wrapper)) {
  387. if (isset($wrapper[$column - 1])) {
  388. $tables[$table]['add'][$field]['after'] = $wrapper[$column - 1];
  389. }
  390. }
  391. }
  392. }
  393. if (isset($old[$table]['indexes']) && isset($new[$table]['indexes'])) {
  394. $diff = $this->_compareIndexes($new[$table]['indexes'], $old[$table]['indexes']);
  395. if ($diff) {
  396. if (isset($tables[$table]['drop']['indexes']) && isset($diff['drop'])) {
  397. $tables[$table]['drop']['indexes'] = $diff['drop'];
  398. }
  399. if (isset($tables[$table]['add']['indexes']) && isset($diff['add'])) {
  400. $tables[$table]['add']['indexes'] = $diff['add'];
  401. }
  402. }
  403. }
  404. }
  405. return $tables;
  406. }
  407. /**
  408. * Formats Schema columns from Model Object
  409. *
  410. * @param array $values options keys(type, null, default, key, length, extra)
  411. * @return array Formatted values
  412. * @access public
  413. */
  414. function __values($values) {
  415. $vals = array();
  416. if (is_array($values)) {
  417. foreach ($values as $key => $val) {
  418. if (is_array($val)) {
  419. $vals[] = "'{$key}' => array('" . implode("', '", $val) . "')";
  420. } else if (!is_numeric($key)) {
  421. $val = var_export($val, true);
  422. $vals[] = "'{$key}' => {$val}";
  423. }
  424. }
  425. }
  426. return $vals;
  427. }
  428. /**
  429. * Formats Schema columns from Model Object
  430. *
  431. * @param array $Obj model object
  432. * @return array Formatted columns
  433. * @access public
  434. */
  435. function __columns(&$Obj) {
  436. $db =& ConnectionManager::getDataSource($Obj->useDbConfig);
  437. $fields = $Obj->schema(true);
  438. $columns = $props = array();
  439. foreach ($fields as $name => $value) {
  440. if ($Obj->primaryKey == $name) {
  441. $value['key'] = 'primary';
  442. }
  443. if (!isset($db->columns[$value['type']])) {
  444. trigger_error('Schema generation error: invalid column type ' . $value['type'] . ' does not exist in DBO', E_USER_NOTICE);
  445. continue;
  446. } else {
  447. $defaultCol = $db->columns[$value['type']];
  448. if (isset($defaultCol['limit']) && $defaultCol['limit'] == $value['length']) {
  449. unset($value['length']);
  450. } elseif (isset($defaultCol['length']) && $defaultCol['length'] == $value['length']) {
  451. unset($value['length']);
  452. }
  453. unset($value['limit']);
  454. }
  455. if (isset($value['default']) && ($value['default'] === '' || $value['default'] === false)) {
  456. unset($value['default']);
  457. }
  458. if (empty($value['length'])) {
  459. unset($value['length']);
  460. }
  461. if (empty($value['key'])) {
  462. unset($value['key']);
  463. }
  464. $columns[$name] = $value;
  465. }
  466. return $columns;
  467. }
  468. /**
  469. * Compare two schema indexes
  470. *
  471. * @param array $new New indexes
  472. * @param array $old Old indexes
  473. * @return mixed false on failure or array of indexes to add and drop
  474. */
  475. function _compareIndexes($new, $old) {
  476. if (!is_array($new) || !is_array($old)) {
  477. return false;
  478. }
  479. $add = $drop = array();
  480. $diff = array_diff_assoc($new, $old);
  481. if (!empty($diff)) {
  482. $add = $diff;
  483. }
  484. $diff = array_diff_assoc($old, $new);
  485. if (!empty($diff)) {
  486. $drop = $diff;
  487. }
  488. foreach ($new as $name => $value) {
  489. if (isset($old[$name])) {
  490. $newUnique = isset($value['unique']) ? $value['unique'] : 0;
  491. $oldUnique = isset($old[$name]['unique']) ? $old[$name]['unique'] : 0;
  492. $newColumn = $value['column'];
  493. $oldColumn = $old[$name]['column'];
  494. $diff = false;
  495. if ($newUnique != $oldUnique) {
  496. $diff = true;
  497. } elseif (is_array($newColumn) && is_array($oldColumn)) {
  498. $diff = ($newColumn !== $oldColumn);
  499. } elseif (is_string($newColumn) && is_string($oldColumn)) {
  500. $diff = ($newColumn != $oldColumn);
  501. } else {
  502. $diff = true;
  503. }
  504. if ($diff) {
  505. $drop[$name] = null;
  506. $add[$name] = $value;
  507. }
  508. }
  509. }
  510. return array_filter(compact('add', 'drop'));
  511. }
  512. }
  513. ?>