Skip to content

Instantly share code, notes, and snippets.

@markkimsal
Last active September 26, 2024 21:11
Show Gist options
  • Save markkimsal/3f9009dceef8eabdd41df72959e71eb1 to your computer and use it in GitHub Desktop.
Save markkimsal/3f9009dceef8eabdd41df72959e71eb1 to your computer and use it in GitHub Desktop.
Concurrent-safe migration for Laravel
<?php
$signature = 'lockingmigrate {--database= : The database connection to use}
{--force : Force the operation to run when in production}
{--path=* : The path(s) to the migrations files to be executed}
{--realpath : Indicate any provided migration file paths are pre-resolved absolute paths}
{--pretend : Dump the SQL queries that would be run}
{--seed : Indicates if the seed task should be re-run}
{--step : Force the migrations to be run so they can be rolled back individually}';
Artisan::command($signature, function ($database=false, $seed=false, $step=false, $pretend=false, $force=false, $path=[]) {
$results = \DB::select('SELECT GET_LOCK("artisan-migrate", 120) as migrate');
if (!$results[0]->migrate) { return 0; }
$params = [
'--database' => $database,
'--path' => $path,
'--pretend' => $pretend,
'--force' => $force,
'--step' => $step,
'--seed' => $seed,
];
$params = array_filter($params);
$retval = Artisan::call('migrate', $params);
$outputLines = explode("\n", trim(\Artisan::output()));
dump($outputLines);
return $retval;
})->describe('Concurrent-safe migrate');
@markkimsal
Copy link
Author

Put this in routes/ folder, then include it in app/Providers/RouteSerivceProvider.php or in routes/console.php.

This allows 120 seconds for all migrate scripts to run. No other lockingmigrate artisan commands will run. When they do get the chance to lock the DB, all the migrations will have run successfully and they will report "nothing to migrate"

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment