Created
January 2, 2016 07:49
-
-
Save lokielse/632003bb8445329f9940 to your computer and use it in GitHub Desktop.
Laravel migrate mysql database to utfmb4
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
use Illuminate\Database\Migrations\Migration; | |
class MigrateToUtf8mb4 extends Migration | |
{ | |
public function up() | |
{ | |
DB::statement('SET FOREIGN_KEY_CHECKS=0;'); | |
$connection = Schema::getConnection(); | |
$schema = $connection->getDoctrineSchemaManager(); | |
$tables = $schema->listTableNames(); | |
$platform = $connection->getDoctrineSchemaManager()->getDatabasePlatform(); | |
$platform->registerDoctrineTypeMapping('enum', 'string'); | |
foreach ($tables as $table) { | |
try { | |
$table = (array) $table; | |
$table = array_values($table)[0]; | |
$columns = $schema->listTableColumns($table); | |
$indexes = $schema->listTableIndexes($table); | |
foreach ($columns as $column) { | |
if ($column->getType()->getName() == 'string' && $column->getLength() == '255') { | |
foreach ($indexes as $index) { | |
if (in_array($column->getName(), $index->getColumns())) { | |
DB::statement(sprintf('ALTER TABLE `%s` CHANGE `%s` `%s` VARCHAR(191);', $table, $column->getName(), $column->getName())); | |
break; | |
} | |
} | |
} | |
} | |
DB::statement(sprintf('ALTER TABLE `%s` CONVERT TO CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;', $table)); | |
foreach ($columns as $column) { | |
if ($column->getType()->getName() == 'string' && $column->getType()->getName() == 'text') { | |
$type = $column->getType()->getName() == 'string' ? 'VARCHAR' : 'TEXT'; | |
DB::statement(sprintf('ALTER TABLE `%s` CHANGE `%s` `%s` `%s` CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;', /**/ | |
$table, $column->getName(), $column->getName(), $type)); | |
} | |
} | |
DB::statement(sprintf('REPAIR TABLE `?`;', $table)); | |
DB::statement(sprintf('OPTIMIZE TABLE `?`;', $table)); | |
} catch (Exception $e) { | |
var_dump([ 'table' => $table, $e->getMessage() ]); | |
throw $e; | |
} | |
} | |
DB::statement('SET FOREIGN_KEY_CHECKS=1;'); | |
} | |
/** | |
* Reverse the migrations. | |
* | |
* @return void | |
*/ | |
public function down() | |
{ | |
// | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment