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: public function generateTable($table, $fields) {
408: $out = "\tpublic \${$table} = array(\n";
409: if (is_array($fields)) {
410: $cols = array();
411: foreach ($fields as $field => $value) {
412: if ($field !== 'indexes' && $field !== 'tableParameters') {
413: if (is_string($value)) {
414: $type = $value;
415: $value = array('type' => $type);
416: }
417: $col = "\t\t'{$field}' => array('type' => '" . $value['type'] . "', ";
418: unset($value['type']);
419: $col .= implode(', ', $this->_values($value));
420: } elseif ($field === 'indexes') {
421: $col = "\t\t'indexes' => array(\n\t\t\t";
422: $props = array();
423: foreach ((array)$value as $key => $index) {
424: $props[] = "'{$key}' => array(" . implode(', ', $this->_values($index)) . ")";
425: }
426: $col .= implode(",\n\t\t\t", $props) . "\n\t\t";
427: } elseif ($field === 'tableParameters') {
428: $col = "\t\t'tableParameters' => array(";
429: $props = array();
430: foreach ((array)$value as $key => $param) {
431: $props[] = "'{$key}' => '$param'";
432: }
433: $col .= implode(', ', $props);
434: }
435: $col .= ")";
436: $cols[] = $col;
437: }
438: $out .= implode(",\n", $cols);
439: }
440: $out .= "\n\t);\n\n";
441: return $out;
442: }
443:
444: 445: 446: 447: 448: 449: 450:
451: public function compare($old, $new = null) {
452: if (empty($new)) {
453: $new = $this;
454: }
455: if (is_array($new)) {
456: if (isset($new['tables'])) {
457: $new = $new['tables'];
458: }
459: } else {
460: $new = $new->tables;
461: }
462:
463: if (is_array($old)) {
464: if (isset($old['tables'])) {
465: $old = $old['tables'];
466: }
467: } else {
468: $old = $old->tables;
469: }
470: $tables = array();
471: foreach ($new as $table => $fields) {
472: if ($table === 'missing') {
473: continue;
474: }
475: if (!array_key_exists($table, $old)) {
476: $tables[$table]['create'] = $fields;
477: } else {
478: $diff = $this->_arrayDiffAssoc($fields, $old[$table]);
479: if (!empty($diff)) {
480: $tables[$table]['add'] = $diff;
481: }
482: $diff = $this->_arrayDiffAssoc($old[$table], $fields);
483: if (!empty($diff)) {
484: $tables[$table]['drop'] = $diff;
485: }
486: }
487:
488: foreach ($fields as $field => $value) {
489: if (!empty($old[$table][$field])) {
490: $diff = $this->_arrayDiffAssoc($value, $old[$table][$field]);
491: if (!empty($diff) && $field !== 'indexes' && $field !== 'tableParameters') {
492: $tables[$table]['change'][$field] = $value;
493: }
494: }
495:
496: if (isset($tables[$table]['add'][$field]) && $field !== 'indexes' && $field !== 'tableParameters') {
497: $wrapper = array_keys($fields);
498: if ($column = array_search($field, $wrapper)) {
499: if (isset($wrapper[$column - 1])) {
500: $tables[$table]['add'][$field]['after'] = $wrapper[$column - 1];
501: }
502: }
503: }
504: }
505:
506: if (isset($old[$table]['indexes']) && isset($new[$table]['indexes'])) {
507: $diff = $this->_compareIndexes($new[$table]['indexes'], $old[$table]['indexes']);
508: if ($diff) {
509: if (!isset($tables[$table])) {
510: $tables[$table] = array();
511: }
512: if (isset($diff['drop'])) {
513: $tables[$table]['drop']['indexes'] = $diff['drop'];
514: }
515: if ($diff && isset($diff['add'])) {
516: $tables[$table]['add']['indexes'] = $diff['add'];
517: }
518: }
519: }
520: if (isset($old[$table]['tableParameters']) && isset($new[$table]['tableParameters'])) {
521: $diff = $this->_compareTableParameters($new[$table]['tableParameters'], $old[$table]['tableParameters']);
522: if ($diff) {
523: $tables[$table]['change']['tableParameters'] = $diff;
524: }
525: }
526: }
527: return $tables;
528: }
529:
530: 531: 532: 533: 534: 535: 536: 537: 538: 539: 540: 541: 542:
543: protected function _arrayDiffAssoc($array1, $array2) {
544: $difference = array();
545: foreach ($array1 as $key => $value) {
546: if (!array_key_exists($key, $array2)) {
547: $difference[$key] = $value;
548: continue;
549: }
550: $correspondingValue = $array2[$key];
551: if (($value === null) !== ($correspondingValue === null)) {
552: $difference[$key] = $value;
553: continue;
554: }
555: if (is_bool($value) !== is_bool($correspondingValue)) {
556: $difference[$key] = $value;
557: continue;
558: }
559: if (is_array($value) && is_array($correspondingValue)) {
560: continue;
561: }
562: if ($value === $correspondingValue) {
563: continue;
564: }
565: $difference[$key] = $value;
566: }
567: return $difference;
568: }
569:
570: 571: 572: 573: 574: 575:
576: protected function _values($values) {
577: $vals = array();
578: if (is_array($values)) {
579: foreach ($values as $key => $val) {
580: if (is_array($val)) {
581: $vals[] = "'{$key}' => array(" . implode(", ", $this->_values($val)) . ")";
582: } else {
583: $val = var_export($val, true);
584: if ($val === 'NULL') {
585: $val = 'null';
586: }
587: if (!is_numeric($key)) {
588: $vals[] = "'{$key}' => {$val}";
589: } else {
590: $vals[] = "{$val}";
591: }
592: }
593: }
594: }
595: return $vals;
596: }
597:
598: 599: 600: 601: 602: 603:
604: protected function _columns(&$Obj) {
605: $db = $Obj->getDataSource();
606: $fields = $Obj->schema(true);
607:
608: $columns = array();
609: foreach ($fields as $name => $value) {
610: if ($Obj->primaryKey === $name) {
611: $value['key'] = 'primary';
612: }
613: if (!isset($db->columns[$value['type']])) {
614: 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);
615: continue;
616: } else {
617: $defaultCol = $db->columns[$value['type']];
618: if (isset($defaultCol['limit']) && $defaultCol['limit'] == $value['length']) {
619: unset($value['length']);
620: } elseif (isset($defaultCol['length']) && $defaultCol['length'] == $value['length']) {
621: unset($value['length']);
622: }
623: unset($value['limit']);
624: }
625:
626: if (isset($value['default']) && ($value['default'] === '' || ($value['default'] === false && $value['type'] !== 'boolean'))) {
627: unset($value['default']);
628: }
629: if (empty($value['length'])) {
630: unset($value['length']);
631: }
632: if (empty($value['key'])) {
633: unset($value['key']);
634: }
635: $columns[$name] = $value;
636: }
637:
638: return $columns;
639: }
640:
641: 642: 643: 644: 645: 646: 647:
648: protected function _compareTableParameters($new, $old) {
649: if (!is_array($new) || !is_array($old)) {
650: return false;
651: }
652: $change = $this->_arrayDiffAssoc($new, $old);
653: return $change;
654: }
655:
656: 657: 658: 659: 660: 661: 662:
663: protected function _compareIndexes($new, $old) {
664: if (!is_array($new) || !is_array($old)) {
665: return false;
666: }
667:
668: $add = $drop = array();
669:
670: $diff = $this->_arrayDiffAssoc($new, $old);
671: if (!empty($diff)) {
672: $add = $diff;
673: }
674:
675: $diff = $this->_arrayDiffAssoc($old, $new);
676: if (!empty($diff)) {
677: $drop = $diff;
678: }
679:
680: foreach ($new as $name => $value) {
681: if (isset($old[$name])) {
682: $newUnique = isset($value['unique']) ? $value['unique'] : 0;
683: $oldUnique = isset($old[$name]['unique']) ? $old[$name]['unique'] : 0;
684: $newColumn = $value['column'];
685: $oldColumn = $old[$name]['column'];
686:
687: $diff = false;
688:
689: if ($newUnique != $oldUnique) {
690: $diff = true;
691: } elseif (is_array($newColumn) && is_array($oldColumn)) {
692: $diff = ($newColumn !== $oldColumn);
693: } elseif (is_string($newColumn) && is_string($oldColumn)) {
694: $diff = ($newColumn != $oldColumn);
695: } else {
696: $diff = true;
697: }
698: if ($diff) {
699: $drop[$name] = null;
700: $add[$name] = $value;
701: }
702: }
703: }
704: return array_filter(compact('add', 'drop'));
705: }
706:
707: 708: 709: 710: 711: 712: 713: 714:
715: protected function _noPrefixTable($prefix, $table) {
716: return preg_replace('/^' . preg_quote($prefix) . '/', '', $table);
717: }
718:
719: 720: 721: 722: 723: 724: 725:
726: protected function _requireFile($path, $file) {
727: if (file_exists($path . DS . $file) && is_file($path . DS . $file)) {
728: require_once $path . DS . $file;
729: return true;
730: } elseif (file_exists($path . DS . 'schema.php') && is_file($path . DS . 'schema.php')) {
731: require_once $path . DS . 'schema.php';
732: return true;
733: }
734: return false;
735: }
736:
737: }
738: