Home > Mobile >  What happens if I assign two DBI connections in a row to a variable?
What happens if I assign two DBI connections in a row to a variable?

Time:01-12

What happens to the first connection if I assign two DBI connections in a row to a variable? It doesn't feel like there is an implicit disconnect (no lag).

my $dbh = DBI->connect( $dsn, $user, $pass );
$dbh = DBI->connect( $dsn, $user, $pass );

CodePudding user response:

The destructors of DBDs do close the connection.

I mean, it's possible that there's a DBD that leaks database connections out there, but that's highly unlikely and it would be a bug.

CodePudding user response:

One may connect multiple times with the exact same parameters. So I don't see a reason for connect to be checking whether there is any existing connection, and certainly not to touch (disconnect) it.

However, the object for this new connection then overwrites the Perl variable $dbh. At this point anything could happen since DBI uses tie-ed variables, but I don't see in sources how this would trigger the destructor (DESTROY method), and I don't see that in a couple of drivers' sources that I looked up (mySQL and Postgresql).

So it seems to me that in this way the handle on the first connection is just lost, and you effectively got a leak. If that is the case then it is also undefined what happens to possibly open transactions in the first connection.

So at least I'd add a check before connecting, using state and/or ping.

  • Related