Skip to content

Commit

Permalink
Merge pull request #181 from buggregator/hotfix/database-connection-c…
Browse files Browse the repository at this point in the history
…hecks

Add database connection checks before running migrations.
  • Loading branch information
butschster committed May 23, 2024
2 parents c14cd13 + dcbf21d commit 7a91028
Show file tree
Hide file tree
Showing 2 changed files with 49 additions and 0 deletions.
11 changes: 11 additions & 0 deletions app/src/Application/Bootloader/AppBootloader.php
Original file line number Diff line number Diff line change
Expand Up @@ -9,8 +9,10 @@
use App\Application\HTTP\Interceptor\StringToIntParametersInterceptor;
use App\Application\HTTP\Interceptor\UuidParametersConverterInterceptor;
use App\Application\Ide\UrlTemplate;
use App\Interfaces\Console\RegisterModulesCommand;
use Spiral\Boot\EnvironmentInterface;
use Spiral\Bootloader\DomainBootloader;
use Spiral\Console\Bootloader\ConsoleBootloader;
use Spiral\Core\CoreInterface;

final class AppBootloader extends DomainBootloader
Expand Down Expand Up @@ -46,4 +48,13 @@ protected static function defineInterceptors(): array
JsonResourceInterceptor::class,
];
}

public function init(ConsoleBootloader $console): void
{
$console->addSequence(
name: RegisterModulesCommand::SEQUENCE,
sequence: 'database:check-connection',
header: 'Check database connection',
);
}
}
38 changes: 38 additions & 0 deletions app/src/Interfaces/Console/CheckDatabaseConnectionCommand.php
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;
}
}

0 comments on commit 7a91028

Please sign in to comment.