1 <?php declare(strict_types=1);
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'))
34 ->withEnvironment(['MYSQL_PWD' => $this->password])
37 ->runCapturingStdErr([
48 public function importSqlFile(string $sqlFilePath): void
50 $output = (new ProgramRunner('mysql', '/usr/bin/mysql'))
51 ->withEnvironment(['MYSQL_PWD' => $this->password])
54 ->runCapturingStdErr([
59 '-e', "source {$sqlFilePath}"
63 throw new Exception("Failed mysql file import with errors:\n" . $output);
67 public function dropTablesSql(): string
70 SET FOREIGN_KEY_CHECKS = 0;
71 SET GROUP_CONCAT_MAX_LEN=32768;
73 SELECT GROUP_CONCAT('`', table_name, '`') INTO @tables
74 FROM information_schema.tables
75 WHERE table_schema = (SELECT DATABASE());
76 SELECT IFNULL(@tables,'dummy') INTO @tables;
78 SET @tables = CONCAT('DROP TABLE IF EXISTS ', @tables);
79 PREPARE stmt FROM @tables;
81 DEALLOCATE PREPARE stmt;
82 SET FOREIGN_KEY_CHECKS = 1;
86 public function runDumpToFile(string $filePath): void
88 $file = fopen($filePath, 'w');
93 (new ProgramRunner('mysqldump', '/usr/bin/mysqldump'))
96 ->withEnvironment(['MYSQL_PWD' => $this->password])
97 ->runWithoutOutputCallbacks([
101 '--single-transaction',
104 ], function ($data) use (&$file, &$hasOutput) {
105 fwrite($file, $data);
107 }, function ($error) use (&$errors) {
108 $errors .= $error . "\n";
110 } catch (\Exception $exception) {
112 if ($exception instanceof ProcessTimedOutException) {
114 throw new Exception("mysqldump operation timed-out.\nNo data has been received so the connection to your database may have failed.");
116 throw new Exception("mysqldump operation timed-out after data was received.");
119 throw new Exception($exception->getMessage());
125 throw new Exception("Failed mysqldump with errors:\n" . $errors);
129 public static function fromEnvOptions(array $env): static
131 $host = ($env['DB_HOST'] ?? '');
132 $username = ($env['DB_USERNAME'] ?? '');
133 $password = ($env['DB_PASSWORD'] ?? '');
134 $database = ($env['DB_DATABASE'] ?? '');
135 $port = intval($env['DB_PORT'] ?? 3306);
137 return new static($host, $username, $password, $database, $port);