Beefy Boxes and Bandwidth Generously Provided by pair Networks
Just another Perl shrine
 
PerlMonks  

Interpolate binds into SQL on error - DBI subclassing

by jZed (Prior)
on Oct 11, 2005 at 18:51 UTC ( #499253=snippet: print w/ replies, xml ) Need Help??

Description: Here's a minimal subclass of DBI that illustrates how to subclass and adds interpolated binds to errors (i.e. it replaces SQL placeholders with the bind values). This isn't necessarily how your DBMS "sees" the statement, but it does give you a cut-and-pasteable approximation.

update Added Corion's fix to support questions marks in the bind values.

package MyDBI;
use base qw(DBI);

package MyDBI::db;
use base qw(DBI::db);

package MyDBI::st;
use base qw(DBI::st);

sub execute {
    my($sth,@binds)=@_;
    my $rv = eval { $sth->SUPER::execute(@binds) };
    return $rv unless $@;
    my $errmsg = $sth->errstr;
    my $err    = $sth->err   ;
    my $stmt = $sth->{Statement};
    @binds = map {
        $sth->{Database}->quote($_) 
        unless DBI::looks_like_number($_);
        $_;
    } @binds;
    $stmt =~ s/\?/shift @binds/eg;
    return $sth->set_err(
         $err,
         sprintf "Execution Error: %s\nReconstructed SQL=\n<\n%s\n>\n"
               , $errmsg, $stmt
    );
}
1;
Comment on Interpolate binds into SQL on error - DBI subclassing
Download Code
Re: Interpolate binds into SQL on error - DBI subclassing
by Corion (Pope) on Oct 11, 2005 at 19:13 UTC

    This snippet will fail if the interpolated values themselves contain question marks - I would go for an eval-replace in the inner loop:

    for my $b(@binds) { $b=$sth->{Database}->quote($b) unless DBI::looks_like_number($b); }; $stmt =~ s/\?/shift @binds/eg;

Back to Snippets Section

Log In?
Username:
Password:

What's my password?
Create A New User
Node Status?
node history
Node Type: snippet [id://499253]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others taking refuge in the Monastery: (9)
As of 2014-12-27 19:52 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    Is guessing a good strategy for surviving in the IT business?





    Results (177 votes), past polls