setName('tools:db:desc') ->setDescription('显示表结构信息') ->addArgument('table', null, '表名') ->addOption('show-index', 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 ToolsDbServiceBase(); $service->showHelp('tools:db:desc', $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); $showIndex = $input->getOption('show-index'); try { $output->writeln(''); $output->writeln('' . str_repeat('=', 60) . ''); $output->writeln('表结构:' . $fullTableName . ''); $output->writeln('' . str_repeat('=', 60) . ''); $output->writeln(''); $columns = Db::connect($connection)->query("SHOW FULL COLUMNS FROM `$fullTableName`"); if (empty($columns)) { $output->writeln('表不存在或无字段'); $output->writeln(''); return; } $tableData = []; foreach ($columns as $column) { $tableData[] = [ '字段名' => $column['Field'], '类型' => $column['Type'], '是否为空' => $column['Null'] === 'YES' ? '是' : '否', '键' => $column['Key'], '默认值' => $column['Default'] ?? 'NULL', '额外' => $column['Extra'] ?? '', '注释' => $column['Comment'] ?? '', ]; } $service->formatTableOutput($tableData, $output); if ($showIndex) { $output->writeln(''); $output->writeln('' . str_repeat('-', 60) . ''); $output->writeln('索引信息'); $output->writeln('' . str_repeat('-', 60) . ''); $output->writeln(''); $indexes = Db::connect($connection)->query("SHOW INDEX FROM `$fullTableName`"); if (!empty($indexes)) { $indexData = []; foreach ($indexes as $index) { $indexData[] = [ '索引名' => $index['Key_name'], '列名' => $index['Column_name'], '唯一' => $index['Non_unique'] == 0 ? '是' : '否', '索引类型' => $index['Index_type'], '顺序' => $index['Seq_in_index'], ]; } $service->formatTableOutput($indexData, $output); } else { $output->writeln('无索引'); } } $output->writeln(''); $output->writeln('' . str_repeat('=', 60) . ''); $output->writeln(''); } catch (\Exception $e) { $output->error('获取表结构失败:' . $e->getMessage()); return; } } }