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('准备执行的 SQL:');
$output->writeln($sql);
$output->writeln('');
if (!$force) {
$confirm = $output->confirm($input, '确定要执行此 SQL 语句吗? ');
if (!$confirm) {
$output->writeln('操作已取消');
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('执行成功');
$output->writeln('影响行数:' . $affectedRows);
$output->writeln('执行时间:' . $executionTime . 'ms');
$output->writeln('');
} catch (\Exception $e) {
$output->writeln('');
$output->error('执行失败:' . $e->getMessage());
if ($useTransaction) {
$output->writeln('事务已回滚');
}
$output->writeln('');
return;
}
}
}