|
3 | 3 | use Illuminate\Database\Migrations\Migration; |
4 | 4 | use Illuminate\Database\Schema\Blueprint; |
5 | 5 | use Illuminate\Support\Facades\Schema; |
| 6 | +use Illuminate\Support\Facades\DB; |
6 | 7 |
|
7 | 8 | return new class extends Migration |
8 | 9 | { |
9 | | - /** |
10 | | - * Make the migrations. |
11 | | - * |
12 | | - * @return void |
13 | | - */ |
14 | 10 | public function up() |
15 | 11 | { |
16 | | - Schema::table('actions', function (Blueprint $table) { |
17 | | - $table->integer('type')->change(); |
18 | | - $table->integer('progress')->nullable()->after('type'); |
19 | | - }); |
| 12 | + $driver = DB::getDriverName(); |
20 | 13 |
|
| 14 | + if ($driver === 'pgsql') { |
| 15 | + // PostgreSQL requires manual check before conversion |
| 16 | + $invalidTypes = DB::table('actions') |
| 17 | + ->whereRaw("type !~ '^\d+$'") |
| 18 | + ->count(); |
| 19 | + |
| 20 | + if ($invalidTypes > 0) { |
| 21 | + throw new \RuntimeException("The 'type' column contains non-numeric values. Please clean up the data before running this migration."); |
| 22 | + } |
| 23 | + |
| 24 | + // Explicit conversion using PostgreSQL's USING clause |
| 25 | + DB::statement('ALTER TABLE actions ALTER COLUMN type TYPE integer USING type::integer'); |
| 26 | + DB::statement('ALTER TABLE actions ALTER COLUMN type SET NOT NULL'); |
| 27 | + } else { |
| 28 | + // MySQL, MariaDB, SQLite: automatic or dynamic type conversion |
| 29 | + Schema::table('actions', function (Blueprint $table) { |
| 30 | + $table->integer('type')->nullable(false)->change(); |
| 31 | + }); |
| 32 | + } |
21 | 33 | } |
22 | 34 |
|
23 | | - /** |
24 | | - * Reverse the migrations. |
25 | | - * |
26 | | - * @return void |
27 | | - */ |
28 | 35 | public function down() |
29 | 36 | { |
30 | | - Schema::table('actions', function (Blueprint $table) { |
31 | | - $table->string('type', 32)->change(); |
32 | | - $table->dropColumn('progress'); |
33 | | - }); |
| 37 | + $driver = DB::getDriverName(); |
34 | 38 |
|
| 39 | + if ($driver === 'pgsql') { |
| 40 | + // Revert PostgreSQL changes |
| 41 | + DB::statement('ALTER TABLE actions ALTER COLUMN type TYPE text USING type::text'); |
| 42 | + DB::statement('ALTER TABLE actions ALTER COLUMN type DROP NOT NULL'); |
| 43 | + } else { |
| 44 | + // Revert changes for MySQL, MariaDB, SQLite |
| 45 | + Schema::table('actions', function (Blueprint $table) { |
| 46 | + $table->string('type')->nullable()->change(); |
| 47 | + }); |
| 48 | + } |
35 | 49 | } |
36 | 50 | }; |
0 commit comments