Created
November 8, 2021 14:06
-
-
Save coreymcmahon/33e8310714421ca4c8dd7fe057b01a66 to your computer and use it in GitHub Desktop.
Migration to add missing `uuid` column to `failed_jobs` table when upgrading Laravel.
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\Support\Facades\Schema; | |
use Ramsey\Uuid\Uuid; | |
class AlterFailedJobsAddUuid extends Migration | |
{ | |
public function up() | |
{ | |
Schema::table('failed_jobs', function (Blueprint $table) { | |
$table->string('uuid')->nullable(); | |
}); | |
// Backfill in chunks | |
$chunks = \DB::table('failed_jobs') | |
->select('id') | |
->get() | |
->pluck('id') | |
->chunk(1000); | |
foreach ($chunks as $chunk) { | |
$values = []; | |
foreach ($chunk as $id) { | |
$uuid = Uuid::uuid4()->toString(); | |
$values[] = "({$id}, '{$uuid}')"; | |
} | |
$imploded = implode(',', $values); | |
$sql = <<<SQL | |
update failed_jobs as f set | |
uuid = u.uuid | |
from (values $imploded) as u(id, uuid) | |
where u.id = f.id | |
SQL; | |
\DB::statement($sql); | |
} | |
Schema::table('failed_jobs', function (Blueprint $table) { | |
$table->string('uuid')->unique()->change(); | |
}); | |
} | |
public function down() | |
{ | |
Schema::table('failed_jobs', function (Blueprint $table) { | |
$table->dropColumn('uuid'); | |
}); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment