roddik has asked for the wisdom of the Perl Monks concerning the following question:

Hello,

I'm writing an application using the DBI module and want to achieve the following: (while typing this part, I thought that it would be better to just post code first :))

use DBI; use POE; my $dbh = DBI->connect('dbi:mysql:****', '****', '****', {RaiseError = +> 1}); POE::Session->create(inline_states => {_start => \&tester}, heap => + {dbh => $dbh->clone()}); POE::Session->create(inline_states => {_start => \&tester}, heap => + {dbh => $dbh->clone()}); POE::Kernel->run(); sub tester { my $heap = $_[HEAP]; for my $key (@{$heap->{dbh}->selectcol_arrayref("SELECT id, sleep( +0.1) FROM mytable WHERE 1")}) { print $key; } }
The intended result for 'mytable' having 5 ids is 1122334455, instead I see 1234512345, that is, when trying to access MySQL, even with different handlers, one session waits until another is over. Trying to use the original dbh (without clone-ing) yields the same result.

So I tried to use threads instead

my @threads; for my $i (1..2) { push @threads, threads->create(\&testsub, $dbh->clone()); } foreach my $thread (@threads) { $thread->join(); } sub testsub { for my $key (@{$_[0]->selectcol_arrayref("SELECT id, sleep(0.1) FROM + keywords WHERE 1")}) { print $key; } }
and got the following error Thread 1 terminated abnormally: DBD::mysql::db selectcol_arrayref failed: handle 2 is owned by thread 225054 not current thread 1e60c2c (handles can't be shared between threads and your driver may need a CLONE method added)

Of course, the straightforward solution is to read everything from the DB, and then send it to the subs as a parameter, but I'm highly reluctant to use this method, because 1) I don't know, which fields do the subs need 2) The subs were made to insert some data to database while working 3) the DB can be large, very large

Thanks for help with making some threads/sessions use one db handle simultaneosly, or, if not possible, any suggestions on the design of the application!

Replies are listed 'Best First'.
Re: Simultaneous access to database
by Fletch (Bishop) on Aug 22, 2008 at 14:01 UTC

    There are several modules on CPAN (e.g. POE::Component::DBIAgent which was based on some stuff I wrote and forwarded the POE list which was subsequently cleaned up, improved on, and packaged by someone else; there's others as well if that doesn't do it, just search for "POE DBI") which give a more POE-y interface by setting up a separate session to manage a db connection. That might be of use here.

    The cake is a lie.
    The cake is a lie.
    The cake is a lie.

Re: Simultaneous access to database
by Anonymous Monk on Aug 22, 2008 at 13:49 UTC
    use 2

      I used 2 but I don't anymore. <rimshot/>