44
55namespace App \Proxy \Executor ;
66
7- use Hyperf \DB \ DB ;
7+ use Hyperf \DbConnection \ Db ;
88use App \Protocol \MySql \Packet ;
99use Hyperf \Logger \LoggerFactory ;
1010use Psr \Log \LoggerInterface ;
@@ -40,11 +40,19 @@ public function execute(string $sql): array
4040
4141 try {
4242 // 使用 Hyperf 数据库连接执行 SQL
43+ /** @var \Hyperf\DbConnection\Connection $connection */
4344 $ connection = DB ::connection ('backend_mysql ' );
4445
4546 // 对于 SELECT 查询,使用 select 方法
46- if (stripos (trim ($ sql ), 'select ' ) === 0 ) {
47+ // 支持前置注释(例如 MySQL Connector/J 会在前面带注释),所以使用正则去除注释后判断
48+ if (preg_match ('/^\s*(?:\/\*[\s\S]*?\*\/\s*)*(select)\b/i ' , $ sql ) === 1 ) {
4749 $ result = $ connection ->select ($ sql );
50+ // 某些 PDO 驱动或数据库层返回对象(stdClass),但下游期望关联数组
51+ if (!empty ($ result )) {
52+ $ result = array_map (function ($ row ) {
53+ return is_array ($ row ) ? $ row : (array ) $ row ;
54+ }, $ result );
55+ }
4856
4957 $ elapsedMs = (int ) ((microtime (true ) - $ startTime ) * 1000 );
5058
@@ -58,7 +66,22 @@ public function execute(string $sql): array
5866 } else {
5967 // 对于其他查询(如 INSERT, UPDATE, DELETE),使用 statement 方法
6068 $ affectedRows = $ connection ->statement ($ sql );
61- $ lastInsertId = $ connection ->getPdo ()->lastInsertId ();
69+ // 某些驱动 statement() 返回 bool 而非受影响行数,统一转换为 int
70+ if (is_bool ($ affectedRows )) {
71+ $ affectedRows = $ affectedRows ? 1 : 0 ;
72+ } else {
73+ $ affectedRows = (int ) $ affectedRows ;
74+ }
75+ // 尝试通过可用方法获取最后插入 ID
76+ $ lastInsertId = 0 ;
77+ if (method_exists ($ connection , 'getPdo ' )) {
78+ $ pdo = $ connection ->getPdo ();
79+ if ($ pdo instanceof \PDO ) {
80+ $ lastInsertId = (int ) $ pdo ->lastInsertId ();
81+ }
82+ } elseif (method_exists ($ connection , 'lastInsertId ' )) {
83+ $ lastInsertId = (int ) $ connection ->lastInsertId ();
84+ }
6285
6386 $ elapsedMs = (int ) ((microtime (true ) - $ startTime ) * 1000 );
6487
@@ -236,14 +259,25 @@ public function getPoolStats(): array
236259 {
237260 // 使用 Hyperf 的连接池统计
238261 try {
262+ /** @var \Hyperf\DbConnection\Connection $connection */
239263 $ connection = DB ::connection ('backend_mysql ' );
240- $ pool = $ connection ->getPool ();
264+ // 使用动态检测以兼容不同 DB 实现
265+ if (method_exists ($ connection , 'getPool ' )) {
266+ $ pool = $ connection ->getPool ();
267+ return [
268+ 'pool_type ' => 'hyperf ' ,
269+ 'pool_name ' => 'backend_mysql ' ,
270+ 'connections_count ' => $ pool ->getConnectionsCount (),
271+ 'idle_connections_count ' => $ pool ->getIdleConnectionsCount (),
272+ ];
273+ }
241274
275+ // 如果没有 pool 支持,则返回基础信息
242276 return [
243277 'pool_type ' => 'hyperf ' ,
244278 'pool_name ' => 'backend_mysql ' ,
245- 'connections_count ' => $ pool -> getConnectionsCount () ,
246- 'idle_connections_count ' => $ pool -> getIdleConnectionsCount () ,
279+ 'connections_count ' => null ,
280+ 'idle_connections_count ' => null ,
247281 ];
248282 } catch (\Throwable $ e ) {
249283 return [
0 commit comments