Files
kiri-databases/BackupCommand.php
T

102 lines
2.6 KiB
PHP
Raw Normal View History

2023-04-11 18:02:44 +08:00
<?php
namespace Database;
use Exception;
use Kiri\Di\LocalService;
use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Input\InputArgument;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;
/**
*
*/
class BackupCommand extends Command
{
public string $command = 'db:backup';
2023-04-11 18:36:43 +08:00
public string $description = 'php kiri.php db:backup --database users --table u_user --data 1 /Users/admin/snowflake-bi/test.sql';
2023-04-11 18:02:44 +08:00
private LocalService $service;
/**
*
*/
protected function configure()
{
$this->service = \Kiri::getDi()->get(LocalService::class);
$this->setName('db:backup')
->addOption('data', 'd', InputArgument::OPTIONAL)
2023-04-11 18:36:43 +08:00
->addArgument('path', InputArgument::REQUIRED, "save to path", null)
2023-04-11 18:02:44 +08:00
->addOption('table', 't', InputArgument::OPTIONAL)
->addOption('database', 'db', InputArgument::OPTIONAL)
2023-04-11 18:36:43 +08:00
->setDescription('php kiri.php db:backup --database users --table u_user --data 1 /Users/admin/snowflake-bi/test.sql');
2023-04-11 18:02:44 +08:00
}
/**
* @param InputInterface $input
* @param OutputInterface $output
* @return int
* @throws Exception
*/
public function execute(InputInterface $input, OutputInterface $output): int
{
try {
/** @var Connection $data */
$data = $this->service->get($input->getOption('database'));
$table = $input->getOption('table');
if ($table !== null) {
$table = explode(',', $table);
} else {
2023-04-11 18:03:08 +08:00
$tmp = $data->createCommand('show tables from `' . $data->database . '`')->all();
2023-04-11 18:02:44 +08:00
$table = [];
foreach ($tmp as $value) {
$table[] = current($value);
}
}
2023-04-11 18:09:29 +08:00
2023-04-11 18:36:43 +08:00
$databaseInfo = $data->createCommand('show create DATABASE `' . $data->database . '`')->one();
$database = next($databaseInfo);
$path = $input->getArgument('path');
if (!is_dir($path)) {
mkdir($path);
}
2023-04-11 18:09:29 +08:00
2023-04-11 18:02:44 +08:00
foreach ($table as $value) {
$tableInfo = $data->createCommand('show create table `' . $data->database . '`.`' . $value . '`')->one();
2023-04-11 18:36:43 +08:00
$tmp = rtrim($path, '/') . '/' . current($tableInfo) . '.sql';
if (!file_exists($tmp)) {
touch($tmp);
}
file_put_contents($tmp, '');
file_put_contents($tmp, $database . ';' . PHP_EOL, FILE_APPEND);
$tableCreator = next($tableInfo);
if (preg_match('/AUTO_INCREMENT=\d+\s/', $tableCreator)) {
$tableCreator = preg_replace('/AUTO_INCREMENT=\d+\s/', 'AUTO_INCREMENT=1 ', $tableCreator);
}
file_put_contents($tmp, $tableCreator . ';' . PHP_EOL . PHP_EOL, FILE_APPEND);
2023-04-11 18:02:44 +08:00
}
} catch (\Throwable $throwable) {
$output->writeln($throwable->getMessage());
} finally {
return 1;
}
}
}