I wanted to add a few convenience methods to statement handles (as if it didn't have enough already). Specifically, I wanted to be able to do
$sth->selectrow_arrayref(...)
when the existing convention is
$dbh->selectrow_arrayref($sth, ...)
Here's the approach I took:
use strict;
use warnings;
use DBI qw( );
# ----------------------------------------
BEGIN {
package MyDBI;
our @ISA = 'DBI';
}
# ----------------------------------------
BEGIN {
package MyDBI::db;
our @ISA = 'DBI::db';
}
# ----------------------------------------
BEGIN {
package MyDBI::st;
our @ISA = 'DBI::st';
sub bind_params {
my $sth = $_[0];
for my $i (1..$#_) {
$sth->bind_param($i, $_[$i])
or return;
}
return 1;
}
sub _do_selectrow {
my ($method, $sth, $attr) = splice(@_, 0, 3);
$sth->execute(@_)
or return;
my $row = $sth->$method()
or return;
$sth->finish();
return $row;
}
sub _do_firstrow {
my ($method, $sth, $attr) = splice(@_, 0, 3);
$sth->execute(@_)
or return;
my $row = $sth->$method()
or return $sth->set_err($DBI::stderr, "No rows returned");
$sth->finish();
return $row;
}
sub selectrow_hashref { return _do_selectrow('fetchrow_hashref', @
+_); }
sub firstrow_hashref { return _do_firstrow ('fetchrow_hashref', @
+_); }
sub selectrow_arrayref { return _do_selectrow('fetchrow_arrayref',
+@_); }
sub firstrow_arrayref { return _do_firstrow ('fetchrow_arrayref',
+@_); }
sub selectrow_array { my $row = _do_selectrow('fetchrow_arrayref
+', @_) or return; return wantarray ? @$row : $row->[0]; }
sub firstrow_array { my $row = _do_firstrow ('fetchrow_arrayref
+', @_) or return; return wantarray ? @$row : $row->[0]; }
}
# ----------------------------------------
1;
You could surely override do using this method. Create the three classes, setup their inheritance relationship, and override do in ::db.