You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
50 lines
1.5 KiB
50 lines
1.5 KiB
<?php |
|
|
|
namespace App\Console\Commands; |
|
|
|
use Illuminate\Console\Command; |
|
use PDO; |
|
use Throwable; |
|
|
|
class EnsureAppDatabaseCommand extends Command |
|
{ |
|
protected $signature = 'app:ensure-database'; |
|
|
|
protected $description = 'Create PostgreSQL app database if it does not exist'; |
|
|
|
public function handle(): int |
|
{ |
|
if (env('DB_CONNECTION', 'pgsql') !== 'pgsql') { |
|
return self::SUCCESS; |
|
} |
|
|
|
$host = env('APP_DB_HOST', env('AUDIT_DB_HOST', '127.0.0.1')); |
|
$port = (int) env('APP_DB_PORT', env('AUDIT_DB_PORT', 5432)); |
|
$user = env('APP_DB_USERNAME', env('AUDIT_DB_USERNAME', 'audit')); |
|
$password = env('APP_DB_PASSWORD', env('AUDIT_DB_PASSWORD', '')); |
|
$database = env('APP_DB_DATABASE', 'databaselist_app'); |
|
|
|
try { |
|
$pdo = new PDO( |
|
"pgsql:host={$host};port={$port};dbname=postgres", |
|
$user, |
|
$password, |
|
[PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION] |
|
); |
|
|
|
$stmt = $pdo->prepare('SELECT 1 FROM pg_database WHERE datname = ?'); |
|
$stmt->execute([$database]); |
|
|
|
if ($stmt->fetchColumn() === false) { |
|
$pdo->exec('CREATE DATABASE "' . str_replace('"', '""', $database) . '"'); |
|
$this->info("Created database [{$database}]."); |
|
} |
|
} catch (Throwable $e) { |
|
$this->warn('Could not ensure app database: ' . $e->getMessage()); |
|
|
|
return self::FAILURE; |
|
} |
|
|
|
return self::SUCCESS; |
|
} |
|
}
|
|
|