mirror of
https://gitee.com/ulthon/ulthon_admin.git
synced 2026-07-01 23:42:48 +08:00
100 lines
3.1 KiB
PHP
100 lines
3.1 KiB
PHP
<?php
|
||
|
||
namespace base\common\command\tools\db;
|
||
|
||
use app\common\service\tools\DbService;
|
||
use app\common\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()
|
||
{
|
||
parent::configure();
|
||
|
||
$this->setName('tools:db:execute')
|
||
->setDescription('执行 SQL 非查询语句(INSERT/UPDATE/DELETE)')
|
||
->addArgument('sql', null, 'SQL 执行语句')
|
||
->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 DbService();
|
||
$service->showHelp('tools:db:execute', $output);
|
||
return;
|
||
}
|
||
|
||
$service = new DbService();
|
||
|
||
if (!$service->checkDebugMode($output)) {
|
||
return;
|
||
}
|
||
|
||
$connection = $service->getDbConnection($input);
|
||
$service->setConnection($connection);
|
||
|
||
$sql = $input->getArgument('sql');
|
||
if (empty($sql)) {
|
||
$output->error('请提供 SQL 执行语句');
|
||
return;
|
||
}
|
||
|
||
$useTransaction = $input->getOption('transaction');
|
||
|
||
if (preg_match('/^\s*SELECT\s+/i', $sql)) {
|
||
$output->error('不支持 SELECT 语句,请使用 tools:db:query 执行查询');
|
||
return;
|
||
}
|
||
|
||
$output->newLine();
|
||
$output->comment('准备执行的 SQL:');
|
||
$output->writeln($sql);
|
||
$output->newLine();
|
||
|
||
if (!$output->confirm($input, '确定要执行此 SQL 语句吗?', true)) {
|
||
$output->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->newLine();
|
||
$output->info('执行成功');
|
||
$output->writeln('影响行数:' . $affectedRows);
|
||
$output->writeln('执行时间:' . $executionTime . 'ms');
|
||
$output->newLine();
|
||
} catch (\Exception $e) {
|
||
$output->newLine();
|
||
$output->error('执行失败:' . $e->getMessage());
|
||
if ($useTransaction) {
|
||
$output->comment('事务已回滚');
|
||
}
|
||
$output->newLine();
|
||
return;
|
||
}
|
||
}
|
||
} |