Created
September 11, 2024 12:25
-
-
Save stevebauman/dcb16199b4f6134d1e883d6d83992858 to your computer and use it in GitHub Desktop.
Migrate all your DB enum columns tostrings
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; | |
use Illuminate\Database\Schema\Blueprint; | |
use Illuminate\Database\SQLiteConnection; | |
use Illuminate\Support\Facades\Schema; | |
use Illuminate\Support\Facades\DB; | |
return new class extends Migration | |
{ | |
/** | |
* The tables and columns that need to be converted to string. | |
* | |
* ['{table_name}' => ['{enum_column}', '{enum_column}']] | |
*/ | |
protected array $tables = [ | |
// 'users' => ['type'], | |
]; | |
/** | |
* Run the migrations. | |
*/ | |
public function up(): void | |
{ | |
// SQLite doesn't support enum columns, so the | |
// columns are already in their appropriate | |
// type and do not need to be adjusted. | |
if (Schema::getConnection() instanceof SQLiteConnection) { | |
return; | |
} | |
foreach ($this->tables as $tableName => $columns) { | |
Schema::table($tableName, function (Blueprint $table) use ($tableName, $columns) { | |
foreach ($columns as $columnName) { | |
$column = $this->getColumnDefinition($tableName, $columnName); | |
DB::statement( | |
implode(' ', array_filter([ | |
"ALTER TABLE `{$tableName}` MODIFY COLUMN `{$columnName}` VARCHAR(255)", | |
($default = $column['default']) ? "DEFAULT '{$default}'" : null, | |
$column['nullable'] ? null : 'NOT NULL', | |
])) | |
); | |
if (! Schema::hasIndex($tableName, $indexName = "{$tableName}_{$columnName}_index")) { | |
$table->index($columnName, $indexName); | |
} | |
} | |
}); | |
} | |
} | |
/** | |
* Get the column definition from the table. | |
*/ | |
protected function getColumnDefinition(string $table, string $column): array | |
{ | |
foreach ($this->getColumns($table) as $value) { | |
if (strtolower($value['name']) === strtolower($column)) { | |
return $value; | |
} | |
} | |
throw new RuntimeException("Column [{$column}] not found in table [{$table}]."); | |
} | |
/** | |
* Get the column definitions for the table. | |
*/ | |
protected function getColumns(string $table): array | |
{ | |
return once(fn () => Schema::getColumns($table)); | |
} | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment