From 8454b1fbadc00fcf8c87d19bd7615a5be00fde09 Mon Sep 17 00:00:00 2001 From: Brion Vibber Date: Thu, 8 Sep 2011 13:03:22 -0700 Subject: [PATCH] Fix for schema upgrade issue when primary keys change; fixes upgrade direct from 0.8.x Previously we were failing to update the primary key during ensureTable(), which could lead to failures when updating some tables (eg queue_item where we changed keys, and the addition of an autoincrement column failed because it conflicted with the old key). Now if the key is different, we remove the old key at the start and add the new key at the end of the ALTER TABLE. Not tested on PostgreSQL -- someone please check whether the alter table 'DROP CONSTRAINT PRIMARY KEY' bit works or if it needs to pull a special name for the key. On MySQL, dropping uses alter table's 'DROP PRIMARY KEY' special case. --- lib/mysqlschema.php | 10 ++++++++++ lib/schema.php | 21 +++++++++++++++++++++ 2 files changed, 31 insertions(+) diff --git a/lib/mysqlschema.php b/lib/mysqlschema.php index c3d3501c74..435ba4e3a9 100644 --- a/lib/mysqlschema.php +++ b/lib/mysqlschema.php @@ -298,6 +298,16 @@ class MysqlSchema extends Schema return "{$tableName}_{$columnName}_idx"; } + /** + * MySQL doesn't take 'DROP CONSTRAINT', need to treat primary keys as + * if they were indexes here, but can use 'PRIMARY KEY' special name. + * + * @param array $phrase + */ + function appendAlterDropPrimary(array &$phrase) + { + $phrase[] = 'DROP PRIMARY KEY'; + } /** * MySQL doesn't take 'DROP CONSTRAINT', need to treat unique keys as diff --git a/lib/schema.php b/lib/schema.php index 2e27955881..aad705a533 100644 --- a/lib/schema.php +++ b/lib/schema.php @@ -579,6 +579,10 @@ class Schema $this->appendAlterDropUnique($phrase, $keyName); } + if (isset($old['primary key']) && (!isset($def['primary key']) || $def['primary key'] != $old['primary key'])) { + $this->appendAlterDropPrimary($phrase); + } + foreach ($fields['add'] as $columnName) { $this->appendAlterAddColumn($phrase, $columnName, $def['fields'][$columnName]); @@ -594,6 +598,10 @@ class Schema $this->appendAlterDropColumn($phrase, $columnName); } + if (isset($def['primary key']) && (!isset($old['primary key']) || $old['primary key'] != $def['primary key'])) { + $this->appendAlterAddPrimary($phrase, $def['primary key']); + } + foreach ($uniques['mod'] + $uniques['add'] as $keyName) { $this->appendAlterAddUnique($phrase, $keyName, $def['unique keys'][$keyName]); } @@ -713,6 +721,19 @@ class Schema $phrase[] = implode(' ', $sql); } + function appendAlterAddPrimary(array &$phrase, array $def) + { + $sql = array(); + $sql[] = 'ADD'; + $this->appendPrimaryKeyDef($sql, $def); + $phrase[] = implode(' ', $sql); + } + + function appendAlterDropPrimary(array &$phrase) + { + $phrase[] = 'DROP CONSTRAINT PRIMARY KEY'; + } + function appendAlterDropUnique(array &$phrase, $keyName) { $phrase[] = 'DROP CONSTRAINT ' . $keyName;