sid_com
sid_com

Reputation: 25117

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

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 );

Upvotes: 2

Views: 95

Answers (2)

zdim
zdim

Reputation: 66901

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 that this would trigger the destructor (DESTROY method) nor can I see that in 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 I'd add a check on $dbh before connecting, using (defined and) state and/or ping. Then, if previous work with it is indeed done and you want to overwrite it, first close it if needed. (Another option is to structure your code so that a new connection goes into a newly declared variable.)

Upvotes: 2

ikegami
ikegami

Reputation: 386206

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.

Upvotes: 2

Related Questions