mirror of
https://gitee.com/ulthon/ulthon_admin.git
synced 2026-07-01 23:42:48 +08:00
108 lines
3.4 KiB
PHP
108 lines
3.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 ToolsDbTableBase extends Command
|
|
{
|
|
protected function configure()
|
|
{
|
|
parent::configure();
|
|
|
|
$this->setName('tools:db:table')
|
|
->setDescription('使用查询构建器操作表')
|
|
->addArgument('table', null, '表名')
|
|
->addOption('where', null, Option::VALUE_OPTIONAL, 'WHERE 条件')
|
|
->addOption('field', null, Option::VALUE_OPTIONAL, '查询字段,多个用逗号分隔')
|
|
->addOption('limit', null, Option::VALUE_OPTIONAL, '限制行数')
|
|
->addOption('order', null, Option::VALUE_OPTIONAL, '排序,如 "id DESC"')
|
|
->addOption('count', null, Option::VALUE_NONE, '只统计数量')
|
|
->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:table', $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');
|
|
$field = $input->getOption('field');
|
|
$limit = $input->getOption('limit');
|
|
$order = $input->getOption('order');
|
|
$count = $input->getOption('count');
|
|
|
|
try {
|
|
$startTime = microtime(true);
|
|
|
|
$query = Db::connect($connection)->table($fullTableName);
|
|
|
|
if ($field) {
|
|
$query->field($field);
|
|
}
|
|
|
|
if ($where) {
|
|
$query->whereRaw($where);
|
|
}
|
|
|
|
if ($order) {
|
|
$query->orderRaw($order);
|
|
}
|
|
|
|
if ($count) {
|
|
$result = $query->count();
|
|
|
|
$output->newLine();
|
|
$output->info('表名:' . $fullTableName);
|
|
$output->writeln('记录数:' . $result);
|
|
$output->newLine();
|
|
} else {
|
|
if ($limit && is_numeric($limit)) {
|
|
$query->limit((int)$limit);
|
|
}
|
|
|
|
$result = $query->select()->toArray();
|
|
|
|
$endTime = microtime(true);
|
|
$executionTime = round(($endTime - $startTime) * 1000, 2);
|
|
|
|
$output->newLine();
|
|
$output->info('表名:' . $fullTableName);
|
|
$service->formatTableOutput($result, $output);
|
|
$output->newLine();
|
|
$output->writeln('影响行数:' . count($result));
|
|
$output->writeln('执行时间:' . $executionTime . 'ms');
|
|
$output->newLine();
|
|
}
|
|
} catch (\Exception $e) {
|
|
$output->error('查询失败:' . $e->getMessage());
|
|
return;
|
|
}
|
|
}
|
|
} |