From a489d465a7f8628ae3c2c24545eeef836663bf43 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E5=90=91=E6=9E=97?= Date: Tue, 11 Apr 2023 18:02:44 +0800 Subject: [PATCH] =?UTF-8?q?=E5=8F=98=E6=9B=B4?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- BackupCommand.php | 78 ++++++++++++++++++++++++++++++++++++++++++ DatabasesProviders.php | 8 ++++- 2 files changed, 85 insertions(+), 1 deletion(-) create mode 100644 BackupCommand.php diff --git a/BackupCommand.php b/BackupCommand.php new file mode 100644 index 0000000..bb83f22 --- /dev/null +++ b/BackupCommand.php @@ -0,0 +1,78 @@ +service = \Kiri::getDi()->get(LocalService::class); + $this->setName('db:backup') + ->addOption('struct', 's', InputArgument::OPTIONAL) + ->addOption('data', 'd', InputArgument::OPTIONAL) + ->addOption('path', 'p', InputArgument::REQUIRED) + ->addOption('table', 't', InputArgument::OPTIONAL) + ->addOption('database', 'db', InputArgument::OPTIONAL) + ->setDescription('php kiri.php sw:backup --struct 1 --database users --data 1'); + } + + + /** + * @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 { + $tmp = $data->createCommand('show tables from `users`')->all(); + $table = []; + foreach ($tmp as $value) { + $table[] = current($value); + } + } + foreach ($table as $value) { + $tableInfo = $data->createCommand('show create table `' . $data->database . '`.`' . $value . '`')->one(); + + file_put_contents($input->getOption('path'), $tableInfo[$value], FILE_APPEND); + } + } catch (\Throwable $throwable) { + $output->writeln($throwable->getMessage()); + } finally { + return 1; + } + } + +} diff --git a/DatabasesProviders.php b/DatabasesProviders.php index 147cbcc..30b42f8 100644 --- a/DatabasesProviders.php +++ b/DatabasesProviders.php @@ -14,6 +14,8 @@ use Kiri\Events\EventProvider; use Kiri\Annotation\Inject; use Kiri\Server\Events\OnWorkerStart; use Kiri\Server\Events\OnTaskerStart; +use Psr\Container\ContainerExceptionInterface; +use Psr\Container\NotFoundExceptionInterface; use Psr\Log\LoggerInterface; use Kiri\Server\Events\OnWorkerExit; use Swoole\Timer; @@ -38,11 +40,15 @@ class DatabasesProviders extends Providers /** * @param LocalService $application * @return void - * @throws ConfigException + * @throws ContainerExceptionInterface + * @throws NotFoundExceptionInterface * @throws Exception */ public function onImport(LocalService $application): void { + $main = Kiri::getDi()->get(Kiri\Main::class); + $main->command(BackupCommand::class); + $databases = Config::get('databases.connections', []); if (empty($databases)) { return;