|
| 1 | +<?php |
| 2 | + |
| 3 | +declare(strict_types=1); |
| 4 | + |
| 5 | +namespace App\Command; |
| 6 | + |
| 7 | +use Hyperf\Command\Command as HyperfCommand; |
| 8 | +use Hyperf\Command\Annotation\Command; |
| 9 | +use Hyperf\DbConnection\Db; |
| 10 | +use Psr\Container\ContainerInterface; |
| 11 | + |
| 12 | +/** |
| 13 | + * 测试数据库连接命令 |
| 14 | + */ |
| 15 | +#[Command] |
| 16 | +class TestDbCommand extends HyperfCommand |
| 17 | +{ |
| 18 | + public function __construct(protected ContainerInterface $container) |
| 19 | + { |
| 20 | + parent::__construct('db:test'); |
| 21 | + } |
| 22 | + |
| 23 | + public function configure() |
| 24 | + { |
| 25 | + parent::configure(); |
| 26 | + $this->setDescription('测试数据库连接'); |
| 27 | + } |
| 28 | + |
| 29 | + public function handle() |
| 30 | + { |
| 31 | + $this->info('开始测试数据库连接...'); |
| 32 | + |
| 33 | + try { |
| 34 | + // 测试 backend_mysql 连接 |
| 35 | + $this->info('测试 backend_mysql 连接...'); |
| 36 | + $connection = Db::connection('backend_mysql'); |
| 37 | + $this->info('获取连接对象成功'); |
| 38 | + |
| 39 | + // 检查连接对象的类型和可用方法 |
| 40 | + $this->info('连接对象类型: ' . get_class($connection)); |
| 41 | + $this->info('连接对象方法: ' . implode(', ', get_class_methods($connection))); |
| 42 | + |
| 43 | + // 尝试不同的方法获取 PDO |
| 44 | + $pdo = null; |
| 45 | + if (method_exists($connection, 'getConnection')) { |
| 46 | + $pdo = $connection->getConnection(); |
| 47 | + $this->info('通过 getConnection 获取 PDO'); |
| 48 | + } elseif (method_exists($connection, 'getPdo')) { |
| 49 | + $pdo = $connection->getPdo(); |
| 50 | + $this->info('通过 getPdo 获取 PDO'); |
| 51 | + } elseif (method_exists($connection, 'getReadPdo')) { |
| 52 | + $pdo = $connection->getReadPdo(); |
| 53 | + $this->info('通过 getReadPdo 获取 PDO'); |
| 54 | + } elseif (method_exists($connection, 'getWritePdo')) { |
| 55 | + $pdo = $connection->getWritePdo(); |
| 56 | + $this->info('通过 getWritePdo 获取 PDO'); |
| 57 | + } else { |
| 58 | + $this->error('无法获取 PDO 对象'); |
| 59 | + return; |
| 60 | + } |
| 61 | + |
| 62 | + if ($pdo instanceof \PDO) { |
| 63 | + $this->info('PDO 对象有效,类型: ' . get_class($pdo)); |
| 64 | + } else { |
| 65 | + $this->error('PDO 对象无效: ' . gettype($pdo) . ' 类: ' . (is_object($pdo) ? get_class($pdo) : 'N/A')); |
| 66 | + return; |
| 67 | + } |
| 68 | + |
| 69 | + // 执行测试查询 |
| 70 | + $result = $connection->select('SELECT 12 as test_value, NOW() as current_time'); |
| 71 | + $this->info('查询执行成功: ' . json_encode($result)); |
| 72 | + |
| 73 | + } catch (\Throwable $e) { |
| 74 | + $this->error('数据库连接测试失败: ' . $e->getMessage()); |
| 75 | + $this->error('文件: ' . $e->getFile() . ':' . $e->getLine()); |
| 76 | + $this->error('Trace: ' . $e->getTraceAsString()); |
| 77 | + } |
| 78 | + } |
| 79 | +} |
0 commit comments