Subversion-Projekte lars-tiefland.cakephp

Revision

Details | Letzte Änderung | Log anzeigen | RSS feed

Revision Autor Zeilennr. Zeile
1 lars 1
<?php
2
/* SVN FILE: $Id: schema.php 7945 2008-12-19 02:16:01Z gwoo $ */
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-2008, 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-2008, 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: 7945 $
21
 * @modifiedby    $LastChangedBy: gwoo $
22
 * @lastmodified  $Date: 2008-12-18 18:16:01 -0800 (Thu, 18 Dec 2008) $
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
 
76
		if (empty($options['name'])) {
77
			$this->name = preg_replace('/schema$/i', '', get_class($this));
78
		}
79
 
80
		if (strtolower($this->name) === 'cake') {
81
			$this->name = Inflector::camelize(Inflector::slug(Configure::read('App.dir')));
82
		}
83
 
84
		if (empty($options['path'])) {
85
			$this->path = CONFIGS . 'sql';
86
		}
87
 
88
		$options = array_merge(get_object_vars($this), $options);
89
		$this->_build($options);
90
	}
91
/**
92
 * Builds schema object properties
93
 *
94
 * @param array $data loaded object properties
95
 * @return void
96
 * @access protected
97
 */
98
	function _build($data) {
99
		$file = null;
100
		foreach ($data as $key => $val) {
101
			if (!empty($val)) {
102
				if (!in_array($key, array('name', 'path', 'file', 'connection', 'tables', '_log'))) {
103
					$this->tables[$key] = $val;
104
					unset($this->{$key});
105
				} elseif ($key !== 'tables') {
106
					if ($key === 'name' && $val !== $this->name && !isset($data['file'])) {
107
						$file = Inflector::underscore($val) . '.php';
108
					}
109
					$this->{$key} = $val;
110
				}
111
			}
112
		}
113
 
114
		if (file_exists($this->path . DS . $file) && is_file($this->path . DS . $file)) {
115
			$this->file = $file;
116
		}
117
	}
118
/**
119
 * Before callback to be implemented in subclasses
120
 *
121
 * @param array $events schema object properties
122
 * @return boolean Should process continue
123
 * @access public
124
 */
125
	function before($event = array()) {
126
		return true;
127
	}
128
/**
129
 * After callback to be implemented in subclasses
130
 *
131
 * @param array $events schema object properties
132
 * @access public
133
 */
134
	function after($event = array()) {
135
	}
136
/**
137
 * Reads database and creates schema tables
138
 *
139
 * @param array $options schema object properties
140
 * @return array Set of name and tables
141
 * @access public
142
 */
143
	function load($options = array()) {
144
		if (is_string($options)) {
145
			$options = array('path' => $options);
146
		}
147
 
148
		$this->_build($options);
149
		extract(get_object_vars($this));
150
 
151
		$class =  $name .'Schema';
152
		if (!class_exists($class)) {
153
			if (file_exists($path . DS . $file) && is_file($path . DS . $file)) {
154
				require_once($path . DS . $file);
155
			} elseif (file_exists($path . DS . 'schema.php') && is_file($path . DS . 'schema.php')) {
156
				require_once($path . DS . 'schema.php');
157
			}
158
		}
159
 
160
		if (class_exists($class)) {
161
			$Schema =& new $class($options);
162
			return $Schema;
163
		}
164
 
165
		return false;
166
	}
167
/**
168
 * Reads database and creates schema tables
169
 *
170
 * @param array $options schema object properties
171
 *		'connection' - the db connection to use
172
 *		'name' - name of the schema
173
 *		'models' - a list of models to use, or false to ignore models
174
 * @return array Array indexed by name and tables
175
 * @access public
176
 */
177
	function read($options = array()) {
178
		extract(array_merge(
179
			array(
180
				'connection' => $this->connection,
181
				'name' => $this->name,
182
				'models' => true,
183
			),
184
			$options
185
		));
186
		$db =& ConnectionManager::getDataSource($connection);
187
 
188
		App::import('Model', 'AppModel');
189
 
190
		$tables = array();
191
		$currentTables = $db->listSources();
192
 
193
		$prefix = null;
194
		if (isset($db->config['prefix'])) {
195
			$prefix = $db->config['prefix'];
196
		}
197
 
198
		if (!is_array($models) && $models !== false) {
199
			$models = Configure::listObjects('model');
200
		}
201
 
202
		if (is_array($models)) {
203
			foreach ($models as $model) {
204
				if (PHP5) {
205
					$Object = ClassRegistry::init(array('class' => $model, 'ds' => $connection));
206
				} else {
207
					$Object =& ClassRegistry::init(array('class' => $model, 'ds' => $connection));
208
				}
209
 
210
				if (is_object($Object) && $Object->useTable !== false) {
211
					$Object->setDataSource($connection);
212
					$table = $db->fullTableName($Object, false);
213
 
214
					if (in_array($table, $currentTables)) {
215
						$key = array_search($table, $currentTables);
216
						if (empty($tables[$Object->table])) {
217
							$tables[$Object->table] = $this->__columns($Object);
218
							$tables[$Object->table]['indexes'] = $db->index($Object);
219
							unset($currentTables[$key]);
220
						}
221
						if (!empty($Object->hasAndBelongsToMany)) {
222
							foreach ($Object->hasAndBelongsToMany as $Assoc => $assocData) {
223
								if (isset($assocData['with'])) {
224
									$class = $assocData['with'];
225
								} elseif ($assocData['_with']) {
226
									$class = $assocData['_with'];
227
								}
228
								if (is_object($Object->$class)) {
229
									$table = $db->fullTableName($Object->$class, false);
230
									if (in_array($table, $currentTables)) {
231
										$key = array_search($table, $currentTables);
232
										$tables[$Object->$class->table] = $this->__columns($Object->$class);
233
										$tables[$Object->$class->table]['indexes'] = $db->index($Object->$class);
234
										unset($currentTables[$key]);
235
									}
236
								}
237
							}
238
						}
239
					}
240
				}
241
			}
242
		}
243
 
244
		if (!empty($currentTables)) {
245
			foreach ($currentTables as $table) {
246
				if ($prefix) {
247
					if (strpos($table, $prefix) !== 0) {
248
						continue;
249
					}
250
					$table = str_replace($prefix, '', $table);
251
				}
252
				$Object = new AppModel(array(
253
					'name' => Inflector::classify($table), 'table' => $table, 'ds' => $connection
254
				));
255
 
256
				$systemTables = array(
257
					'aros', 'acos', 'aros_acos', Configure::read('Session.table'), 'i18n'
258
				);
259
 
260
				if (in_array($table, $systemTables)) {
261
					$tables[$Object->table] = $this->__columns($Object);
262
					$tables[$Object->table]['indexes'] = $db->index($Object);
263
				} elseif ($models === false) {
264
					$tables[$table] = $this->__columns($Object);
265
					$tables[$table]['indexes'] = $db->index($Object);
266
				} else {
267
					$tables['missing'][$table] = $this->__columns($Object);
268
					$tables['missing'][$table]['indexes'] = $db->index($Object);
269
				}
270
			}
271
		}
272
 
273
		ksort($tables);
274
		return compact('name', 'tables');
275
	}
276
/**
277
 * Writes schema file from object or options
278
 *
279
 * @param mixed $object schema object or options array
280
 * @param array $options schema object properties to override object
281
 * @return mixed false or string written to file
282
 * @access public
283
 */
284
	function write($object, $options = array()) {
285
		if (is_object($object)) {
286
			$object = get_object_vars($object);
287
			$this->_build($object);
288
		}
289
 
290
		if (is_array($object)) {
291
			$options = $object;
292
			unset($object);
293
		}
294
 
295
		extract(array_merge(
296
			get_object_vars($this), $options
297
		));
298
 
299
		$out = "class {$name}Schema extends CakeSchema {\n";
300
 
301
		$out .= "\tvar \$name = '{$name}';\n\n";
302
 
303
		if ($path !== $this->path) {
304
			$out .= "\tvar \$path = '{$path}';\n\n";
305
		}
306
 
307
		if ($file !== $this->file) {
308
			$out .= "\tvar \$file = '{$file}';\n\n";
309
		}
310
 
311
		if ($connection !== 'default') {
312
			$out .= "\tvar \$connection = '{$connection}';\n\n";
313
		}
314
 
315
		$out .= "\tfunction before(\$event = array()) {\n\t\treturn true;\n\t}\n\n\tfunction after(\$event = array()) {\n\t}\n\n";
316
 
317
		if (empty($tables)) {
318
			$this->read();
319
		}
320
 
321
		foreach ($tables as $table => $fields) {
322
			if (!is_numeric($table) && $table !== 'missing') {
323
				$out .= "\tvar \${$table} = array(\n";
324
				if (is_array($fields)) {
325
					$cols = array();
326
					foreach ($fields as $field => $value) {
327
						if ($field != 'indexes') {
328
							if (is_string($value)) {
329
								$type = $value;
330
								$value = array('type'=> $type);
331
							}
332
							$col = "\t\t\t'{$field}' => array('type' => '" . $value['type'] . "', ";
333
							unset($value['type']);
334
							$col .= join(', ',  $this->__values($value));
335
						} else {
336
							$col = "\t\t\t'indexes' => array(";
337
							$props = array();
338
							foreach ((array)$value as $key => $index) {
339
								$props[] = "'{$key}' => array(".join(', ',  $this->__values($index)).")";
340
							}
341
							$col .= join(', ', $props);
342
						}
343
						$col .= ")";
344
						$cols[] = $col;
345
					}
346
					$out .= join(",\n", $cols);
347
				}
348
				$out .= "\n\t\t);\n";
349
			}
350
		}
351
		$out .="}\n";
352
 
353
 
354
		$File =& new File($path . DS . $file, true);
355
		$header = '$Id';
356
		$content = "<?php \n/* SVN FILE: $header$ */\n/* ". $name ." schema generated on: " . date('Y-m-d H:m:s') . " : ". time() . "*/\n{$out}?>";
357
		$content = $File->prepare($content);
358
		if ($File->write($content)) {
359
			return $content;
360
		}
361
		return false;
362
	}
363
/**
364
 * Compares two sets of schemas
365
 *
366
 * @param mixed $old Schema object or array
367
 * @param mixed $new Schema object or array
368
 * @return array Tables (that are added, dropped, or changed)
369
 * @access public
370
 */
371
	function compare($old, $new = null) {
372
		if (empty($new)) {
373
			$new = $this;
374
		}
375
		if (is_array($new)) {
376
			if (isset($new['tables'])) {
377
				$new = $new['tables'];
378
			}
379
		} else {
380
			$new = $new->tables;
381
		}
382
 
383
		if (is_array($old)) {
384
			if (isset($old['tables'])) {
385
				$old = $old['tables'];
386
			}
387
		} else {
388
			$old = $old->tables;
389
		}
390
		$tables = array();
391
		foreach ($new as $table => $fields) {
392
			if ($table == 'missing') {
393
				break;
394
			}
395
			if (!array_key_exists($table, $old)) {
396
				$tables[$table]['add'] = $fields;
397
			} else {
398
				$diff = array_diff_assoc($fields, $old[$table]);
399
				if (!empty($diff)) {
400
					$tables[$table]['add'] = $diff;
401
				}
402
				$diff = array_diff_assoc($old[$table], $fields);
403
				if (!empty($diff)) {
404
					$tables[$table]['drop'] = $diff;
405
				}
406
			}
407
			foreach ($fields as $field => $value) {
408
				if (isset($old[$table][$field])) {
409
					$diff = array_diff_assoc($value, $old[$table][$field]);
410
					if (!empty($diff) && $field !== 'indexes') {
411
						$tables[$table]['change'][$field] = array_merge($old[$table][$field], $diff);
412
					}
413
				}
414
 
415
				if (isset($add[$table][$field])) {
416
					$wrapper = array_keys($fields);
417
					if ($column = array_search($field, $wrapper)) {
418
						if (isset($wrapper[$column - 1])) {
419
							$tables[$table]['add'][$field]['after'] = $wrapper[$column - 1];
420
						}
421
					}
422
				}
423
			}
424
 
425
			if (isset($old[$table]['indexes']) && isset($new[$table]['indexes'])) {
426
				$diff = $this->_compareIndexes($new[$table]['indexes'], $old[$table]['indexes']);
427
				if ($diff) {
428
					$tables[$table]['drop']['indexes'] = $diff['drop'];
429
					$tables[$table]['add']['indexes'] = $diff['add'];
430
				}
431
			}
432
		}
433
		return $tables;
434
	}
435
/**
436
 * Formats Schema columns from Model Object
437
 *
438
 * @param array $values options keys(type, null, default, key, length, extra)
439
 * @return array Formatted values
440
 * @access public
441
 */
442
	function __values($values) {
443
		$vals = array();
444
		if (is_array($values)) {
445
			foreach ($values as $key => $val) {
446
				if (is_array($val)) {
447
					$vals[] = "'{$key}' => array('".join("', '",  $val)."')";
448
				} else if (!is_numeric($key)) {
449
					$val = var_export($val, true);
450
					$vals[] = "'{$key}' => {$val}";
451
				}
452
			}
453
		}
454
		return $vals;
455
	}
456
/**
457
 * Formats Schema columns from Model Object
458
 *
459
 * @param array $Obj model object
460
 * @return array Formatted columns
461
 * @access public
462
 */
463
	function __columns(&$Obj) {
464
		$db =& ConnectionManager::getDataSource($Obj->useDbConfig);
465
		$fields = $Obj->schema(true);
466
		$columns = $props = array();
467
		foreach ($fields as $name => $value) {
468
			if ($Obj->primaryKey == $name) {
469
				$value['key'] = 'primary';
470
			}
471
			if (!isset($db->columns[$value['type']])) {
472
				trigger_error('Schema generation error: invalid column type ' . $value['type'] . ' does not exist in DBO', E_USER_NOTICE);
473
				continue;
474
			} else {
475
				$defaultCol = $db->columns[$value['type']];
476
				if (isset($defaultCol['limit']) && $defaultCol['limit'] == $value['length']) {
477
					unset($value['length']);
478
				} elseif (isset($defaultCol['length']) && $defaultCol['length'] == $value['length']) {
479
					unset($value['length']);
480
				}
481
				unset($value['limit']);
482
			}
483
 
484
			if (isset($value['default']) && ($value['default'] === '' || $value['default'] === false)) {
485
				unset($value['default']);
486
			}
487
			if (empty($value['length'])) {
488
				unset($value['length']);
489
			}
490
			if (empty($value['key'])) {
491
				unset($value['key']);
492
			}
493
			$columns[$name] = $value;
494
		}
495
 
496
		return $columns;
497
	}
498
/**
499
 * Compare two schema indexes
500
 *
501
 * @param array $new New indexes
502
 * @param array $old Old indexes
503
 * @return mixed false on failure or array of indexes to add and drop
504
 */
505
	function _compareIndexes($new, $old) {
506
		if (!is_array($new) || !is_array($old)) {
507
			return false;
508
		}
509
 
510
		$add = $drop = array();
511
 
512
		$diff = array_diff_assoc($new, $old);
513
		if (!empty($diff)) {
514
			$add = $diff;
515
		}
516
 
517
		$diff = array_diff_assoc($old, $new);
518
		if (!empty($diff)) {
519
			$drop = $diff;
520
		}
521
 
522
		foreach ($new as $name => $value) {
523
			if (isset($old[$name])) {
524
				$newUnique = isset($value['unique']) ? $value['unique'] : 0;
525
				$oldUnique = isset($old[$name]['unique']) ? $old[$name]['unique'] : 0;
526
				$newColumn = $value['column'];
527
				$oldColumn = $old[$name]['column'];
528
 
529
				$diff = false;
530
 
531
				if ($newUnique != $oldUnique) {
532
					$diff = true;
533
				} elseif (is_array($newColumn) && is_array($oldColumn)) {
534
					$diff = ($newColumn !== $oldColumn);
535
				} elseif (is_string($newColumn) && is_string($oldColumn)) {
536
					$diff = ($newColumn != $oldColumn);
537
				} else {
538
					$diff = true;
539
				}
540
				if ($diff) {
541
					$drop[$name] = null;
542
					$add[$name] = $value;
543
				}
544
			}
545
		}
546
		return array_filter(compact('add', 'drop'));
547
	}
548
}
549
?>