| 1 | use strict; | ||
| 2 | use warnings; | ||
| 3 | package Search::GIN::Driver::TXN; | ||
| 4 | |||
| 5 | our $VERSION = '0.11'; | ||
| 6 | |||
| 7 | use Moose::Role; | ||
| 8 | use Scope::Guard; | ||
| 9 | use Carp qw(croak); | ||
| 10 | use namespace::autoclean; | ||
| 11 | |||
| 12 | with qw(Search::GIN::Driver); | ||
| 13 | |||
| 14 | requires qw(txn_begin txn_commit txn_rollback); | ||
| 15 | |||
| 16 | has current_transaction => ( | ||
| 17 | isa => "Any", | ||
| 18 | is => "rw", | ||
| 19 | writer => "set_current_transaction", | ||
| 20 | predicate => "has_current_transaction", | ||
| 21 | clearer => "clear_current_transaction", | ||
| 22 | ); | ||
| 23 | |||
| 24 | sub txn_do { | ||
| 25 | my ( $self, $coderef ) = ( shift, shift ); | ||
| 26 | |||
| 27 | ref $coderef eq 'CODE' or croak '$coderef must be a CODE reference'; | ||
| 28 | |||
| 29 | my ( $txn, $scope_guard ); | ||
| 30 | |||
| 31 | if ( $self->has_current_transaction ) { | ||
| 32 | my $prev = $self->current_transaction; | ||
| 33 | $txn = $self->txn_begin($prev); | ||
| 34 | $scope_guard = Scope::Guard->new(sub { $self->set_current_transaction($prev) }); | ||
| 35 | } else { | ||
| 36 | $txn = $self->txn_begin; | ||
| 37 | $scope_guard = Scope::Guard->new(sub { $self->clear_current_transaction() }); | ||
| 38 | } | ||
| 39 | |||
| 40 | my @result; | ||
| 41 | my $want_array = wantarray; | ||
| 42 | |||
| 43 | my $err = do { | ||
| 44 | local $@; | ||
| 45 | eval { | ||
| 46 | if ( $want_array ) { | ||
| 47 | @result = $coderef->(@_); | ||
| 48 | } elsif( defined $want_array ) { | ||
| 49 | $result[0] = $coderef->(@_); | ||
| 50 | } else { | ||
| 51 | $coderef->(@_); | ||
| 52 | } | ||
| 53 | |||
| 54 | $self->txn_commit($txn); | ||
| 55 | |||
| 56 | 1; | ||
| 57 | }; | ||
| 58 | |||
| 59 | $@ | ||
| 60 | }; | ||
| 61 | |||
| 62 | if ( !$err ) { | ||
| 63 | return $want_array ? @result : $result[0]; | ||
| 64 | } else { | ||
| 65 | my $rollback_exception = do { | ||
| 66 | local $@; | ||
| 67 | eval { $self->txn_rollback($txn) }; | ||
| 68 | $@; | ||
| 69 | }; | ||
| 70 | |||
| 71 | if ($rollback_exception) { | ||
| 72 | croak "Transaction aborted: $err, rollback failed: $rollback_exception"; | ||
| 73 | } else { | ||
| 74 | die $err; | ||
| 75 | } | ||
| 76 | } | ||
| 77 | } | ||
| 78 | |||
| 79 | 1; |