3
* Schema database management for CakePHP.
7
* CakePHP(tm) : Rapid Development Framework (http://cakephp.org)
8
* Copyright 2005-2010, Cake Software Foundation, Inc. (http://cakefoundation.org)
10
* Licensed under The MIT License
11
* Redistributions of files must retain the above copyright notice.
13
* @copyright Copyright 2005-2010, Cake Software Foundation, Inc. (http://cakefoundation.org)
14
* @link http://cakephp.org CakePHP(tm) Project
16
* @subpackage cake.cake.libs.model
17
* @since CakePHP(tm) v 1.2.0.5550
18
* @license MIT License (http://www.opensource.org/licenses/mit-license.php)
20
App::import('Core', array('Model', 'ConnectionManager'));
23
* Base Class for Schema management
26
* @subpackage cake.cake.libs.model
28
class CakeSchema extends Object {
31
* Name of the App Schema
39
* Path to write location
52
var $file = 'schema.php';
55
* Connection used for read
60
var $connection = 'default';
75
var $tables = array();
80
* @param array $options optional load object properties
82
function __construct($options = array()) {
83
parent::__construct();
85
if (empty($options['name'])) {
86
$this->name = preg_replace('/schema$/i', '', get_class($this));
88
if (!empty($options['plugin'])) {
89
$this->plugin = $options['plugin'];
92
if (strtolower($this->name) === 'cake') {
93
$this->name = Inflector::camelize(Inflector::slug(Configure::read('App.dir')));
96
if (empty($options['path'])) {
97
if (is_dir(CONFIGS . 'schema')) {
98
$this->path = CONFIGS . 'schema';
100
$this->path = CONFIGS . 'sql';
104
$options = array_merge(get_object_vars($this), $options);
105
$this->_build($options);
109
* Builds schema object properties
111
* @param array $data loaded object properties
115
function _build($data) {
117
foreach ($data as $key => $val) {
119
if (!in_array($key, array('plugin', 'name', 'path', 'file', 'connection', 'tables', '_log'))) {
120
$this->tables[$key] = $val;
121
unset($this->{$key});
122
} elseif ($key !== 'tables') {
123
if ($key === 'name' && $val !== $this->name && !isset($data['file'])) {
124
$file = Inflector::underscore($val) . '.php';
126
$this->{$key} = $val;
130
if (file_exists($this->path . DS . $file) && is_file($this->path . DS . $file)) {
132
} elseif (!empty($this->plugin)) {
133
$this->path = App::pluginPath($this->plugin) . 'config' . DS . 'schema';
138
* Before callback to be implemented in subclasses
140
* @param array $events schema object properties
141
* @return boolean Should process continue
144
function before($event = array()) {
149
* After callback to be implemented in subclasses
151
* @param array $events schema object properties
154
function after($event = array()) {
158
* Reads database and creates schema tables
160
* @param array $options schema object properties
161
* @return array Set of name and tables
164
function &load($options = array()) {
165
if (is_string($options)) {
166
$options = array('path' => $options);
169
$this->_build($options);
170
extract(get_object_vars($this));
172
$class = $name .'Schema';
174
if (!class_exists($class)) {
175
if (file_exists($path . DS . $file) && is_file($path . DS . $file)) {
176
require_once($path . DS . $file);
177
} elseif (file_exists($path . DS . 'schema.php') && is_file($path . DS . 'schema.php')) {
178
require_once($path . DS . 'schema.php');
182
if (class_exists($class)) {
183
$Schema =& new $class($options);
191
* Reads database and creates schema tables
195
* - 'connection' - the db connection to use
196
* - 'name' - name of the schema
197
* - 'models' - a list of models to use, or false to ignore models
199
* @param array $options schema object properties
200
* @return array Array indexed by name and tables
203
function read($options = array()) {
206
'connection' => $this->connection,
207
'name' => $this->name,
212
$db =& ConnectionManager::getDataSource($connection);
214
App::import('Model', 'AppModel');
215
if (isset($this->plugin)) {
216
App::import('Model', Inflector::camelize($this->plugin) . 'AppModel');
220
$currentTables = $db->listSources();
223
if (isset($db->config['prefix'])) {
224
$prefix = $db->config['prefix'];
227
if (!is_array($models) && $models !== false) {
228
if (isset($this->plugin)) {
229
$models = App::objects('model', App::pluginPath($this->plugin) . 'models' . DS, false);
231
$models = App::objects('model');
235
if (is_array($models)) {
236
foreach ($models as $model) {
237
$importModel = $model;
238
if (isset($this->plugin)) {
239
$importModel = $this->plugin . '.' . $model;
241
if (!App::import('Model', $importModel)) {
244
$vars = get_class_vars($model);
245
if (empty($vars['useDbConfig']) || $vars['useDbConfig'] != $connection) {
250
$Object = ClassRegistry::init(array('class' => $model, 'ds' => $connection));
252
$Object =& ClassRegistry::init(array('class' => $model, 'ds' => $connection));
255
if (is_object($Object) && $Object->useTable !== false) {
256
$fulltable = $table = $db->fullTableName($Object, false);
257
if ($prefix && strpos($table, $prefix) !== 0) {
260
$table = str_replace($prefix, '', $table);
262
if (in_array($fulltable, $currentTables)) {
263
$key = array_search($fulltable, $currentTables);
264
if (empty($tables[$table])) {
265
$tables[$table] = $this->__columns($Object);
266
$tables[$table]['indexes'] = $db->index($Object);
267
$tables[$table]['tableParameters'] = $db->readTableParameters($fulltable);
268
unset($currentTables[$key]);
270
if (!empty($Object->hasAndBelongsToMany)) {
271
foreach ($Object->hasAndBelongsToMany as $Assoc => $assocData) {
272
if (isset($assocData['with'])) {
273
$class = $assocData['with'];
275
if (is_object($Object->$class)) {
276
$withTable = $db->fullTableName($Object->$class, false);
277
if (in_array($withTable, $currentTables)) {
278
$key = array_search($withTable, $currentTables);
279
$tables[$withTable] = $this->__columns($Object->$class);
280
$tables[$withTable]['indexes'] = $db->index($Object->$class);
281
$tables[$withTable]['tableParameters'] = $db->readTableParameters($withTable);
282
unset($currentTables[$key]);
292
if (!empty($currentTables)) {
293
foreach ($currentTables as $table) {
295
if (strpos($table, $prefix) !== 0) {
298
$table = str_replace($prefix, '', $table);
300
$Object = new AppModel(array(
301
'name' => Inflector::classify($table), 'table' => $table, 'ds' => $connection
304
$systemTables = array(
305
'aros', 'acos', 'aros_acos', Configure::read('Session.table'), 'i18n'
308
if (in_array($table, $systemTables)) {
309
$tables[$Object->table] = $this->__columns($Object);
310
$tables[$Object->table]['indexes'] = $db->index($Object);
311
$tables[$Object->table]['tableParameters'] = $db->readTableParameters($table);
312
} elseif ($models === false) {
313
$tables[$table] = $this->__columns($Object);
314
$tables[$table]['indexes'] = $db->index($Object);
315
$tables[$table]['tableParameters'] = $db->readTableParameters($table);
317
$tables['missing'][$table] = $this->__columns($Object);
318
$tables['missing'][$table]['indexes'] = $db->index($Object);
319
$tables['missing'][$table]['tableParameters'] = $db->readTableParameters($table);
325
return compact('name', 'tables');
329
* Writes schema file from object or options
331
* @param mixed $object schema object or options array
332
* @param array $options schema object properties to override object
333
* @return mixed false or string written to file
336
function write($object, $options = array()) {
337
if (is_object($object)) {
338
$object = get_object_vars($object);
339
$this->_build($object);
342
if (is_array($object)) {
348
get_object_vars($this), $options
351
$out = "class {$name}Schema extends CakeSchema {\n";
353
$out .= "\tvar \$name = '{$name}';\n\n";
355
if ($path !== $this->path) {
356
$out .= "\tvar \$path = '{$path}';\n\n";
359
if ($file !== $this->file) {
360
$out .= "\tvar \$file = '{$file}';\n\n";
363
if ($connection !== 'default') {
364
$out .= "\tvar \$connection = '{$connection}';\n\n";
367
$out .= "\tfunction before(\$event = array()) {\n\t\treturn true;\n\t}\n\n\tfunction after(\$event = array()) {\n\t}\n\n";
369
if (empty($tables)) {
373
foreach ($tables as $table => $fields) {
374
if (!is_numeric($table) && $table !== 'missing') {
375
$out .= $this->generateTable($table, $fields);
380
$File =& new File($path . DS . $file, true);
382
$content = "<?php \n/* SVN FILE: {$header}$ */\n/* {$name} schema generated on: " . date('Y-m-d H:m:s') . " : ". time() . "*/\n{$out}?>";
383
$content = $File->prepare($content);
384
if ($File->write($content)) {
391
* Generate the code for a table. Takes a table name and $fields array
392
* Returns a completed variable declaration to be used in schema classes
394
* @param string $table Table name you want returned.
395
* @param array $fields Array of field information to generate the table with.
396
* @return string Variable declaration for a schema class
398
function generateTable($table, $fields) {
399
$out = "\tvar \${$table} = array(\n";
400
if (is_array($fields)) {
402
foreach ($fields as $field => $value) {
403
if ($field != 'indexes' && $field != 'tableParameters') {
404
if (is_string($value)) {
406
$value = array('type'=> $type);
408
$col = "\t\t'{$field}' => array('type' => '" . $value['type'] . "', ";
409
unset($value['type']);
410
$col .= join(', ', $this->__values($value));
411
} elseif ($field == 'indexes') {
412
$col = "\t\t'indexes' => array(";
414
foreach ((array)$value as $key => $index) {
415
$props[] = "'{$key}' => array(" . join(', ', $this->__values($index)) . ")";
417
$col .= join(', ', $props);
418
} elseif ($field == 'tableParameters') {
419
//@todo add charset, collate and engine here
420
$col = "\t\t'tableParameters' => array(";
422
foreach ((array)$value as $key => $param) {
423
$props[] = "'{$key}' => '$param'";
425
$col .= join(', ', $props);
430
$out .= join(",\n", $cols);
437
* Compares two sets of schemas
439
* @param mixed $old Schema object or array
440
* @param mixed $new Schema object or array
441
* @return array Tables (that are added, dropped, or changed)
444
function compare($old, $new = null) {
448
if (is_array($new)) {
449
if (isset($new['tables'])) {
450
$new = $new['tables'];
456
if (is_array($old)) {
457
if (isset($old['tables'])) {
458
$old = $old['tables'];
464
foreach ($new as $table => $fields) {
465
if ($table == 'missing') {
468
if (!array_key_exists($table, $old)) {
469
$tables[$table]['add'] = $fields;
471
$diff = array_diff_assoc($fields, $old[$table]);
473
$tables[$table]['add'] = $diff;
475
$diff = array_diff_assoc($old[$table], $fields);
477
$tables[$table]['drop'] = $diff;
481
foreach ($fields as $field => $value) {
482
if (isset($old[$table][$field])) {
483
$diff = array_diff_assoc($value, $old[$table][$field]);
484
if (!empty($diff) && $field !== 'indexes' && $field !== 'tableParameters') {
485
$tables[$table]['change'][$field] = array_merge($old[$table][$field], $diff);
489
if (isset($add[$table][$field])) {
490
$wrapper = array_keys($fields);
491
if ($column = array_search($field, $wrapper)) {
492
if (isset($wrapper[$column - 1])) {
493
$tables[$table]['add'][$field]['after'] = $wrapper[$column - 1];
499
if (isset($old[$table]['indexes']) && isset($new[$table]['indexes'])) {
500
$diff = $this->_compareIndexes($new[$table]['indexes'], $old[$table]['indexes']);
502
if (!isset($tables[$table])) {
503
$tables[$table] = array();
505
if (isset($diff['drop'])) {
506
$tables[$table]['drop']['indexes'] = $diff['drop'];
508
if ($diff && isset($diff['add'])) {
509
$tables[$table]['add']['indexes'] = $diff['add'];
513
if (isset($old[$table]['tableParameters']) && isset($new[$table]['tableParameters'])) {
514
$diff = $this->_compareTableParameters($new[$table]['tableParameters'], $old[$table]['tableParameters']);
516
$tables[$table]['change']['tableParameters'] = $diff;
524
* Formats Schema columns from Model Object
526
* @param array $values options keys(type, null, default, key, length, extra)
527
* @return array Formatted values
530
function __values($values) {
532
if (is_array($values)) {
533
foreach ($values as $key => $val) {
534
if (is_array($val)) {
535
$vals[] = "'{$key}' => array('" . implode("', '", $val) . "')";
536
} else if (!is_numeric($key)) {
537
$val = var_export($val, true);
538
$vals[] = "'{$key}' => {$val}";
546
* Formats Schema columns from Model Object
548
* @param array $Obj model object
549
* @return array Formatted columns
552
function __columns(&$Obj) {
553
$db =& ConnectionManager::getDataSource($Obj->useDbConfig);
554
$fields = $Obj->schema(true);
555
$columns = $props = array();
556
foreach ($fields as $name => $value) {
557
if ($Obj->primaryKey == $name) {
558
$value['key'] = 'primary';
560
if (!isset($db->columns[$value['type']])) {
561
trigger_error(sprintf(__('Schema generation error: invalid column type %s does not exist in DBO', true), $value['type']), E_USER_NOTICE);
564
$defaultCol = $db->columns[$value['type']];
565
if (isset($defaultCol['limit']) && $defaultCol['limit'] == $value['length']) {
566
unset($value['length']);
567
} elseif (isset($defaultCol['length']) && $defaultCol['length'] == $value['length']) {
568
unset($value['length']);
570
unset($value['limit']);
573
if (isset($value['default']) && ($value['default'] === '' || $value['default'] === false)) {
574
unset($value['default']);
576
if (empty($value['length'])) {
577
unset($value['length']);
579
if (empty($value['key'])) {
580
unset($value['key']);
582
$columns[$name] = $value;
589
* Compare two schema files table Parameters
591
* @param array $new New indexes
592
* @param array $old Old indexes
593
* @return mixed False on failure, or an array of parameters to add & drop.
595
function _compareTableParameters($new, $old) {
596
if (!is_array($new) || !is_array($old)) {
599
$change = array_diff_assoc($new, $old);
604
* Compare two schema indexes
606
* @param array $new New indexes
607
* @param array $old Old indexes
608
* @return mixed false on failure or array of indexes to add and drop
610
function _compareIndexes($new, $old) {
611
if (!is_array($new) || !is_array($old)) {
615
$add = $drop = array();
617
$diff = array_diff_assoc($new, $old);
622
$diff = array_diff_assoc($old, $new);
627
foreach ($new as $name => $value) {
628
if (isset($old[$name])) {
629
$newUnique = isset($value['unique']) ? $value['unique'] : 0;
630
$oldUnique = isset($old[$name]['unique']) ? $old[$name]['unique'] : 0;
631
$newColumn = $value['column'];
632
$oldColumn = $old[$name]['column'];
636
if ($newUnique != $oldUnique) {
638
} elseif (is_array($newColumn) && is_array($oldColumn)) {
639
$diff = ($newColumn !== $oldColumn);
640
} elseif (is_string($newColumn) && is_string($oldColumn)) {
641
$diff = ($newColumn != $oldColumn);
647
$add[$name] = $value;
651
return array_filter(compact('add', 'drop'));