CRM-18772 Create function to check if column already exists in the database
authorSeamus Lee <seamuslee001@gmail.com>
Sun, 5 Jun 2016 23:36:07 +0000 (09:36 +1000)
committerSeamus Lee <seamuslee001@gmail.com>
Sun, 5 Jun 2016 23:41:49 +0000 (09:41 +1000)
CRM/Core/BAO/SchemaHandler.php
tests/phpunit/CRM/Core/BAO/SchemaHandlerTest.php

index 5e116e96d53e84f4ef5f7d9c08fd025debb74789..46e63179b28860b40615ab0da8a9782055e2016a 100644 (file)
@@ -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;
+  }
+
 }
index e3dfb1adf871383be333a84cdb0402c4feb1e0a4..57f1d763bc8f89d58db8e13a488dcd5c0f38f1ea 100644 (file)
@@ -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));
+    }
+  }
+
 }