Files
ulthon_admin/extend/base/common/command/tools/db/ToolsDbCountBase.php
2026-03-26 20:22:34 +08:00

81 lines
2.4 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 ToolsDbCountBase extends Command
{
protected function configure()
{
parent::configure();
$this->setName('tools:db:count')
->setDescription('统计表记录数')
->addArgument('table', null, '表名')
->addOption('where', null, Option::VALUE_OPTIONAL, 'WHERE 条件')
->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:count', $output);
return;
}
$service = new DbService();
if (!$service->checkDebugMode($output)) {
return;
}
$connection = $service->getDbConnection($input);
$service->setConnection($connection);
$tableName = $input->getArgument('table');
if (empty($tableName)) {
$output->error('请提供表名');
return;
}
$fullTableName = $service->getFullTableName($tableName);
$where = $input->getOption('where');
try {
$startTime = microtime(true);
$query = Db::connect($connection)->table($fullTableName);
if ($where) {
$query->whereRaw($where);
}
$count = $query->count();
$endTime = microtime(true);
$executionTime = round(($endTime - $startTime) * 1000, 2);
$output->newLine();
$output->comment(str_repeat('=', 60));
$output->info('表名:' . $fullTableName);
$output->comment(str_repeat('=', 60));
$output->newLine();
$output->info('记录数:' . $count);
$output->info('执行时间:' . $executionTime . 'ms');
$output->newLine();
$output->comment(str_repeat('=', 60));
$output->newLine();
} catch (\Exception $e) {
$output->error('统计失败:' . $e->getMessage());
return;
}
}
}