mirror of
https://gitee.com/ulthon/ulthon_admin.git
synced 2026-07-01 23:42:48 +08:00
91 lines
2.8 KiB
PHP
91 lines
2.8 KiB
PHP
<?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;
|
||
}
|
||
}
|
||
}
|