diff --git a/server/src/com/cloud/upgrade/dao/Upgrade301to302.java b/server/src/com/cloud/upgrade/dao/Upgrade301to302.java index 528f1f53d02..2008cd80b15 100644 --- a/server/src/com/cloud/upgrade/dao/Upgrade301to302.java +++ b/server/src/com/cloud/upgrade/dao/Upgrade301to302.java @@ -74,6 +74,7 @@ public class Upgrade301to302 implements DbUpgrade { public void performDataMigration(Connection conn) { dropKeysIfExists(conn); updateSharedNetworks(conn); + fixLastHostIdKey(conn); } @Override @@ -157,4 +158,34 @@ public class Upgrade301to302 implements DbUpgrade { } } } + + + private void fixLastHostIdKey(Connection conn) { + //Drop i_usage_event__created key (if exists) and re-add it again + List keys = new ArrayList(); + + //Drop vmInstance keys (if exists) and insert one with correct name + keys = new ArrayList(); + + keys.add("fk_vm_instance__last_host_id"); + keys.add("i_vm_instance__last_host_id"); + + DbUpgradeUtils.dropKeysIfExist(conn, "cloud.vm_instance", keys, true); + DbUpgradeUtils.dropKeysIfExist(conn, "cloud.vm_instance", keys, false); + PreparedStatement pstmt = null; + try { + pstmt = conn.prepareStatement("ALTER TABLE `cloud`.`vm_instance` ADD CONSTRAINT `fk_vm_instance__last_host_id` FOREIGN KEY (`last_host_id`) REFERENCES `host` (`id`)"); + pstmt.executeUpdate(); + pstmt.close(); + } catch (SQLException e) { + throw new CloudRuntimeException("Unable to insert foreign key in vm_instance table ", e); + }finally { + try { + if (pstmt != null) { + pstmt.close(); + } + } catch (SQLException e) { + } + } + } } diff --git a/setup/db/db/schema-21to22-cleanup.sql b/setup/db/db/schema-21to22-cleanup.sql index b854ef14c68..eef6cded77d 100644 --- a/setup/db/db/schema-21to22-cleanup.sql +++ b/setup/db/db/schema-21to22-cleanup.sql @@ -71,7 +71,6 @@ DELETE FROM op_ha_work WHERE taken IS NOT NULL; DELETE FROM op_ha_work WHERE host_id NOT IN (SELECT DISTINCT id FROM host); UPDATE `cloud`.`vm_instance` SET last_host_id=NULL WHERE last_host_id NOT IN (SELECT DISTINCT id FROM host); -ALTER TABLE `cloud`.`vm_instance` ADD CONSTRAINT `fk_vm_instance__last_host_id` FOREIGN KEY `fk_vm_instance__last_host_id` (`last_host_id`) REFERENCES `host`(`id`); UPDATE `cloud`.`vm_instance` SET domain_id=1, account_id=1 where account_id not in (select distinct id from account) or domain_id not in (select distinct id from domain); ALTER TABLE `cloud`.`vm_instance` ADD CONSTRAINT `fk_vm_instance__account_id` FOREIGN KEY `fk_vm_instance__account_id` (`account_id`) REFERENCES `account` (`id`);