feat(command): 新增数据库调试命令行工具集

This commit is contained in:
augushong
2026-01-26 23:10:10 +08:00
parent 148f8b7a6f
commit e8f58ef322
14 changed files with 935 additions and 1 deletions

View File

@@ -0,0 +1,90 @@
<?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 ToolsDbQueryBase extends Command
{
protected function configure()
{
$this->setName('tools:db:query')
->setDescription('执行 SQL 查询语句SELECT并显示结果')
->addArgument('sql', null, 'SQL 查询语句')
->addOption('format', null, Option::VALUE_OPTIONAL, '输出格式可选值table默认、json', 'table')
->addOption('limit', null, Option::VALUE_OPTIONAL, '限制显示行数')
->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:query', $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;
}
$format = $input->getOption('format') ?: 'table';
$limit = $input->getOption('limit');
if (!preg_match('/^\s*SELECT\s+/i', $sql)) {
$output->error('仅支持 SELECT 语句,请使用 tools:db:execute 执行其他 SQL 语句');
return;
}
try {
$startTime = microtime(true);
$query = Db::connect($connection)->query($sql);
$endTime = microtime(true);
$executionTime = round(($endTime - $startTime) * 1000, 2);
if (!is_array($query)) {
$query = [];
}
if ($limit && is_numeric($limit)) {
$query = array_slice($query, 0, (int)$limit);
}
$output->writeln('');
if ($format === 'json') {
$service->formatJsonOutput($query, $output);
} else {
$service->formatTableOutput($query, $output);
}
$output->writeln('');
$output->writeln('<info>查询成功</info>');
$output->writeln('影响行数:' . count($query));
$output->writeln('执行时间:' . $executionTime . 'ms');
$output->writeln('');
} catch (\Exception $e) {
$output->error('查询失败:' . $e->getMessage());
return;
}
}
}