Institute a central "load this first in testing" package
[dbsrgits/DBIx-Class.git] / t / storage / txn.t
1 BEGIN { do "./t/lib/ANFANG.pm" or die ( $@ || $! ) }
2
3 use strict;
4 use warnings;
5
6 use Test::More;
7 use Test::Warn;
8 use Test::Exception;
9
10 use DBICTest;
11
12 my $code = sub {
13   my ($artist, @cd_titles) = @_;
14
15   $artist->create_related('cds', {
16     title => $_,
17     year => 2006,
18   }) foreach (@cd_titles);
19
20   return $artist->cds->all;
21 };
22
23 # Test checking of parameters
24 {
25   my $schema = DBICTest->init_schema;
26
27   throws_ok (sub {
28     (ref $schema)->txn_do(sub{});
29   }, qr/storage/, "can't call txn_do without storage");
30
31   throws_ok {
32     $schema->txn_do('');
33   } qr/\Qrun() requires a coderef to execute as its first argument/,
34   '$coderef parameter check ok';
35 }
36
37 # Test successful txn_do() - scalar/list context
38 for my $want (0,1) {
39   my $schema = DBICTest->init_schema;
40
41   is( $schema->storage->transaction_depth, 0, 'txn depth starts at 0');
42
43   my @titles = map {'txn_do test CD ' . $_} (1..5);
44   my $artist = $schema->resultset('Artist')->find(1);
45   my $count_before = $artist->cds->count;
46
47   my @res;
48   if ($want) {
49     @res = $schema->txn_do($code, $artist, @titles);
50     is(scalar @res, $count_before+5, 'successful txn added 5 cds');
51   }
52   else {
53     $res[0] = $schema->txn_do($code, $artist, @titles);
54     is($res[0], $count_before+5, 'successful txn added 5 cds');
55   }
56
57   is($artist->cds({
58     title => "txn_do test CD $_",
59   })->first->year, 2006, "new CD $_ year correct") for (1..5);
60
61   is( $schema->storage->transaction_depth, 0, 'txn depth has been reset');
62 }
63
64 # Test txn_do() @_ aliasing support
65 {
66   my $schema = DBICTest->init_schema;
67
68   my $res = 'original';
69   $schema->storage->txn_do (sub { $_[0] = 'changed' }, $res);
70   is ($res, 'changed', "Arguments properly aliased for txn_do");
71 }
72
73 # Test nested successful txn_do()
74 {
75   my $schema = DBICTest->init_schema;
76
77   is( $schema->storage->transaction_depth, 0, 'txn depth starts at 0');
78
79   my $nested_code = sub {
80     my ($schema, $artist, $code) = @_;
81
82     my @titles1 = map {'nested txn_do test CD ' . $_} (1..5);
83     my @titles2 = map {'nested txn_do test CD ' . $_} (6..10);
84
85     $schema->txn_do($code, $artist, @titles1);
86     $schema->txn_do($code, $artist, @titles2);
87   };
88
89   my $artist = $schema->resultset('Artist')->find(2);
90   my $count_before = $artist->cds->count;
91
92   lives_ok (sub {
93     $schema->txn_do($nested_code, $schema, $artist, $code);
94   }, 'nested txn_do succeeded');
95
96   is($artist->cds({
97     title => 'nested txn_do test CD '.$_,
98   })->first->year, 2006, qq{nested txn_do CD$_ year ok}) for (1..10);
99   is($artist->cds->count, $count_before+10, 'nested txn_do added all CDs');
100
101   is( $schema->storage->transaction_depth, 0, 'txn depth has been reset');
102 }
103
104 # test nested txn_begin on fresh connection
105 {
106   my $schema = DBICTest->init_schema(sqlite_use_file => 1, no_deploy => 1);
107   $schema->storage->ensure_connected;
108
109   is ($schema->storage->transaction_depth, 0, 'Start outside txn');
110
111   my @pids;
112   SKIP:
113   for my $action (
114     sub {
115       my $s = shift;
116       die "$$ starts in txn!" if $s->storage->transaction_depth != 0;
117       $s->txn_do ( sub {
118         die "$$ not in txn!" if $s->storage->transaction_depth == 0;
119         $s->storage->dbh->do('SELECT 1') }
120       );
121       die "$$ did not finish txn!" if $s->storage->transaction_depth != 0;
122     },
123     sub {
124       $_[0]->txn_begin;
125       $_[0]->storage->dbh->do('SELECT 1');
126       $_[0]->txn_commit
127     },
128     sub {
129       my $guard = $_[0]->txn_scope_guard;
130       $_[0]->storage->dbh->do('SELECT 1');
131       $guard->commit
132     },
133   ) {
134     my $pid = fork();
135
136     if( ! defined $pid ) {
137       skip "EAGAIN encountered, your system is likely bogged down: skipping forking test", 1
138         if $! == Errno::EAGAIN();
139
140       die "Unable to fork: $!"
141     }
142
143     if ($pid) {
144       push @pids, $pid;
145       next;
146     }
147
148     $action->($schema);
149     exit 0;
150   }
151
152   is ($schema->storage->transaction_depth, 0, 'Parent still outside txn');
153
154   for my $pid (@pids) {
155     waitpid ($pid, 0);
156     ok (! $?, "Child $pid exit ok");
157   }
158 }
159
160 # Test txn_do/scope_guard with forking: outer txn_do
161 {
162   my $schema = DBICTest->init_schema( sqlite_use_file => 1 );
163
164   for my $pass (1..2) {
165
166     # do something trying to destabilize the depth count
167     for (1..2) {
168       eval {
169         my $guard = $schema->txn_scope_guard;
170         $schema->txn_do( sub { die } );
171       };
172       is( $schema->storage->transaction_depth, 0, 'Transaction successfully aborted' );
173       $schema->txn_do( sub {
174         ok ($schema->storage->_dbh->do ('SELECT 1'), "Query after exceptions ok ($_)");
175       });
176     }
177
178     $schema->txn_do ( sub { _test_forking_action ($schema, $pass) } );
179   }
180 }
181
182 # same test with outer guard
183 {
184   my $schema = DBICTest->init_schema( sqlite_use_file => 1 );
185
186   for my $pass (1..2) {
187
188     # do something trying to destabilize the depth count
189     for (1..2) {
190       eval {
191         my $guard = $schema->txn_scope_guard;
192         $schema->txn_do( sub { die } );
193       };
194       is( $schema->storage->transaction_depth, 0, 'Transaction successfully aborted' );
195       $schema->txn_do( sub {
196         ok ($schema->storage->_dbh->do ('SELECT 1'), "Query after exceptions ok ($_)");
197       });
198     }
199
200     my $guard = $schema->txn_scope_guard;
201     my @pids = _test_forking_action ($schema, $pass);
202     $guard->commit;
203   }
204 }
205
206 sub _test_forking_action {
207   my ($schema, $pass) = @_;
208
209   my @pids;
210
211   SKIP: for my $count (1 .. 5) {
212
213     skip 'Weird DBI General Protection Faults, skip forking tests (RT#63104)', 5
214       if $^O eq 'MSWin32';
215
216     my $pid = fork();
217     if( ! defined $pid ) {
218
219       skip "EAGAIN encountered, your system is likely bogged down: skipping forking test", 1
220         if $! == Errno::EAGAIN();
221
222       die "Unable to fork: $!"
223     }
224
225     if ($pid) {
226       push @pids, $pid;
227       next;
228     }
229
230     if ($count % 2) {
231       $schema->txn_do (sub {
232         my $depth = $schema->storage->transaction_depth;
233         die "$$(txn_do)unexpected txn depth $depth!" if $depth != 1;
234         $schema->resultset ('Artist')->create ({ name => "forking action $$"});
235       });
236     }
237     else {
238       my $guard = $schema->txn_scope_guard;
239       my $depth = $schema->storage->transaction_depth;
240       die "$$(scope_guard) unexpected txn depth $depth!" if $depth != 1;
241       $schema->resultset ('Artist')->create ({ name => "forking action $$"});
242       $guard->commit;
243     }
244
245     exit 0;
246   }
247
248   for my $pid (@pids) {
249     waitpid ($pid, 0);
250     ok (! $?, "Child $pid exit ok (pass $pass)");
251   }
252
253   # it is important to reap all children before checking the final db-state
254   # otherwise a deadlock may occur between the transactions running in the
255   # children and the query of the parent
256   for my $pid (@pids) {
257     isa_ok ($schema->resultset ('Artist')->find ({ name => "forking action $pid" }), 'DBIx::Class::Row');
258   }
259 }
260
261 my $fail_code = sub {
262   my ($artist) = @_;
263   $artist->create_related('cds', {
264     title => 'this should not exist',
265     year => 2005,
266   });
267   die "the sky is falling";
268 };
269
270 {
271   my $schema = DBICTest->init_schema;
272
273   # Test failed txn_do()
274   for my $pass (1,2) {
275
276     is( $schema->storage->transaction_depth, 0, "txn depth starts at 0 (pass $pass)");
277
278     my $artist = $schema->resultset('Artist')->find(3);
279
280     throws_ok (sub {
281       $schema->txn_do($fail_code, $artist);
282     }, qr/the sky is falling/, "failed txn_do threw an exception (pass $pass)");
283
284     my $cd = $artist->cds({
285       title => 'this should not exist',
286       year => 2005,
287     })->first;
288     ok(!defined($cd), qq{failed txn_do didn't change the cds table (pass $pass)});
289
290     is( $schema->storage->transaction_depth, 0, "txn depth has been reset (pass $pass)");
291   }
292
293
294   # Test failed txn_do() with failed rollback
295   {
296     is( $schema->storage->transaction_depth, 0, 'txn depth starts at 0');
297
298     my $artist = $schema->resultset('Artist')->find(3);
299
300     # Force txn_rollback() to throw an exception
301     no warnings qw/once redefine/;
302
303     # this should logically work just fine - but it does not,
304     # only direct override of the existing method dtrt
305     #local *DBIx::Class::Storage::DBI::SQLite::txn_rollback = sub { die 'FAILED' };
306
307     local *DBIx::Class::Storage::DBI::txn_rollback = sub { die 'FAILED' };
308     Class::C3->reinitialize() if DBIx::Class::_ENV_::OLD_MRO;
309
310     throws_ok (
311       sub {
312         $schema->txn_do($fail_code, $artist);
313       },
314       qr/the sky is falling.+Rollback failed/s,
315       'txn_rollback threw a rollback exception (and included the original exception'
316     );
317
318     my $cd = $artist->cds({
319       title => 'this should not exist',
320       year => 2005,
321     })->first;
322     isa_ok($cd, 'DBICTest::CD', q{failed txn_do with a failed txn_rollback }.
323            q{changed the cds table});
324     $cd->delete; # Rollback failed
325     $cd = $artist->cds({
326       title => 'this should not exist',
327       year => 2005,
328     })->first;
329     ok(!defined($cd), q{deleted the failed txn's cd});
330     $schema->storage->_dbh->rollback;
331   }
332 }
333
334 # Test nested failed txn_do()
335 {
336   my $schema = DBICTest->init_schema();
337
338   is( $schema->storage->transaction_depth, 0, 'txn depth starts at 0');
339
340   my $nested_fail_code = sub {
341     my ($schema, $artist, $code1, $code2) = @_;
342
343     my @titles = map {'nested txn_do test CD ' . $_} (1..5);
344
345     $schema->txn_do($code1, $artist, @titles); # successful txn
346     $schema->txn_do($code2, $artist);          # failed txn
347   };
348
349   my $artist = $schema->resultset('Artist')->find(3);
350
351   throws_ok ( sub {
352     $schema->txn_do($nested_fail_code, $schema, $artist, $code, $fail_code);
353   }, qr/the sky is falling/, 'nested failed txn_do threw exception');
354
355   ok(!defined($artist->cds({
356     title => 'nested txn_do test CD '.$_,
357     year => 2006,
358   })->first), qq{failed txn_do didn't add first txn's cd $_}) for (1..5);
359   my $cd = $artist->cds({
360     title => 'this should not exist',
361     year => 2005,
362   })->first;
363   ok(!defined($cd), q{failed txn_do didn't add failed txn's cd});
364 }
365
366
367 # Grab a new schema to test txn before connect
368 # also test nested txn exception
369 {
370   my $schema = DBICTest->init_schema(no_deploy => 1);
371   lives_ok (sub {
372     $schema->txn_begin();
373     $schema->txn_begin();
374   }, 'Pre-connection nested transactions.');
375
376   throws_ok( sub { $schema->txn_rollback }, 'DBIx::Class::Storage::NESTED_ROLLBACK_EXCEPTION', 'got proper nested rollback exception' );
377 }
378
379 # make sure AutoCommit => 0 on external handles behaves correctly with scope_guard
380 warnings_are {
381   my $factory = DBICTest->init_schema;
382   cmp_ok ($factory->resultset('CD')->count, '>', 0, 'Something to delete');
383   my $dbh = $factory->storage->dbh;
384   $dbh->{AutoCommit} = 0;
385
386   ok (!$dbh->{AutoCommit}, 'AutoCommit is off on $dbh');
387   my $schema = DBICTest::Schema->connect (sub { $dbh });
388
389   lives_ok ( sub {
390     my $guard = $schema->txn_scope_guard;
391     $schema->resultset('CD')->delete;
392     $guard->commit;
393   }, 'No attempt to start a transaction with scope guard');
394
395   is ($schema->resultset('CD')->count, 0, 'Deletion successful in txn');
396
397   # this will commit the implicitly started txn
398   $dbh->commit;
399
400 } [], 'No warnings on AutoCommit => 0 with txn_guard';
401
402 # make sure AutoCommit => 0 on external handles behaves correctly with txn_do
403 warnings_are {
404   my $factory = DBICTest->init_schema;
405   cmp_ok ($factory->resultset('CD')->count, '>', 0, 'Something to delete');
406   my $dbh = $factory->storage->dbh;
407   $dbh->{AutoCommit} = 0;
408
409   ok (!$dbh->{AutoCommit}, 'AutoCommit is off on $dbh');
410   my $schema = DBICTest::Schema->connect (sub { $dbh });
411
412   lives_ok ( sub {
413     $schema->txn_do (sub { $schema->resultset ('CD')->delete });
414   }, 'No attempt to start a atransaction with txn_do');
415
416   is ($schema->resultset('CD')->count, 0, 'Deletion successful');
417
418   # this will commit the implicitly started txn
419   $dbh->commit;
420
421 } [], 'No warnings on AutoCommit => 0 with txn_do';
422
423
424 # make sure we are not fucking up the stacktrace on broken overloads
425 {
426   package DBICTest::BrokenOverload;
427
428   use overload '""' => sub { $_[0] };
429 }
430
431 {
432   my @w;
433   local $SIG{__WARN__} = sub {
434     $_[0] =~ /\QExternal exception class DBICTest::BrokenOverload implements partial (broken) overloading preventing its instances from being used in simple (\E\$x eq \$y\Q) comparisons/
435       ? push @w, @_
436       : warn @_
437   };
438
439   my $s = DBICTest->init_schema(no_deploy => 1);
440   $s->stacktrace(0);
441   my $g = $s->storage->txn_scope_guard;
442   my $broken_exception = bless {}, 'DBICTest::BrokenOverload';
443
444   # FIXME - investigate what confuses the regex engine below
445
446   # do not reformat - line-num part of the test
447   my $ln = __LINE__ + 6;
448   throws_ok {
449     $s->txn_do( sub {
450       $s->txn_do( sub {
451         $s->storage->_dbh->disconnect;
452         die $broken_exception
453       });
454     })
455   } qr/\QTransaction aborted: $broken_exception. Rollback failed: DBIx::Class::Storage::DBI::txn_rollback(): lost connection to storage at @{[__FILE__]} line $ln\E\n/;  # FIXME wtf - ...\E$/m doesn't work here
456
457   is @w, 1, 'One matching warning only';
458
459   # try the same broken exception object, but have exception_action inject it
460   $s->exception_action(sub { die $broken_exception });
461   eval {
462     $s->txn_do( sub {
463       die "some string masked away";
464     });
465   };
466   isa_ok $@, 'DBICTest::BrokenOverload', 'Deficient exception properly propagated';
467
468   is @w, 2, 'The warning was emitted a second time';
469 }
470
471 done_testing;