Hello,
I have script that is connected to PostgreSQL and run 24x7.
Some times we need to restart PostgreSQL or some connection problem can occur, so script is needed to reconnect on this situations.

There are two ways:
1) check connection before every statement execution
2) check connection on errors

I decided to go by way 2, because I don't want to add extra overhead by calling ping() every time we execute statement
So my problem is how to be sure that DBI error is about "connection".
Here is my prototype based on 'Active' attribute and on state() method.
eval { $dbh->do(...); }; if (my $e = $@) { if ($dbh->{Active} != 1 || $dbh->state =~ /08\d{3}/){ # reconnect and retry } else { # not connection related error } }

Is it correct way?
And how to emulate connection lost for testing (maybe fork and close handler from child)?

update 2017-02-23
I emulated connection lost via fork:
unless (fork()) { $dbh->{InactiveDestroy} = 0; exit; } wait();
My observation shows that:
$dbh->{Active} == 1 even if dbh return "DBD::Pg::db selectrow_array failed: no connection to the server".
$dbh->{Active} == '' only if you explicitly call $dbh->disconnect;
But $dbh->state works like expected.

Still interesting in any production experience with robust handling for connection lost.

PS. To be sure that ping is really slow down I performed simple test
sub query { $dbh->selectrow_array(q{ SELECT now() }); } sub ping_and_query { $dbh->selectrow_array(q{ SELECT now() }) if $dbh->ping; } cmpthese(-2, { 'query' => \&query, 'ping+query' => \&ping_and_query, }); --- Rate ping+query query ping+query 6349/s -- -39% query 10327/s 63% --

In reply to Handle DBI connection lost by bash

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.