Stream data of backup for less memory usage

This commit is contained in:
Tim 2023-09-29 11:28:55 +02:00
parent 0a2a06fb8a
commit 4af4717785
2 changed files with 13 additions and 4 deletions

View File

@ -27,13 +27,15 @@ class BackupDatabaseCommand extends Command
protected function configure(): void protected function configure(): void
{ {
$this->addArgument('name', InputArgument::OPTIONAL, 'Database name'); $this->addArgument('name', InputArgument::OPTIONAL, 'Database name');
$this->addArgument('file', InputArgument::OPTIONAL, 'Backup file name');
} }
protected function execute(InputInterface $input, OutputInterface $output): int protected function execute(InputInterface $input, OutputInterface $output): int
{ {
$db = $this->getDatabaseName($input, $output); $db = $this->getDatabaseName($input, $output);
$fileName = $input->getArgument('file');
$backupName = $this->bs->backup($db); $backupName = $this->bs->backup($db, $fileName);
$output->writeln(sprintf('Backup written to: %s', $backupName)); $output->writeln(sprintf('Backup written to: %s', $backupName));
return Command::SUCCESS; return Command::SUCCESS;

View File

@ -21,15 +21,22 @@ class BackupService
$fileName = sprintf('%s_%s_backup.sql', $db, $date); $fileName = sprintf('%s_%s_backup.sql', $db, $date);
} }
$filesystem = new Filesystem();
$process = new Process([ $process = new Process([
'mysqldump', 'mysqldump',
'-u', $this->credentials->getUser(), '-u', $this->credentials->getUser(),
$db, $db,
]); ]);
$process->setEnv(['MYSQL_PWD' => $this->credentials->getPassword()]); $process->setEnv(['MYSQL_PWD' => $this->credentials->getPassword()]);
$process->run(); $process->start();
$filesystem->dumpFile($fileName, $process->getOutput());
$stream = fopen($fileName, 'w+');
foreach ($process as $type => $data) {
if ($process::OUT === $type) {
fwrite($stream, $data);
} else { // $process::ERR === $type
echo "\nError: " . $data;
}
}
return $fileName; return $fileName;
} }