3 namespace Cli\Services;
9 public function __construct(
10 protected string $host,
11 protected string $user,
12 protected string $password,
13 protected string $database,
14 protected int $port = 3306
21 public function ensureOptionsSet(): void
23 $options = ['host', 'user', 'password', 'database'];
24 foreach ($options as $option) {
25 if (!$this->$option) {
26 throw new Exception("Could not find a valid value for the \"{$option}\" database option.");
31 public function testConnection(): bool
33 $output = (new ProgramRunner('mysql', '/usr/bin/mysql'))
36 ->runCapturingStdErr([
40 '-p' . $this->password,
42 '-e' . "'show tables;'"
48 public function importSqlFile(string $sqlFilePath): void
50 $output = (new ProgramRunner('mysql', '/usr/bin/mysql'))
53 ->runCapturingStdErr([
57 '-p' . $this->password,
63 throw new Exception("Failed mysql file import with errors:\n" . $output);
67 public function runDumpToFile(string $filePath): void
69 $file = fopen($filePath, 'w');
74 (new ProgramRunner('mysqldump', '/usr/bin/mysqldump'))
77 ->runWithoutOutputCallbacks([
81 '-p' . $this->password,
82 '--single-transaction',
85 ], function ($data) use (&$file, &$hasOutput) {
88 }, function ($error) use (&$errors) {
89 $errors .= $error . "\n";
91 } catch (\Exception $exception) {
93 if ($exception instanceof ProcessTimedOutException) {
95 throw new Exception("mysqldump operation timed-out.\nNo data has been received so the connection to your database may have failed.");
97 throw new Exception("mysqldump operation timed-out after data was received.");
100 throw new Exception($exception->getMessage());
106 throw new Exception("Failed mysqldump with errors:\n" . $errors);
110 public static function fromEnvOptions(array $env): static
112 $host = ($env['DB_HOST'] ?? '');
113 $username = ($env['DB_USERNAME'] ?? '');
114 $password = ($env['DB_PASSWORD'] ?? '');
115 $database = ($env['DB_DATABASE'] ?? '');
116 $port = intval($env['DB_PORT'] ?? 3306);
118 return new static($host, $username, $password, $database, $port);