From 1babca0b8ffc86918729f2d4ad604c32f0b8deeb Mon Sep 17 00:00:00 2001
From: "Jay S. Bryant" <jsbryant@us.ibm.com>
Date: Mon, 6 Jan 2014 12:44:26 -0600
Subject: [PATCH] Fix downgrade in 002_quota_class.py for MySQL

Downgrade in the script 002_quota_class.py is failing for MySQL
because there is an attempt to delete the quota_classes table
while the reservations table still has a foreign key defined.
The foreign key causes the delete of the quota_classes table to fail.

This change is based upon commit 8328fc46d783f4ec9286eededafa91afae89cba0
which makes a similar change to 018_add_qos_specs.py .

Change-Id: I81844a2da4fb3b831f1f9dead3634e82f54e559e
Closes-bug: 1265944
---
 .../migrate_repo/versions/002_quota_class.py    | 17 +++++++++++++++++
 1 file changed, 17 insertions(+)

diff --git a/cinder/db/sqlalchemy/migrate_repo/versions/002_quota_class.py b/cinder/db/sqlalchemy/migrate_repo/versions/002_quota_class.py
index 4124675e8..4217d1a69 100644
--- a/cinder/db/sqlalchemy/migrate_repo/versions/002_quota_class.py
+++ b/cinder/db/sqlalchemy/migrate_repo/versions/002_quota_class.py
@@ -12,6 +12,7 @@
 #    License for the specific language governing permissions and limitations
 #    under the License.
 
+from migrate import ForeignKeyConstraint
 from sqlalchemy import Boolean, Column, DateTime
 from sqlalchemy import MetaData, Integer, String, Table, ForeignKey
 
@@ -109,6 +110,22 @@ def downgrade(migrate_engine):
     meta = MetaData()
     meta.bind = migrate_engine
 
+    if migrate_engine.name == 'mysql':
+        # NOTE(jsbryant): MySQL Cannot drop the quota_usages table
+        # until the foreign key reservations_ibfk_1 is removed.  We
+        # remove the foreign key first, and then we drop the table.
+        table = Table('reservations', meta, autoload=True)
+        ref_table = Table('reservations', meta, autoload=True)
+        params = {'columns': [table.c['usage_id']],
+                  'refcolumns': [ref_table.c['id']],
+                  'name': 'reservations_ibfk_1'}
+
+        try:
+            fkey = ForeignKeyConstraint(**params)
+            fkey.drop()
+        except Exception:
+            LOG.error(_("Dropping foreign key reservations_ibfk_1 failed."))
+
     quota_classes = Table('quota_classes', meta, autoload=True)
     try:
         quota_classes.drop()
-- 
2.45.2