Framework: Additiona read or write connection opened on reconnect with DB::disconnect()

Created on 27 Dec 2019  路  7Comments  路  Source: laravel/framework

  • Laravel Version: 6.2
  • PHP Version: 7.2
  • Database Driver & Version: MySQL

Description:

  • When using read and write connections, calling DB::disconnect() and then executing a select query opens a connection to both read and write DB instead of just read. The same happens other way around, if you execute a write query after DB::disconnect() it opens both write and read instead of only write.

  • DB::disconnect() sets both readPdo and pdo to null. In DatabaseManager.php reconnect() calls refreshPdoConnections() that unnecessarily opens both read and write connections to the DB.

  • Using DB::purge() instead solves the problem scrapping the connection and not using the reconnect() when executing a new query.

I could use purge instead but I wonder if there is any downside to it. Seems like disconnect() and reconnect() are opening an unnecessary connection. This causes problems since it can potentially stop both write and read DB in situations when there are too many connections.

Steps To Reproduce:

Set up both a read and write DB in your database.php

Without disconnect

$user = DB::table('users')->first();
sleep(15); 

show full processlist on mysql returns 1 open connection on read and 0 on write for the app.

With disconnect

$user = DB::table('users')->first();
DB::disconnect();
$user = DB::table('users')->first();
sleep(15); 

show full processlist on mysql returns 1 open connection on read and 1 on write for the app.

bug

All 7 comments

I do wonder how your connections are set up. disconnect on the DatabaseManager only disconnects the default connection. How are your connections named?

I followed the official documentation for read and write configurations.

https://laravel.com/docs/6.x/database#read-and-write-connections

So basically my connections are named like this

'mysql' => [
    'read' => [
        'host' => [
            '192.168.1.1',
        ],
    ],
    'write' => [
        'host' => [
            '196.168.1.3',
         ],
    ],
    ...
]

I also tried using disconnect('mysql), with the same result.

I can verify the issue and opened a PR with a proposed fix in https://github.com/laravel/framework/pull/30998

@bernardwiesner you're linking to the 4.2 docs btw.

@driesvints
Sorry about that, was searching on my phone and that's what came up first, updated it with 6.x.

Pr was merged

Cool :)

Was this page helpful?
0 / 5 - 0 ratings