AnyEvent::DBI and transactions

Andrey Khlopenov khlopenov.andrey at gmail.com
Tue Apr 15 12:53:53 CEST 2014


Hello.
Is there right way to work with AnyEvent::DBI and transactions?
#!/usr/bin/perl

use common::sense;
use AnyEvent;
use AnyEvent::DBI;

sub db_init {
  my %opts  = (@_);
  my $dbh   = delete $opts{'dbh'};

  undef $$dbh;
  $$dbh = new AnyEvent::DBI
    $opts{'c'},
    "",
    "",
    PrintError  =>  0,
    AutoCommit  =>  1,
    on_error    =>  sub {
      my $fatal = pop;

      chomp $@;
      print STDERR '[', AE::time, '|', $opts{'c'}, ']: ', $@, "\n";
      $fatal and db_init(dbh => $dbh, c => $opts{'c'});
    }
  ;
}

my $cv = AE::cv;
my $dbh; db_init(dbh => \$dbh, c => 'DBI:SQLite:dbname=_c.db');

foreach my $n (1 .. 10 * 10) {
  if ($n % 10 == 0) {

    my $commit = AE::cv {
      $dbh->commit(sub {
         $#_ ? $cv->end : $dbh->rollback(sub { $cv->end; });
      });
    };

    $dbh->begin_work(sub {
      my ($dbh, $rc) = @_;

      $#_ or return;
      $cv->begin;

      foreach (1 .. 10) {
        $commit->begin;
        $dbh->exec(
          "INSERT INTO data(rand) VALUES(abs(random()))",
          sub { $commit->end; }
        );
      }
    });
  }
}

$cv->recv;
undef $_ foreach ($dbh);

I receive an error "Already in a transaction" in 2 .. 10 iterations of
cycle(even if I do some hard work at begin of the cycle before each
transaction).
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://lists.schmorp.de/pipermail/anyevent/attachments/20140415/65792d16/attachment.html>


More information about the anyevent mailing list