Subject: | PATCH: add supports for code ref as connection option |
The attached patches for code / tests / docs further enhance the lazy
loading feature of the module. They allow me to do this:
DBI->connect( 'dbi:Multi:', undef, undef, {
dsns => [ # in priority order
10 => sub { $self->connect_db(1) },
10 => sub { $self->connect_db(2) },
],
});
This way, I can use a custom method call to generate the handle, but the
actual call is deferred until it needs to happen.
Mark
Subject: | handle-as-coderef.t |
# vim: ft=perl
use Test::More 'no_plan';
# $Id: dbd-multi-db.t,v 1.3 2006/02/10 18:47:47 wright Exp $
use strict;
$^W = 1;
use_ok 'DBD::Multi';
can_ok 'DBD::Multi::db', 'prepare';
my $c = DBI->connect('DBI:Multi:', undef, undef, {
dsns => [
1 => ['dbi:SQLite:one.db', '',''],
1 => sub { DBI->connect('DBI:SQLite:two.db') },
2 => ['dbi:SQLite:three.db','',''],
2 => sub { DBI->connect('DBI:SQLite:four.db') },
],
});
isa_ok $c, 'DBI::db';
cmp_ok scalar($c->data_sources), '==', 4, "data_sources returned some";
# one
my $sth = $c->prepare("CREATE TABLE multi(id int)");
isa_ok $sth, 'DBI::st';
# two
is $c->do("CREATE TABLE multi(id int)"), '0E0', 'do successful';
$SIG{__WARN__} = sub {}; # I don't want to hear it.
eval {
my $sth = $c->prepare("CREAATE TABLE multi(id int)");
};
ok $@, "$@";
unlink "$_.db" for qw[one two three four five six seven eight nine ten];
Subject: | dbd-multi-coderef.patch |
--- lib/DBD/Multi.pm.orig Tue Jan 16 15:24:07 2007
+++ lib/DBD/Multi.pm Tue Jan 16 15:32:10 2007
@@ -354,8 +354,12 @@
$dsource = $self->all_dsources->{$self->current_dsource};
}
+ # Support ready-made handles
return $dsource if UNIVERSAL::isa($dsource, 'DBI::db');
+ # Support code-refs which return handles
+ return $dsource->() if ref $dsource eq 'CODE';
+
my $dbh = DBI->connect_cached(@{$dsource});
return $dbh;
}
@@ -400,6 +404,7 @@
10 => [ 'dbi:SQLite:read_two.db', '', '' ],
20 => [ 'dbi:SQLite:master.db', '', '' ],
30 => $other_dbh,
+ 40 => sub { DBI->connect },
],
# optional
failed_max => 1, # short credibility
@@ -436,11 +441,11 @@
executing multiple queries on the same prepared statement handle will always
run on the same connection.
-The second parameter can either be a DBI object or a list of parameters to pass
-to the DBI C<connect()> instructor. If a set of parameters is given, then
-DBD::Multi will be able to attempt re-connect in the event that the connection
-is lost. If a DBI object is used, the DBD::Multi will give up permanently
-once that connection is lost.
+The second parameter can a DBI object, a code ref which returns a DBI object,
+or a list of parameters to pass to the DBI C<connect()> instructor. If a set
+of parameters or a code ref is given, then DBD::Multi will be able to attempt
+re-connect in the event that the connection is lost. If a DBI object is used,
+the DBD::Multi will give up permanently once that connection is lost.
=head2 Configuring Failures