1: <?php
2: 3: 4: 5: 6: 7: 8: 9: 10: 11: 12: 13: 14: 15: 16: 17:
18:
19: App::uses('Model', 'Model');
20: App::uses('AppModel', 'Model');
21: App::uses('ConnectionManager', 'Model');
22: App::uses('File', 'Utility');
23:
24: 25: 26: 27: 28:
29: class CakeSchema extends Object {
30:
31: 32: 33: 34: 35:
36: public $name = null;
37:
38: 39: 40: 41: 42:
43: public $path = null;
44:
45: 46: 47: 48: 49:
50: public $file = 'schema.php';
51:
52: 53: 54: 55: 56:
57: public $connection = 'default';
58:
59: 60: 61: 62: 63:
64: public $plugin = null;
65:
66: 67: 68: 69: 70:
71: public $tables = array();
72:
73: 74: 75: 76: 77:
78: public function __construct($options = array()) {
79: parent::__construct();
80:
81: if (empty($options['name'])) {
82: $this->name = preg_replace('/schema$/i', '', get_class($this));
83: }
84: if (!empty($options['plugin'])) {
85: $this->plugin = $options['plugin'];
86: }
87:
88: if (strtolower($this->name) === 'cake') {
89: $this->name = 'App';
90: }
91:
92: if (empty($options['path'])) {
93: $this->path = APP . 'Config' . DS . 'Schema';
94: }
95:
96: $options = array_merge(get_object_vars($this), $options);
97: $this->build($options);
98: }
99:
100: 101: 102: 103: 104: 105:
106: public function build($data) {
107: $file = null;
108: foreach ($data as $key => $val) {
109: if (!empty($val)) {
110: if (!in_array($key, array('plugin', 'name', 'path', 'file', 'connection', 'tables', '_log'))) {
111: if ($key[0] === '_') {
112: continue;
113: }
114: $this->tables[$key] = $val;
115: unset($this->{$key});
116: } elseif ($key !== 'tables') {
117: if ($key === 'name' && $val !== $this->name && !isset($data['file'])) {
118: $file = Inflector::underscore($val) . '.php';
119: }
120: $this->{$key} = $val;
121: }
122: }
123: }
124: if (file_exists($this->path . DS . $file) && is_file($this->path . DS . $file)) {
125: $this->file = $file;
126: } elseif (!empty($this->plugin)) {
127: $this->path = CakePlugin::path($this->plugin) . 'Config' . DS . 'Schema';
128: }
129: }
130:
131: 132: 133: 134: 135: 136:
137: public function before($event = array()) {
138: return true;
139: }
140:
141: 142: 143: 144: 145: 146:
147: public function after($event = array()) {
148: }
149:
150: 151: 152: 153: 154: 155:
156: public function load($options = array()) {
157: if (is_string($options)) {
158: $options = array('path' => $options);
159: }
160:
161: $this->build($options);
162: extract(get_object_vars($this));
163:
164: $class = $name . 'Schema';
165:
166: if (!class_exists($class) && !$this->_requireFile($path, $file)) {
167: $class = Inflector::camelize(Inflector::slug(Configure::read('App.dir'))) . 'Schema';
168: if (!class_exists($class)) {
169: $this->_requireFile($path, $file);
170: }
171: }
172:
173: if (class_exists($class)) {
174: $Schema = new $class($options);
175: return $Schema;
176: }
177: return false;
178: }
179:
180: 181: 182: 183: 184: 185: 186: 187: 188: 189: 190: 191:
192: public function read($options = array()) {
193: extract(array_merge(
194: array(
195: 'connection' => $this->connection,
196: 'name' => $this->name,
197: 'models' => true,
198: ),
199: $options
200: ));
201: $db = ConnectionManager::getDataSource($connection);
202:
203: if (isset($this->plugin)) {
204: App::uses($this->plugin . 'AppModel', $this->plugin . '.Model');
205: }
206:
207: $tables = array();
208: $currentTables = (array)$db->listSources();
209:
210: $prefix = null;
211: if (isset($db->config['prefix'])) {
212: $prefix = $db->config['prefix'];
213: }
214:
215: if (!is_array($models) && $models !== false) {
216: if (isset($this->plugin)) {
217: $models = App::objects($this->plugin . '.Model', null, false);
218: } else {
219: $models = App::objects('Model');
220: }
221: }
222:
223: if (is_array($models)) {
224: foreach ($models as $model) {
225: $importModel = $model;
226: $plugin = null;
227: if ($model === 'AppModel') {
228: continue;
229: }
230:
231: if (isset($this->plugin)) {
232: if ($model === $this->plugin . 'AppModel') {
233: continue;
234: }
235: $importModel = $model;
236: $plugin = $this->plugin . '.';
237: }
238:
239: App::uses($importModel, $plugin . 'Model');
240: if (!class_exists($importModel)) {
241: continue;
242: }
243:
244: $vars = get_class_vars($model);
245: if (empty($vars['useDbConfig']) || $vars['useDbConfig'] != $connection) {
246: continue;
247: }
248:
249: try {
250: $Object = ClassRegistry::init(array('class' => $model, 'ds' => $connection));
251: } catch (CakeException $e) {
252: continue;
253: }
254:
255: if (!is_object($Object) || $Object->useTable === false) {
256: continue;
257: }
258: $db = $Object->getDataSource();
259:
260: $fulltable = $table = $db->fullTableName($Object, false, false);
261: if ($prefix && strpos($table, $prefix) !== 0) {
262: continue;
263: }
264: if (!in_array($fulltable, $currentTables)) {
265: continue;
266: }
267:
268: $table = $this->_noPrefixTable($prefix, $table);
269:
270: $key = array_search($fulltable, $currentTables);
271: if (empty($tables[$table])) {
272: $tables[$table] = $this->_columns($Object);
273: $tables[$table]['indexes'] = $db->index($Object);
274: $tables[$table]['tableParameters'] = $db->readTableParameters($fulltable);
275: unset($currentTables[$key]);
276: }
277: if (empty($Object->hasAndBelongsToMany)) {
278: continue;
279: }
280: foreach ($Object->hasAndBelongsToMany as $assocData) {
281: if (isset($assocData['with'])) {
282: $class = $assocData['with'];
283: }
284: if (!is_object($Object->$class)) {
285: continue;
286: }
287: $withTable = $db->fullTableName($Object->$class, false, false);
288: if ($prefix && strpos($withTable, $prefix) !== 0) {
289: continue;
290: }
291: if (in_array($withTable, $currentTables)) {
292: $key = array_search($withTable, $currentTables);
293: $noPrefixWith = $this->_noPrefixTable($prefix, $withTable);
294:
295: $tables[$noPrefixWith] = $this->_columns($Object->$class);
296: $tables[$noPrefixWith]['indexes'] = $db->index($Object->$class);
297: $tables[$noPrefixWith]['tableParameters'] = $db->readTableParameters($withTable);
298: unset($currentTables[$key]);
299: }
300: }
301: }
302: }
303:
304: if (!empty($currentTables)) {
305: foreach ($currentTables as $table) {
306: if ($prefix) {
307: if (strpos($table, $prefix) !== 0) {
308: continue;
309: }
310: $table = $this->_noPrefixTable($prefix, $table);
311: }
312: $Object = new AppModel(array(
313: 'name' => Inflector::classify($table), 'table' => $table, 'ds' => $connection
314: ));
315:
316: $systemTables = array(
317: 'aros', 'acos', 'aros_acos', Configure::read('Session.table'), 'i18n'
318: );
319:
320: $fulltable = $db->fullTableName($Object, false, false);
321:
322: if (in_array($table, $systemTables)) {
323: $tables[$Object->table] = $this->_columns($Object);
324: $tables[$Object->table]['indexes'] = $db->index($Object);
325: $tables[$Object->table]['tableParameters'] = $db->readTableParameters($fulltable);
326: } elseif ($models === false) {
327: $tables[$table] = $this->_columns($Object);
328: $tables[$table]['indexes'] = $db->index($Object);
329: $tables[$table]['tableParameters'] = $db->readTableParameters($fulltable);
330: } else {
331: $tables['missing'][$table] = $this->_columns($Object);
332: $tables['missing'][$table]['indexes'] = $db->index($Object);
333: $tables['missing'][$table]['tableParameters'] = $db->readTableParameters($fulltable);
334: }
335: }
336: }
337:
338: ksort($tables);
339: return compact('name', 'tables');
340: }
341:
342: 343: 344: 345: 346: 347: 348:
349: public function write($object, $options = array()) {
350: if (is_object($object)) {
351: $object = get_object_vars($object);
352: $this->build($object);
353: }
354:
355: if (is_array($object)) {
356: $options = $object;
357: unset($object);
358: }
359:
360: extract(array_merge(
361: get_object_vars($this), $options
362: ));
363:
364: $out = "class {$name}Schema extends CakeSchema {\n\n";
365:
366: if ($path !== $this->path) {
367: $out .= "\tpublic \$path = '{$path}';\n\n";
368: }
369:
370: if ($file !== $this->file) {
371: $out .= "\tpublic \$file = '{$file}';\n\n";
372: }
373:
374: if ($connection !== 'default') {
375: $out .= "\tpublic \$connection = '{$connection}';\n\n";
376: }
377:
378: $out .= "\tpublic function before(\$event = array()) {\n\t\treturn true;\n\t}\n\n\tpublic function after(\$event = array()) {\n\t}\n\n";
379:
380: if (empty($tables)) {
381: $this->read();
382: }
383:
384: foreach ($tables as $table => $fields) {
385: if (!is_numeric($table) && $table !== 'missing') {
386: $out .= $this->generateTable($table, $fields);
387: }
388: }
389: $out .= "}\n";
390:
391: $file = new File($path . DS . $file, true);
392: $content = "<?php \n{$out}";
393: if ($file->write($content)) {
394: return $content;
395: }
396: return false;
397: }
398:
399: 400: 401: 402: 403: 404: 405: 406: 407: 408:
409: public function generateTable($table, $fields) {
410: $out = "\tpublic \${$table} = array(\n";
411: if (is_array($fields)) {
412: $cols = array();
413: foreach ($fields as $field => $value) {
414: if ($field !== 'indexes' && $field !== 'tableParameters') {
415: if (is_string($value)) {
416: $type = $value;
417: $value = array('type' => $type);
418: }
419: $col = "\t\t'{$field}' => array('type' => '" . $value['type'] . "', ";
420: unset($value['type']);
421: $col .= implode(', ', $this->_values($value));
422: } elseif ($field === 'indexes') {
423: $col = "\t\t'indexes' => array(\n\t\t\t";
424: $props = array();
425: foreach ((array)$value as $key => $index) {
426: $props[] = "'{$key}' => array(" . implode(', ', $this->_values($index)) . ")";
427: }
428: $col .= implode(",\n\t\t\t", $props) . "\n\t\t";
429: } elseif ($field === 'tableParameters') {
430: $col = "\t\t'tableParameters' => array(";
431: $props = $this->_values($value);
432: $col .= implode(', ', $props);
433: }
434: $col .= ")";
435: $cols[] = $col;
436: }
437: $out .= implode(",\n", $cols);
438: }
439: $out .= "\n\t);\n\n";
440: return $out;
441: }
442:
443: 444: 445: 446: 447: 448: 449:
450: public function compare($old, $new = null) {
451: if (empty($new)) {
452: $new = $this;
453: }
454: if (is_array($new)) {
455: if (isset($new['tables'])) {
456: $new = $new['tables'];
457: }
458: } else {
459: $new = $new->tables;
460: }
461:
462: if (is_array($old)) {
463: if (isset($old['tables'])) {
464: $old = $old['tables'];
465: }
466: } else {
467: $old = $old->tables;
468: }
469: $tables = array();
470: foreach ($new as $table => $fields) {
471: if ($table === 'missing') {
472: continue;
473: }
474: if (!array_key_exists($table, $old)) {
475: $tables[$table]['create'] = $fields;
476: } else {
477: $diff = $this->_arrayDiffAssoc($fields, $old[$table]);
478: if (!empty($diff)) {
479: $tables[$table]['add'] = $diff;
480: }
481: $diff = $this->_arrayDiffAssoc($old[$table], $fields);
482: if (!empty($diff)) {
483: $tables[$table]['drop'] = $diff;
484: }
485: }
486:
487: foreach ($fields as $field => $value) {
488: if (!empty($old[$table][$field])) {
489: $diff = $this->_arrayDiffAssoc($value, $old[$table][$field]);
490: if (empty($diff)) {
491: $diff = $this->_arrayDiffAssoc($old[$table][$field], $value);
492: }
493: if (!empty($diff) && $field !== 'indexes' && $field !== 'tableParameters') {
494: $tables[$table]['change'][$field] = $value;
495: }
496: }
497:
498: if (isset($tables[$table]['add'][$field]) && $field !== 'indexes' && $field !== 'tableParameters') {
499: $wrapper = array_keys($fields);
500: if ($column = array_search($field, $wrapper)) {
501: if (isset($wrapper[$column - 1])) {
502: $tables[$table]['add'][$field]['after'] = $wrapper[$column - 1];
503: }
504: }
505: }
506: }
507:
508: if (isset($old[$table]['indexes']) && isset($new[$table]['indexes'])) {
509: $diff = $this->_compareIndexes($new[$table]['indexes'], $old[$table]['indexes']);
510: if ($diff) {
511: if (!isset($tables[$table])) {
512: $tables[$table] = array();
513: }
514: if (isset($diff['drop'])) {
515: $tables[$table]['drop']['indexes'] = $diff['drop'];
516: }
517: if ($diff && isset($diff['add'])) {
518: $tables[$table]['add']['indexes'] = $diff['add'];
519: }
520: }
521: }
522: if (isset($old[$table]['tableParameters']) && isset($new[$table]['tableParameters'])) {
523: $diff = $this->_compareTableParameters($new[$table]['tableParameters'], $old[$table]['tableParameters']);
524: if ($diff) {
525: $tables[$table]['change']['tableParameters'] = $diff;
526: }
527: }
528: }
529: return $tables;
530: }
531:
532: 533: 534: 535: 536: 537: 538: 539: 540: 541: 542: 543: 544:
545: protected function _arrayDiffAssoc($array1, $array2) {
546: $difference = array();
547: foreach ($array1 as $key => $value) {
548: if (!array_key_exists($key, $array2)) {
549: $difference[$key] = $value;
550: continue;
551: }
552: $correspondingValue = $array2[$key];
553: if (($value === null) !== ($correspondingValue === null)) {
554: $difference[$key] = $value;
555: continue;
556: }
557: if (is_bool($value) !== is_bool($correspondingValue)) {
558: $difference[$key] = $value;
559: continue;
560: }
561: if (is_array($value) && is_array($correspondingValue)) {
562: continue;
563: }
564: if ($value === $correspondingValue) {
565: continue;
566: }
567: $difference[$key] = $value;
568: }
569: return $difference;
570: }
571:
572: 573: 574: 575: 576: 577:
578: protected function _values($values) {
579: $vals = array();
580: if (is_array($values)) {
581: foreach ($values as $key => $val) {
582: if (is_array($val)) {
583: $vals[] = "'{$key}' => array(" . implode(", ", $this->_values($val)) . ")";
584: } else {
585: $val = var_export($val, true);
586: if ($val === 'NULL') {
587: $val = 'null';
588: }
589: if (!is_numeric($key)) {
590: $vals[] = "'{$key}' => {$val}";
591: } else {
592: $vals[] = "{$val}";
593: }
594: }
595: }
596: }
597: return $vals;
598: }
599:
600: 601: 602: 603: 604: 605:
606: protected function _columns(&$Obj) {
607: $db = $Obj->getDataSource();
608: $fields = $Obj->schema(true);
609:
610: $columns = array();
611: foreach ($fields as $name => $value) {
612: if ($Obj->primaryKey === $name) {
613: $value['key'] = 'primary';
614: }
615: if (!isset($db->columns[$value['type']])) {
616: 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);
617: continue;
618: } else {
619: $defaultCol = $db->columns[$value['type']];
620: if (isset($defaultCol['limit']) && $defaultCol['limit'] == $value['length']) {
621: unset($value['length']);
622: } elseif (isset($defaultCol['length']) && $defaultCol['length'] == $value['length']) {
623: unset($value['length']);
624: }
625: unset($value['limit']);
626: }
627:
628: if (isset($value['default']) && ($value['default'] === '' || ($value['default'] === false && $value['type'] !== 'boolean'))) {
629: unset($value['default']);
630: }
631: if (empty($value['length'])) {
632: unset($value['length']);
633: }
634: if (empty($value['key'])) {
635: unset($value['key']);
636: }
637: $columns[$name] = $value;
638: }
639:
640: return $columns;
641: }
642:
643: 644: 645: 646: 647: 648: 649:
650: protected function _compareTableParameters($new, $old) {
651: if (!is_array($new) || !is_array($old)) {
652: return false;
653: }
654: $change = $this->_arrayDiffAssoc($new, $old);
655: return $change;
656: }
657:
658: 659: 660: 661: 662: 663: 664:
665: protected function _compareIndexes($new, $old) {
666: if (!is_array($new) || !is_array($old)) {
667: return false;
668: }
669:
670: $add = $drop = array();
671:
672: $diff = $this->_arrayDiffAssoc($new, $old);
673: if (!empty($diff)) {
674: $add = $diff;
675: }
676:
677: $diff = $this->_arrayDiffAssoc($old, $new);
678: if (!empty($diff)) {
679: $drop = $diff;
680: }
681:
682: foreach ($new as $name => $value) {
683: if (isset($old[$name])) {
684: $newUnique = isset($value['unique']) ? $value['unique'] : 0;
685: $oldUnique = isset($old[$name]['unique']) ? $old[$name]['unique'] : 0;
686: $newColumn = $value['column'];
687: $oldColumn = $old[$name]['column'];
688:
689: $diff = false;
690:
691: if ($newUnique != $oldUnique) {
692: $diff = true;
693: } elseif (is_array($newColumn) && is_array($oldColumn)) {
694: $diff = ($newColumn !== $oldColumn);
695: } elseif (is_string($newColumn) && is_string($oldColumn)) {
696: $diff = ($newColumn != $oldColumn);
697: } else {
698: $diff = true;
699: }
700: if ($diff) {
701: $drop[$name] = null;
702: $add[$name] = $value;
703: }
704: }
705: }
706: return array_filter(compact('add', 'drop'));
707: }
708:
709: 710: 711: 712: 713: 714: 715: 716:
717: protected function _noPrefixTable($prefix, $table) {
718: return preg_replace('/^' . preg_quote($prefix) . '/', '', $table);
719: }
720:
721: 722: 723: 724: 725: 726: 727:
728: protected function _requireFile($path, $file) {
729: if (file_exists($path . DS . $file) && is_file($path . DS . $file)) {
730: require_once $path . DS . $file;
731: return true;
732: } elseif (file_exists($path . DS . 'schema.php') && is_file($path . DS . 'schema.php')) {
733: require_once $path . DS . 'schema.php';
734: return true;
735: }
736: return false;
737: }
738:
739: }
740: