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 = Inflector::camelize(Inflector::slug(Configure::read('App.dir')));
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)) {
167: if (file_exists($path . DS . $file) && is_file($path . DS . $file)) {
168: require_once $path . DS . $file;
169: } elseif (file_exists($path . DS . 'schema.php') && is_file($path . DS . 'schema.php')) {
170: require_once $path . DS . 'schema.php';
171: }
172: }
173:
174: if (class_exists($class)) {
175: $Schema = new $class($options);
176: return $Schema;
177: }
178: return false;
179: }
180:
181: 182: 183: 184: 185: 186: 187: 188: 189: 190: 191: 192:
193: public function read($options = array()) {
194: extract(array_merge(
195: array(
196: 'connection' => $this->connection,
197: 'name' => $this->name,
198: 'models' => true,
199: ),
200: $options
201: ));
202: $db = ConnectionManager::getDataSource($connection);
203:
204: if (isset($this->plugin)) {
205: App::uses($this->plugin . 'AppModel', $this->plugin . '.Model');
206: }
207:
208: $tables = array();
209: $currentTables = (array)$db->listSources();
210:
211: $prefix = null;
212: if (isset($db->config['prefix'])) {
213: $prefix = $db->config['prefix'];
214: }
215:
216: if (!is_array($models) && $models !== false) {
217: if (isset($this->plugin)) {
218: $models = App::objects($this->plugin . '.Model', null, false);
219: } else {
220: $models = App::objects('Model');
221: }
222: }
223:
224: if (is_array($models)) {
225: foreach ($models as $model) {
226: $importModel = $model;
227: $plugin = null;
228: if ($model === 'AppModel') {
229: continue;
230: }
231:
232: if (isset($this->plugin)) {
233: if ($model === $this->plugin . 'AppModel') {
234: continue;
235: }
236: $importModel = $model;
237: $plugin = $this->plugin . '.';
238: }
239:
240: App::uses($importModel, $plugin . 'Model');
241: if (!class_exists($importModel)) {
242: continue;
243: }
244:
245: $vars = get_class_vars($model);
246: if (empty($vars['useDbConfig']) || $vars['useDbConfig'] != $connection) {
247: continue;
248: }
249:
250: try {
251: $Object = ClassRegistry::init(array('class' => $model, 'ds' => $connection));
252: } catch (CakeException $e) {
253: continue;
254: }
255:
256: if (!is_object($Object) || $Object->useTable === false) {
257: continue;
258: }
259: $db = $Object->getDataSource();
260:
261: $fulltable = $table = $db->fullTableName($Object, false, false);
262: if ($prefix && strpos($table, $prefix) !== 0) {
263: continue;
264: }
265: if (!in_array($fulltable, $currentTables)) {
266: continue;
267: }
268:
269: $table = $this->_noPrefixTable($prefix, $table);
270:
271: $key = array_search($fulltable, $currentTables);
272: if (empty($tables[$table])) {
273: $tables[$table] = $this->_columns($Object);
274: $tables[$table]['indexes'] = $db->index($Object);
275: $tables[$table]['tableParameters'] = $db->readTableParameters($fulltable);
276: unset($currentTables[$key]);
277: }
278: if (empty($Object->hasAndBelongsToMany)) {
279: continue;
280: }
281: foreach ($Object->hasAndBelongsToMany as $assocData) {
282: if (isset($assocData['with'])) {
283: $class = $assocData['with'];
284: }
285: if (!is_object($Object->$class)) {
286: continue;
287: }
288: $withTable = $db->fullTableName($Object->$class, false, false);
289: if ($prefix && strpos($withTable, $prefix) !== 0) {
290: continue;
291: }
292: if (in_array($withTable, $currentTables)) {
293: $key = array_search($withTable, $currentTables);
294: $noPrefixWith = $this->_noPrefixTable($prefix, $withTable);
295:
296: $tables[$noPrefixWith] = $this->_columns($Object->$class);
297: $tables[$noPrefixWith]['indexes'] = $db->index($Object->$class);
298: $tables[$noPrefixWith]['tableParameters'] = $db->readTableParameters($withTable);
299: unset($currentTables[$key]);
300: }
301: }
302: }
303: }
304:
305: if (!empty($currentTables)) {
306: foreach ($currentTables as $table) {
307: if ($prefix) {
308: if (strpos($table, $prefix) !== 0) {
309: continue;
310: }
311: $table = $this->_noPrefixTable($prefix, $table);
312: }
313: $Object = new AppModel(array(
314: 'name' => Inflector::classify($table), 'table' => $table, 'ds' => $connection
315: ));
316:
317: $systemTables = array(
318: 'aros', 'acos', 'aros_acos', Configure::read('Session.table'), 'i18n'
319: );
320:
321: $fulltable = $db->fullTableName($Object, false, false);
322:
323: if (in_array($table, $systemTables)) {
324: $tables[$Object->table] = $this->_columns($Object);
325: $tables[$Object->table]['indexes'] = $db->index($Object);
326: $tables[$Object->table]['tableParameters'] = $db->readTableParameters($fulltable);
327: } elseif ($models === false) {
328: $tables[$table] = $this->_columns($Object);
329: $tables[$table]['indexes'] = $db->index($Object);
330: $tables[$table]['tableParameters'] = $db->readTableParameters($fulltable);
331: } else {
332: $tables['missing'][$table] = $this->_columns($Object);
333: $tables['missing'][$table]['indexes'] = $db->index($Object);
334: $tables['missing'][$table]['tableParameters'] = $db->readTableParameters($fulltable);
335: }
336: }
337: }
338:
339: ksort($tables);
340: return compact('name', 'tables');
341: }
342:
343: 344: 345: 346: 347: 348: 349:
350: public function write($object, $options = array()) {
351: if (is_object($object)) {
352: $object = get_object_vars($object);
353: $this->build($object);
354: }
355:
356: if (is_array($object)) {
357: $options = $object;
358: unset($object);
359: }
360:
361: extract(array_merge(
362: get_object_vars($this), $options
363: ));
364:
365: $out = "class {$name}Schema extends CakeSchema {\n\n";
366:
367: if ($path !== $this->path) {
368: $out .= "\tpublic \$path = '{$path}';\n\n";
369: }
370:
371: if ($file !== $this->file) {
372: $out .= "\tpublic \$file = '{$file}';\n\n";
373: }
374:
375: if ($connection !== 'default') {
376: $out .= "\tpublic \$connection = '{$connection}';\n\n";
377: }
378:
379: $out .= "\tpublic function before(\$event = array()) {\n\t\treturn true;\n\t}\n\n\tpublic function after(\$event = array()) {\n\t}\n\n";
380:
381: if (empty($tables)) {
382: $this->read();
383: }
384:
385: foreach ($tables as $table => $fields) {
386: if (!is_numeric($table) && $table !== 'missing') {
387: $out .= $this->generateTable($table, $fields);
388: }
389: }
390: $out .= "}\n";
391:
392: $file = new File($path . DS . $file, true);
393: $content = "<?php \n{$out}";
394: if ($file->write($content)) {
395: return $content;
396: }
397: return false;
398: }
399:
400: 401: 402: 403: 404: 405: 406: 407:
408: public function generateTable($table, $fields) {
409: $out = "\tpublic \${$table} = array(\n";
410: if (is_array($fields)) {
411: $cols = array();
412: foreach ($fields as $field => $value) {
413: if ($field !== 'indexes' && $field !== 'tableParameters') {
414: if (is_string($value)) {
415: $type = $value;
416: $value = array('type' => $type);
417: }
418: $col = "\t\t'{$field}' => array('type' => '" . $value['type'] . "', ";
419: unset($value['type']);
420: $col .= implode(', ', $this->_values($value));
421: } elseif ($field === 'indexes') {
422: $col = "\t\t'indexes' => array(\n\t\t\t";
423: $props = array();
424: foreach ((array)$value as $key => $index) {
425: $props[] = "'{$key}' => array(" . implode(', ', $this->_values($index)) . ")";
426: }
427: $col .= implode(",\n\t\t\t", $props) . "\n\t\t";
428: } elseif ($field === 'tableParameters') {
429: $col = "\t\t'tableParameters' => array(";
430: $props = array();
431: foreach ((array)$value as $key => $param) {
432: $props[] = "'{$key}' => '$param'";
433: }
434: $col .= implode(', ', $props);
435: }
436: $col .= ")";
437: $cols[] = $col;
438: }
439: $out .= implode(",\n", $cols);
440: }
441: $out .= "\n\t);\n\n";
442: return $out;
443: }
444:
445: 446: 447: 448: 449: 450: 451:
452: public function compare($old, $new = null) {
453: if (empty($new)) {
454: $new = $this;
455: }
456: if (is_array($new)) {
457: if (isset($new['tables'])) {
458: $new = $new['tables'];
459: }
460: } else {
461: $new = $new->tables;
462: }
463:
464: if (is_array($old)) {
465: if (isset($old['tables'])) {
466: $old = $old['tables'];
467: }
468: } else {
469: $old = $old->tables;
470: }
471: $tables = array();
472: foreach ($new as $table => $fields) {
473: if ($table === 'missing') {
474: continue;
475: }
476: if (!array_key_exists($table, $old)) {
477: $tables[$table]['create'] = $fields;
478: } else {
479: $diff = $this->_arrayDiffAssoc($fields, $old[$table]);
480: if (!empty($diff)) {
481: $tables[$table]['add'] = $diff;
482: }
483: $diff = $this->_arrayDiffAssoc($old[$table], $fields);
484: if (!empty($diff)) {
485: $tables[$table]['drop'] = $diff;
486: }
487: }
488:
489: foreach ($fields as $field => $value) {
490: if (!empty($old[$table][$field])) {
491: $diff = $this->_arrayDiffAssoc($value, $old[$table][$field]);
492: if (!empty($diff) && $field !== 'indexes' && $field !== 'tableParameters') {
493: $tables[$table]['change'][$field] = $value;
494: }
495: }
496:
497: if (isset($tables[$table]['add'][$field]) && $field !== 'indexes' && $field !== 'tableParameters') {
498: $wrapper = array_keys($fields);
499: if ($column = array_search($field, $wrapper)) {
500: if (isset($wrapper[$column - 1])) {
501: $tables[$table]['add'][$field]['after'] = $wrapper[$column - 1];
502: }
503: }
504: }
505: }
506:
507: if (isset($old[$table]['indexes']) && isset($new[$table]['indexes'])) {
508: $diff = $this->_compareIndexes($new[$table]['indexes'], $old[$table]['indexes']);
509: if ($diff) {
510: if (!isset($tables[$table])) {
511: $tables[$table] = array();
512: }
513: if (isset($diff['drop'])) {
514: $tables[$table]['drop']['indexes'] = $diff['drop'];
515: }
516: if ($diff && isset($diff['add'])) {
517: $tables[$table]['add']['indexes'] = $diff['add'];
518: }
519: }
520: }
521: if (isset($old[$table]['tableParameters']) && isset($new[$table]['tableParameters'])) {
522: $diff = $this->_compareTableParameters($new[$table]['tableParameters'], $old[$table]['tableParameters']);
523: if ($diff) {
524: $tables[$table]['change']['tableParameters'] = $diff;
525: }
526: }
527: }
528: return $tables;
529: }
530:
531: 532: 533: 534: 535: 536: 537: 538: 539: 540: 541: 542: 543:
544: protected function _arrayDiffAssoc($array1, $array2) {
545: $difference = array();
546: foreach ($array1 as $key => $value) {
547: if (!array_key_exists($key, $array2)) {
548: $difference[$key] = $value;
549: continue;
550: }
551: $correspondingValue = $array2[$key];
552: if (($value === null) !== ($correspondingValue === null)) {
553: $difference[$key] = $value;
554: continue;
555: }
556: if (is_bool($value) !== is_bool($correspondingValue)) {
557: $difference[$key] = $value;
558: continue;
559: }
560: if (is_array($value) && is_array($correspondingValue)) {
561: continue;
562: }
563: if ($value === $correspondingValue) {
564: continue;
565: }
566: $difference[$key] = $value;
567: }
568: return $difference;
569: }
570:
571: 572: 573: 574: 575: 576:
577: protected function _values($values) {
578: $vals = array();
579: if (is_array($values)) {
580: foreach ($values as $key => $val) {
581: if (is_array($val)) {
582: $vals[] = "'{$key}' => array(" . implode(", ", $this->_values($val)) . ")";
583: } else {
584: $val = var_export($val, true);
585: if ($val === 'NULL') {
586: $val = 'null';
587: }
588: if (!is_numeric($key)) {
589: $vals[] = "'{$key}' => {$val}";
590: } else {
591: $vals[] = "{$val}";
592: }
593: }
594: }
595: }
596: return $vals;
597: }
598:
599: 600: 601: 602: 603: 604:
605: protected function _columns(&$Obj) {
606: $db = $Obj->getDataSource();
607: $fields = $Obj->schema(true);
608:
609: $columns = array();
610: foreach ($fields as $name => $value) {
611: if ($Obj->primaryKey === $name) {
612: $value['key'] = 'primary';
613: }
614: if (!isset($db->columns[$value['type']])) {
615: 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);
616: continue;
617: } else {
618: $defaultCol = $db->columns[$value['type']];
619: if (isset($defaultCol['limit']) && $defaultCol['limit'] == $value['length']) {
620: unset($value['length']);
621: } elseif (isset($defaultCol['length']) && $defaultCol['length'] == $value['length']) {
622: unset($value['length']);
623: }
624: unset($value['limit']);
625: }
626:
627: if (isset($value['default']) && ($value['default'] === '' || ($value['default'] === false && $value['type'] !== 'boolean'))) {
628: unset($value['default']);
629: }
630: if (empty($value['length'])) {
631: unset($value['length']);
632: }
633: if (empty($value['key'])) {
634: unset($value['key']);
635: }
636: $columns[$name] = $value;
637: }
638:
639: return $columns;
640: }
641:
642: 643: 644: 645: 646: 647: 648:
649: protected function _compareTableParameters($new, $old) {
650: if (!is_array($new) || !is_array($old)) {
651: return false;
652: }
653: $change = $this->_arrayDiffAssoc($new, $old);
654: return $change;
655: }
656:
657: 658: 659: 660: 661: 662: 663:
664: protected function _compareIndexes($new, $old) {
665: if (!is_array($new) || !is_array($old)) {
666: return false;
667: }
668:
669: $add = $drop = array();
670:
671: $diff = $this->_arrayDiffAssoc($new, $old);
672: if (!empty($diff)) {
673: $add = $diff;
674: }
675:
676: $diff = $this->_arrayDiffAssoc($old, $new);
677: if (!empty($diff)) {
678: $drop = $diff;
679: }
680:
681: foreach ($new as $name => $value) {
682: if (isset($old[$name])) {
683: $newUnique = isset($value['unique']) ? $value['unique'] : 0;
684: $oldUnique = isset($old[$name]['unique']) ? $old[$name]['unique'] : 0;
685: $newColumn = $value['column'];
686: $oldColumn = $old[$name]['column'];
687:
688: $diff = false;
689:
690: if ($newUnique != $oldUnique) {
691: $diff = true;
692: } elseif (is_array($newColumn) && is_array($oldColumn)) {
693: $diff = ($newColumn !== $oldColumn);
694: } elseif (is_string($newColumn) && is_string($oldColumn)) {
695: $diff = ($newColumn != $oldColumn);
696: } else {
697: $diff = true;
698: }
699: if ($diff) {
700: $drop[$name] = null;
701: $add[$name] = $value;
702: }
703: }
704: }
705: return array_filter(compact('add', 'drop'));
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: