Merge pull request #17943 from jitendrapurohit/core-1906
[civicrm-core.git] / CRM / Utils / SQL / TempTable.php
index 0681978495b7a2cbd94d8bff009208afe2a693d0..f0024d7ef79a5a15728fa8b35687061d04ca5c3b 100644 (file)
@@ -13,7 +13,6 @@
  *
  * @package CRM
  * @copyright CiviCRM LLC https://civicrm.org/licensing
- *
  * Table naming rules:
  *   - MySQL imposes a 64 char limit.
  *   - All temp tables start with "civicrm_tmp".
@@ -125,7 +124,7 @@ class CRM_Utils_SQL_TempTable {
     $sql = sprintf('%s %s %s AS %s',
       $this->toSQL('CREATE'),
       $this->memory ? self::MEMORY : self::INNODB,
-      $this->utf8 ? self::UTF8 : '',
+      $this->getUtf8String(),
       ($selectQuery instanceof CRM_Utils_SQL_Select ? $selectQuery->toSQL() : $selectQuery)
     );
     CRM_Core_DAO::executeQuery($sql, [], TRUE, NULL, TRUE, FALSE);
@@ -133,6 +132,28 @@ class CRM_Utils_SQL_TempTable {
     return $this;
   }
 
+  /**
+   * Get the utf8 string for the table.
+   *
+   * If the db collation is already utf8 by default (either
+   * utf8 or utf84mb) then rely on that. Otherwise set to utf8.
+   *
+   * Respecting the DB collation supports utf8mb4 adopters, which is currently
+   * not the norm in civi installs.
+   *
+   * @return string
+   */
+  public function getUtf8String() {
+    if (!$this->utf8) {
+      return '';
+    }
+    $dbUTF = CRM_Core_BAO_SchemaHandler::getDBCollation();
+    if (strpos($dbUTF, 'utf8') !== FALSE) {
+      return '';
+    }
+    return self::UTF8;
+  }
+
   /**
    * Create the empty table.
    *
@@ -146,7 +167,7 @@ class CRM_Utils_SQL_TempTable {
       $this->toSQL('CREATE'),
       $columns,
       $this->memory ? self::MEMORY : self::INNODB,
-      $this->utf8 ? self::UTF8 : ''
+      $this->getUtf8String()
     );
     CRM_Core_DAO::executeQuery($sql, [], TRUE, NULL, TRUE, FALSE);
     $this->createSql = $sql;