simon_w: #2118 - When removing a value from an enum, set affected rows back to the default

git-svn-id: svn://svn.silverstripe.com/silverstripe/open/modules/sapphire/trunk@47870 467b73ca-7a2a-4603-9d3b-597d59a354a9
This commit is contained in:
Sam Minnee 2008-01-10 23:53:34 +00:00
parent 9750028e8d
commit d0827cc3ef

View File

@ -309,6 +309,38 @@ abstract class Database extends Object {
Profiler::unmark('createField');
Database::alteration_message("Field $table.$field: created as $spec","created");
} else if($this->fieldList[$table][$field] != $spec) {
// If enums are being modified, then we need to fix existing data in the table.
// Update any records where the enum is set to a legacy value to be set to the default.
// One hard-coded exception is SiteTree - the default for this is Page.
if(substr($spec, 0, 4) == "enum") {
$new = substr($spec, 5);
$old = substr($this->fieldList[$table][$field], 5);
$new = substr($new, 0, strpos($new, ')'));
$old = substr($old, 0, strpos($old, ')'));
$new = str_replace("'", '', $new);
$old = str_replace("'", '', $old);
$new = explode(',', $new);
$old = explode(',', $old);
$holder = array();
foreach($old as $check) {
if(!in_array($check, $new)) {
$holder[] = $check;
}
}
if(count($holder)) {
$default = explode('default ', $spec);
$default = $default[1];
if($default == "'SiteTree'") $default = "'Page'";
$query = "UPDATE `$table` SET $field=$default WHERE $field IN (";
for($i=0;$i+1<count($holder);$i++) {
$query .= "'{$holder[$i]}', ";
}
$query .= "'{$holder[$i]}')";
DB::query($query);
$amount = DB::affectedRows();
Database::alteration_message("Changed $amount rows to default value of field $field (Value: $default)");
}
}
Profiler::mark('alterField');
$this->transAlterField($table, $field, $spec);
Profiler::unmark('alterField');