Files
ulthon_admin/extend/base/common/command/tools/db/ToolsDbCountBase.php

80 lines
2.5 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 ToolsDbCountBase extends Command
{
protected function 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 ToolsDbServiceBase();
$service->showHelp('tools:db:count', $output);
return;
}
$service = new ToolsDbServiceBase();
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->writeln('');
$output->writeln('<comment>' . str_repeat('=', 60) . '</comment>');
$output->writeln('<info>表名:' . $fullTableName . '</info>');
$output->writeln('<comment>' . str_repeat('=', 60) . '</comment>');
$output->writeln('');
$output->writeln('<info>记录数:</info>' . $count);
$output->writeln('<info>执行时间:</info>' . $executionTime . 'ms');
$output->writeln('');
$output->writeln('<comment>' . str_repeat('=', 60) . '</comment>');
$output->writeln('');
} catch (\Exception $e) {
$output->error('统计失败:' . $e->getMessage());
return;
}
}
}