From: Seamus Lee Date: Sun, 5 Jun 2016 23:36:07 +0000 (+1000) Subject: CRM-18772 Create function to check if column already exists in the database X-Git-Url: https://vcs.fsf.org/?a=commitdiff_plain;h=82f5a856a417cb5b839f56340bef524b62a03471;p=civicrm-core.git CRM-18772 Create function to check if column already exists in the database --- diff --git a/CRM/Core/BAO/SchemaHandler.php b/CRM/Core/BAO/SchemaHandler.php index 5e116e96d5..46e63179b2 100644 --- a/CRM/Core/BAO/SchemaHandler.php +++ b/CRM/Core/BAO/SchemaHandler.php @@ -579,4 +579,23 @@ MODIFY {$columnName} varchar( $length ) return FALSE; } + /** + * Check if the table has a specified column + * + * @param string $tableName + * @param string $columnName + * + * @return \CRM_Core_DAO|object + */ + public static function checkIfFieldExists($tableName, $columnName) { + $result = CRM_Core_DAO::executeQuery( + "SHOW COLUMNS FROM $tableName LIKE ' %1 '", + array(1 => array($columnName, 'mysqlColumnNameOrAlias')) + ); + if ($result->fetch()) { + return TRUE; + } + return FALSE; + } + } diff --git a/tests/phpunit/CRM/Core/BAO/SchemaHandlerTest.php b/tests/phpunit/CRM/Core/BAO/SchemaHandlerTest.php index e3dfb1adf8..57f1d763bc 100644 --- a/tests/phpunit/CRM/Core/BAO/SchemaHandlerTest.php +++ b/tests/phpunit/CRM/Core/BAO/SchemaHandlerTest.php @@ -122,4 +122,30 @@ class CRM_Core_BAO_SchemaHandlerTest extends CiviUnitTestCase { CRM_Core_BAO_SchemaHandler::createIndexes(array('civicrm_contact' => array('hash'))); } + /** + * @return array + */ + public function columnTests() { + $columns = array(); + $columns[] = array('civicrm_contribution', 'total_amount'); + $columns[] = array('civicrm_contact', 'from_name'); + $columns[] = array('civicrm_contact', 'xxxx'); + return $columns; + } + + /** + * @param $tableName + * @param $columnName + * + * @dataProvider columnTests + */ + public function testCheckIfColumnExists($tableName, $columnName) { + if ($columnName == 'xxxx') { + $this->assertFalse(CRM_Core_BAO_SchemaHandler::checkIfFieldExists($tableName, $columnName)); + } + else { + $this->assertTrue(CRM_Core_BAO_SchemaHandler::checkIfFieldExists($tableName, $columnName)); + } + } + }