-
-
Notifications
You must be signed in to change notification settings - Fork 22
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Add database connection checks before running migrations. This should…
… prevent issues where migrations cannot be executed due to race conditions, ensuring the database is initialized before migrations run.
- Loading branch information
1 parent
c14cd13
commit dcbf21d
Showing
2 changed files
with
49 additions
and
0 deletions.
There are no files selected for viewing
This file contains 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
38 changes: 38 additions & 0 deletions
38
app/src/Interfaces/Console/CheckDatabaseConnectionCommand.php
This file contains 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
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,38 @@ | ||
<?php | ||
|
||
declare(strict_types=1); | ||
|
||
namespace App\Interfaces\Console; | ||
|
||
use Cycle\Database\DatabaseInterface; | ||
use Spiral\Console\Attribute\AsCommand; | ||
use Spiral\Console\Command; | ||
|
||
#[AsCommand( | ||
name: 'database:check-connection', | ||
description: 'Check database connection', | ||
)] | ||
final class CheckDatabaseConnectionCommand extends Command | ||
{ | ||
public function __invoke(DatabaseInterface $db): int | ||
{ | ||
$tries = 0; | ||
$multiplier = 1.5; | ||
|
||
do { | ||
try { | ||
$db->getDriver()->connect(); | ||
$this->info('Database connection is OK'); | ||
break; | ||
} catch (\Throwable $e) { | ||
$tries++; | ||
$this->error($e->getMessage()); | ||
$delay = (int) ($multiplier * $tries); | ||
$this->error('Cannot connect to the database. Retrying in ' . $delay . ' second...'); | ||
\sleep($delay); | ||
} | ||
} while (true); | ||
|
||
return self::SUCCESS; | ||
} | ||
} |