From 030d45c8b472e79df54c36a212c156aeb28f8fd3 Mon Sep 17 00:00:00 2001 From: Seamus Lee Date: Fri, 1 Jul 2016 12:30:46 +1000 Subject: [PATCH] CRM-19038 backport safe Remove FK code to 4.6 --- CRM/Core/BAO/SchemaHandler.php | 30 +++++++++++++++++++ .../CRM/Core/BAO/SchemaHandlerTest.php | 16 ++++++++++ 2 files changed, 46 insertions(+) diff --git a/CRM/Core/BAO/SchemaHandler.php b/CRM/Core/BAO/SchemaHandler.php index 6b2170141c..c5ddefba10 100644 --- a/CRM/Core/BAO/SchemaHandler.php +++ b/CRM/Core/BAO/SchemaHandler.php @@ -604,4 +604,34 @@ MODIFY {$columnName} varchar( $length ) return FALSE; } + /** + * Remove a foreign key from a table if it exists + * + * @param $table_name + * @param $constraint_name + */ + public static function safeRemoveFK($table_name, $constraint_name) { + + $config = CRM_Core_Config::singleton(); + $dbUf = DB::parseDSN($config->dsn); + $query = " + SELECT CONSTRAINT_NAME FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS + WHERE TABLE_SCHEMA = %1 + AND TABLE_NAME = %2 + AND CONSTRAINT_NAME = %3 + AND CONSTRAINT_TYPE = 'FOREIGN KEY' + "; + $params = array( + 1 => array($dbUf['database'], 'String'), + 2 => array($table_name, 'String'), + 3 => array($constraint_name, 'String'), + ); + $dao = CRM_Core_DAO::executeQuery($query, $params); + + if ($dao->fetch()) { + CRM_Core_DAO::executeQuery("ALTER TABLE {$table_name} DROP FOREIGN KEY {$constraint_name}", array()); + } + + } + } diff --git a/tests/phpunit/CRM/Core/BAO/SchemaHandlerTest.php b/tests/phpunit/CRM/Core/BAO/SchemaHandlerTest.php index 00a86bbc2d..90089fb1ca 100644 --- a/tests/phpunit/CRM/Core/BAO/SchemaHandlerTest.php +++ b/tests/phpunit/CRM/Core/BAO/SchemaHandlerTest.php @@ -148,4 +148,20 @@ class CRM_Core_BAO_SchemaHandlerTest extends CiviUnitTestCase { } } + /** + * Test to see if we can drop foreign key + * + */ + public function testSafeDropForeignKey() { + $tests = array('FK_civicrm_mailing_recipients_email_id', 'FK_civicrm_mailing_recipients_id'); + foreach ($tests as $test) { + if ($test == 'FK_civicrm_mailing_recipients_id') { + $this->assertFalse(CRM_Core_BAO_SchemaHandler::safeRemoveFK('civicrm_mailing_recipients', $test)); + } + else { + $this->assertTrue(CRM_Core_BAO_SchemaHandler::safeRemoveFK('civicrm_mailing_recipients', $test)); + } + } + } + } -- 2.25.1