Files
ulthon_admin/extend/base/common/command/tools/db/ToolsDbExecuteBase.php

104 lines
3.4 KiB
PHP
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

<?php
namespace base\common\command\tools\db;
use base\common\service\ToolsDbServiceBase;
use think\console\Command;
use think\console\Input;
use think\console\input\Option;
use think\console\Output;
use think\facade\Db;
class ToolsDbExecuteBase extends Command
{
protected function configure()
{
$this->setName('tools:db:execute')
->setDescription('执行 SQL 非查询语句INSERT/UPDATE/DELETE')
->addArgument('sql', null, 'SQL 执行语句')
->addOption('force', null, Option::VALUE_NONE, '跳过确认直接执行')
->addOption('transaction', null, Option::VALUE_NONE, '在事务中执行(失败自动回滚)')
->addOption('connection', null, Option::VALUE_OPTIONAL, '指定数据库连接配置')
->addOption('help', 'h', Option::VALUE_NONE, '显示帮助信息');
}
protected function execute($input, $output)
{
if ($input->getOption('help')) {
$service = new ToolsDbServiceBase();
$service->showHelp('tools:db:execute', $output);
return;
}
$service = new ToolsDbServiceBase();
if (!$service->checkDebugMode($output)) {
return;
}
$connection = $service->getDbConnection($input);
$service->setConnection($connection);
$sql = $input->getArgument('sql');
if (empty($sql)) {
$output->error('请提供 SQL 执行语句');
return;
}
$force = $input->getOption('force');
$useTransaction = $input->getOption('transaction');
if (preg_match('/^\s*SELECT\s+/i', $sql)) {
$output->error('不支持 SELECT 语句,请使用 tools:db:query 执行查询');
return;
}
$output->writeln('');
$output->writeln('<comment>准备执行的 SQL</comment>');
$output->writeln($sql);
$output->writeln('');
if (!$force) {
$confirm = $output->confirm($input, '<question>确定要执行此 SQL 语句吗?</question> ');
if (!$confirm) {
$output->writeln('<comment>操作已取消</comment>');
return;
}
}
try {
$startTime = microtime(true);
if ($useTransaction) {
Db::connect($connection)->startTrans();
try {
$affectedRows = Db::connect($connection)->execute($sql);
Db::connect($connection)->commit();
} catch (\Exception $e) {
Db::connect($connection)->rollback();
throw $e;
}
} else {
$affectedRows = Db::connect($connection)->execute($sql);
}
$endTime = microtime(true);
$executionTime = round(($endTime - $startTime) * 1000, 2);
$output->writeln('');
$output->writeln('<info>执行成功</info>');
$output->writeln('影响行数:' . $affectedRows);
$output->writeln('执行时间:' . $executionTime . 'ms');
$output->writeln('');
} catch (\Exception $e) {
$output->writeln('');
$output->error('执行失败:' . $e->getMessage());
if ($useTransaction) {
$output->writeln('<comment>事务已回滚</comment>');
}
$output->writeln('');
return;
}
}
}