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('' . str_repeat('=', 60) . '');
$output->writeln('表名:' . $fullTableName . '');
$output->writeln('' . str_repeat('=', 60) . '');
$output->writeln('');
$output->writeln('记录数:' . $count);
$output->writeln('执行时间:' . $executionTime . 'ms');
$output->writeln('');
$output->writeln('' . str_repeat('=', 60) . '');
$output->writeln('');
} catch (\Exception $e) {
$output->error('统计失败:' . $e->getMessage());
return;
}
}
}