Rewrite txn_do and dbh_do to use a (hidden for now) blockrunner
[dbsrgits/DBIx-Class.git] / t / 52leaks.t
CommitLineData
66917da3 1# work around brain damage in PPerl (yes, it has to be a global)
2$SIG{__WARN__} = sub {
3 warn @_ unless $_[0] =~ /\QUse of "goto" to jump into a construct is deprecated/
4} if ($ENV{DBICTEST_IN_PERSISTENT_ENV});
5
6# the persistent environments run with this flag first to see if
7# we will run at all (e.g. it will fail if $^X doesn't match)
8exit 0 if $ENV{DBICTEST_PERSISTENT_ENV_BAIL_EARLY};
9
f05edfd1 10# Do the override as early as possible so that CORE::bless doesn't get compiled away
11# We will replace $bless_override only if we are in author mode
12my $bless_override;
13BEGIN {
14 $bless_override = sub {
15 CORE::bless( $_[0], (@_ > 1) ? $_[1] : caller() );
16 };
17 *CORE::GLOBAL::bless = sub { goto $bless_override };
18}
19
50261284 20use strict;
21use warnings;
a917fb06 22use Test::More;
d5e5fb4b 23
66917da3 24my $TB = Test::More->builder;
25if ($ENV{DBICTEST_IN_PERSISTENT_ENV}) {
26 # without this explicit close ->reset below warns
27 close ($TB->$_) for qw/output failure_output/;
28
29 # so done_testing can work
30 $TB->reset;
31
32 # this simulates a subtest
33 $TB->_indent(' ' x 4);
34}
35
d5e5fb4b 36use lib qw(t/lib);
37use DBICTest::RunMode;
e0b2dc74 38use DBIx::Class;
dee99c24 39use B 'svref_2object';
d12d8272 40BEGIN {
d5e5fb4b 41 plan skip_all => "Your perl version $] appears to leak like a sieve - skipping test"
dee99c24 42 if DBIx::Class::_ENV_::PEEPEENESS;
d12d8272 43}
44
a8c2c746 45use Scalar::Util qw/refaddr reftype weaken/;
a917fb06 46
a8c2c746 47# this is what holds all weakened refs to be checked for leakage
48my $weak_registry = {};
49
6a43bc0c 50# whether or to invoke IC::DT
51my $has_dt;
52
a8c2c746 53# Skip the heavy-duty leak tracing when just doing an install
54unless (DBICTest::RunMode->is_plain) {
f05edfd1 55
eb7aa960 56 # have our own little stack maker - Carp infloops due to the bless override
57 my $trace = sub {
58 my $depth = 1;
59 my (@stack, @frame);
60
61 while (@frame = caller($depth++)) {
62 push @stack, [@frame[3,1,2]];
63 }
6a43bc0c 64
eb7aa960 65 $stack[0][0] = '';
66 return join "\tinvoked as ", map { sprintf ("%s at %s line %d\n", @$_ ) } @stack;
67 };
68
69 # redefine the bless override so that we can catch each and every object created
a8c2c746 70 no warnings qw/redefine once/;
71 no strict qw/refs/;
72
f05edfd1 73 $bless_override = sub {
74
a8c2c746 75 my $obj = CORE::bless(
76 $_[0], (@_ > 1) ? $_[1] : do {
77 my ($class, $fn, $line) = caller();
78 fail ("bless() of $_[0] into $class without explicit class specification at $fn line $line")
79 if $class =~ /^ (?: DBIx\:\:Class | DBICTest ) /x;
80 $class;
81 }
82 );
83
84 my $slot = (sprintf '%s=%s(0x%x)', # so we don't trigger stringification
85 ref $obj,
86 reftype $obj,
87 refaddr $obj,
88 );
89
90 # weaken immediately to avoid weird side effects
eb7aa960 91 $weak_registry->{$slot} = { weakref => $obj, strace => $trace->() };
a8c2c746 92 weaken $weak_registry->{$slot}{weakref};
93
94 return $obj;
95 };
96
eb7aa960 97 require Try::Tiny;
a8c2c746 98 for my $func (qw/try catch finally/) {
99 my $orig = \&{"Try::Tiny::$func"};
100 *{"Try::Tiny::$func"} = sub (&;@) {
101
102 my $slot = sprintf ('CODE(0x%x)', refaddr $_[0]);
103
eb7aa960 104 $weak_registry->{$slot} = { weakref => $_[0], strace => $trace->() };
a8c2c746 105 weaken $weak_registry->{$slot}{weakref};
106
107 goto $orig;
108 }
109 }
eb7aa960 110
111 # Some modules are known to install singletons on-load
112 # Load them and empty the registry
113
114 # this loads the DT armada
115 $has_dt = DBIx::Class::Optional::Dependencies->req_ok_for('test_dt_sqlite');
116
117 require Errno;
118 require DBI;
119 require DBD::SQLite;
120 require FileHandle;
121
122 %$weak_registry = ();
a8c2c746 123}
124
dee99c24 125my @compose_ns_classes;
a8c2c746 126{
66917da3 127 use_ok ('DBICTest');
a917fb06 128
a8c2c746 129 my $schema = DBICTest->init_schema;
130 my $rs = $schema->resultset ('Artist');
131 my $storage = $schema->storage;
a917fb06 132
dee99c24 133 @compose_ns_classes = map { "DBICTest::${_}" } keys %{$schema->source_registrations};
134
a8c2c746 135 ok ($storage->connected, 'we are connected');
a917fb06 136
052b8ce2 137 my $row_obj = $rs->search({}, { rows => 1})->next; # so that commits/rollbacks work
a8c2c746 138 ok ($row_obj, 'row from db');
139
052b8ce2 140 # txn_do to invoke more codepaths
a8c2c746 141 my ($mc_row_obj, $pager, $pager_explicit_count) = $schema->txn_do (sub {
142
9345b14c 143 my $artist = $schema->resultset('Artist')->create ({
a8c2c746 144 name => 'foo artist',
145 cds => [{
146 title => 'foo cd',
147 year => 1984,
187ec69a 148 tracks => [
149 { title => 't1' },
150 { title => 't2' },
151 ],
152 genre => { name => 'mauve' },
a8c2c746 153 }],
154 });
155
156 my $pg = $rs->search({}, { rows => 1})->page(2)->pager;
157
158 my $pg_wcount = $rs->page(4)->pager->total_entries (66);
159
160 return ($artist, $pg, $pg_wcount);
161 });
162
9345b14c 163 # more codepaths - error handling in txn_do
164 {
165 eval { $schema->txn_do ( sub {
166 $storage->_dbh->begin_work;
167 fail ('how did we get so far?!');
168 } ) };
169
170 eval { $schema->txn_do ( sub {
171 $schema->txn_do ( sub {
172 die "It's called EXCEPTION";
173 fail ('how did we get so far?!');
174 } );
175 fail ('how did we get so far?!');
176 } ) };
177 like( $@, qr/It\'s called EXCEPTION/, 'Exception correctly propagated in nested txn_do' );
178 }
179
180 # dbh_do codepath
187ec69a 181 my ($rs_bind_circref, $cond_rowobj) = $schema->storage->dbh_do ( sub {
182 my $row = $_[0]->schema->resultset('Artist')->new({});
183 my $rs = $_[0]->schema->resultset('Artist')->search({
184 name => $row, # this is deliberately bogus, see FIXME below!
185 });
186 return ($rs, $row);
187 });
188
a8c2c746 189 is ($pager->next_page, 3, 'There is one more page available');
190
191 # based on 66 per 10 pages
192 is ($pager_explicit_count->last_page, 7, 'Correct last page');
551e711a 193
052b8ce2 194 # do some population (invokes some extra codepaths)
195 # also exercise the guard code and the manual txn control
196 {
197 my $guard = $schema->txn_scope_guard;
198 # populate with bindvars
199 $rs->populate([{ name => 'James Bound' }]);
200 $guard->commit;
201
202 $schema->txn_begin;
203 # populate mixed
204 $rs->populate([{ name => 'James Rebound', rank => \ '11' }]);
205 $schema->txn_commit;
206
207 $schema->txn_begin;
208 # and without bindvars
209 $rs->populate([{ name => \ '"James Unbound"' }]);
210 $schema->txn_rollback;
211 }
212
0a03206a 213 # prefetching
214 my $cds_rs = $schema->resultset('CD');
215 my $cds_with_artist = $cds_rs->search({}, { prefetch => 'artist' });
216 my $cds_with_tracks = $cds_rs->search({}, { prefetch => 'tracks' });
217 my $cds_with_stuff = $cds_rs->search({}, { prefetch => [ 'genre', { artist => { cds => { tracks => 'cd_single' } } } ] });
218
219 # implicit pref
220 my $cds_with_impl_artist = $cds_rs->search({}, { columns => [qw/me.title artist.name/], join => 'artist' });
221
222 # get_column
223 my $getcol_rs = $cds_rs->get_column('me.cdid');
224 my $pref_getcol_rs = $cds_with_stuff->get_column('me.cdid');
225
226 # fire the column getters
227 my @throwaway = $pref_getcol_rs->all;
228
a8c2c746 229 my $base_collection = {
a8c2c746 230 resultset => $rs,
307ab4c5 231
0a03206a 232 pref_precursor => $cds_rs,
233
234 pref_rs_single => $cds_with_artist,
235 pref_rs_multi => $cds_with_tracks,
236 pref_rs_nested => $cds_with_stuff,
237
238 pref_rs_implicit => $cds_with_impl_artist,
239
240 pref_row_single => $cds_with_artist->next,
241 pref_row_multi => $cds_with_tracks->next,
242 pref_row_nested => $cds_with_stuff->next,
243
244 # even though this does not leak Storable croaks on it :(((
245 #pref_row_implicit => $cds_with_impl_artist->next,
246
247 get_column_rs_plain => $getcol_rs,
248 get_column_rs_pref => $pref_getcol_rs,
249
37aafa2e 250 # twice so that we make sure only one H::M object spawned
251 chained_resultset => $rs->search_rs ({}, { '+columns' => [ 'foo' ] } ),
252 chained_resultset2 => $rs->search_rs ({}, { '+columns' => [ 'bar' ] } ),
253
a8c2c746 254 row_object => $row_obj,
551e711a 255
187ec69a 256 mc_row_object => $mc_row_obj,
257
a8c2c746 258 result_source => $rs->result_source,
551e711a 259
4376a157 260 result_source_handle => $rs->result_source->handle,
261
a8c2c746 262 pager_explicit_count => $pager_explicit_count,
187ec69a 263
264 leaky_resultset => $rs_bind_circref,
265 leaky_resultset_cond => $cond_rowobj,
266 leaky_resultset_member => $rs_bind_circref->next,
a8c2c746 267 };
574d9b69 268
eb7aa960 269 require Storable;
4376a157 270 %$base_collection = (
271 %$base_collection,
272 refrozen => Storable::dclone( $base_collection ),
273 rerefrozen => Storable::dclone( Storable::dclone( $base_collection ) ),
0a03206a 274 pref_row_implicit => $cds_with_impl_artist->next,
4376a157 275 schema => $schema,
276 storage => $storage,
277 sql_maker => $storage->sql_maker,
278 dbh => $storage->_dbh,
cd122820 279 fresh_pager => $rs->page(5)->pager,
280 pager => $pager,
4376a157 281 );
282
6a43bc0c 283 if ($has_dt) {
284 my $rs = $base_collection->{icdt_rs} = $schema->resultset('Event');
285
286 my $now = DateTime->now;
287 for (1..5) {
288 $base_collection->{"icdt_row_$_"} = $rs->create({
289 created_on => DateTime->new(year => 2011, month => 1, day => $_, time_zone => "-0${_}00" ),
290 starts_at => $now->clone->add(days => $_),
291 });
292 }
293
294 # re-search
295 my @dummy = $rs->all;
296 }
297
eb7aa960 298 # dbh's are created in XS space, so pull them separately
299 for ( grep { defined } map { @{$_->{ChildHandles}} } values %{ {DBI->installed_drivers()} } ) {
300 $base_collection->{"DBI handle $_"} = $_;
301 }
302
187ec69a 303 SKIP: {
304 if ( DBIx::Class::Optional::Dependencies->req_ok_for ('test_leaks') ) {
305 Test::Memory::Cycle::memory_cycle_ok ($base_collection, 'No cycles in the object collection')
306 }
307 else {
308 skip 'Circular ref test needs ' . DBIx::Class::Optional::Dependencies->req_missing_for ('test_leaks'), 1;
309 }
eb7aa960 310 }
574d9b69 311
a8c2c746 312 for (keys %$base_collection) {
313 $weak_registry->{"basic $_"} = { weakref => $base_collection->{$_} };
314 weaken $weak_registry->{"basic $_"}{weakref};
574d9b69 315 }
551e711a 316}
317
50261284 318# check that "phantom-chaining" works - we never lose track of the original $schema
319# and have access to the entire tree without leaking anything
320{
321 my $phantom;
322 for (
323 sub { DBICTest->init_schema },
324 sub { shift->source('Artist') },
325 sub { shift->resultset },
326 sub { shift->result_source },
327 sub { shift->schema },
328 sub { shift->resultset('Artist') },
329 sub { shift->find_or_create({ name => 'detachable' }) },
330 sub { shift->result_source },
331 sub { shift->schema },
332 sub { shift->clone },
187ec69a 333 sub { shift->resultset('CD') },
334 sub { shift->next },
335 sub { shift->artist },
336 sub { shift->search_related('cds') },
50261284 337 sub { shift->next },
187ec69a 338 sub { shift->search_related('artist') },
50261284 339 sub { shift->result_source },
340 sub { shift->resultset },
341 sub { shift->create({ name => 'detached' }) },
342 sub { shift->update({ name => 'reattached' }) },
343 sub { shift->discard_changes },
344 sub { shift->delete },
345 sub { shift->insert },
346 ) {
347 $phantom = $_->($phantom);
348
349 my $slot = (sprintf 'phantom %s=%s(0x%x)', # so we don't trigger stringification
350 ref $phantom,
351 reftype $phantom,
352 refaddr $phantom,
353 );
dee99c24 354
50261284 355 $weak_registry->{$slot} = $phantom;
356 weaken $weak_registry->{$slot};
357 }
358
359 ok( $phantom->in_storage, 'Properly deleted/reinserted' );
360 is( $phantom->name, 'reattached', 'Still correct name' );
361}
a8c2c746 362
307ab4c5 363# Naturally we have some exceptions
364my $cleared;
365for my $slot (keys %$weak_registry) {
6a43bc0c 366 if ($slot =~ /^Test::Builder/) {
c8194884 367 # T::B 2.0 has result objects and other fancyness
368 delete $weak_registry->{$slot};
369 }
9345b14c 370 elsif ($slot =~ /^Method::Generate::(?:Accessor|Constructor)/) {
371 # Moo keeps globals around, this is normal
372 delete $weak_registry->{$slot};
373 }
6a43bc0c 374 elsif ($slot =~ /^SQL::Translator/) {
307ab4c5 375 # SQLT is a piece of shit, leaks all over
376 delete $weak_registry->{$slot};
377 }
6a43bc0c 378 elsif ($slot =~ /^Hash::Merge/) {
37aafa2e 379 # only clear one object of a specific behavior - more would indicate trouble
307ab4c5 380 delete $weak_registry->{$slot}
381 unless $cleared->{hash_merge_singleton}{$weak_registry->{$slot}{weakref}{behavior}}++;
382 }
b4ad8a74 383 elsif (DBIx::Class::_ENV_::INVISIBLE_DOLLAR_AT and $slot =~ /^__TxnScopeGuard__FIXUP__/) {
48e4eac6 384 delete $weak_registry->{$slot}
1f870d5a 385 }
eb7aa960 386 elsif ($slot =~ /^DateTime::TimeZone/) {
387 # DT is going through a refactor it seems - let it leak zones for now
388 delete $weak_registry->{$slot};
389 }
307ab4c5 390}
391
dee99c24 392# every result class has a result source instance as classdata
393# make sure these are all present and distinct before ignoring
394# (distinct means only 1 reference)
395for my $rs_class (
a8c2c746 396 'DBICTest::BaseResult',
dee99c24 397 @compose_ns_classes,
a8c2c746 398 map { DBICTest::Schema->class ($_) } DBICTest::Schema->sources
dee99c24 399) {
400 # need to store the SVref and examine it separately, to push the rsrc instance off the pad
401 my $SV = svref_2object($rs_class->result_source_instance);
402 is( $SV->REFCNT, 1, "Source instance of $rs_class referenced exactly once" );
403
404 # ignore it
405 delete $weak_registry->{$rs_class->result_source_instance};
fa442fd5 406}
a8c2c746 407
dee99c24 408# Schema classes also hold sources, but these are clones, since
409# each source contains the schema (or schema class name in this case)
410# Hence the clone so that the same source can be registered with
411# multiple schemas
412for my $moniker ( keys %{DBICTest::Schema->source_registrations || {}} ) {
413
414 my $SV = svref_2object(DBICTest::Schema->source($moniker));
415 is( $SV->REFCNT, 1, "Source instance registered under DBICTest::Schema as $moniker referenced exactly once" );
416
417 delete $weak_registry->{DBICTest::Schema->source($moniker)};
fa442fd5 418}
a8c2c746 419
187ec69a 420# FIXME !!!
421# There is an actual strong circular reference taking place here, but because
422# half of it is in XS no leaktracer sees it, and Devel::FindRef is equally
423# stumped when trying to trace the origin. The problem is:
424#
425# $cond_object --> result_source --> schema --> storage --> $dbh --> {cached_kids}
426# ^ /
427# \-------- bound value on prepared/cached STH <-----------/
428#
429TODO: {
430 local $TODO = 'Not sure how to fix this yet, an entanglment could be an option';
431 my $r = $weak_registry->{'basic leaky_resultset_cond'}{weakref};
432 ok(! defined $r, 'We no longer leak!')
433 or $r->result_source(undef);
434}
435
48e4eac6 436for my $slot (sort keys %$weak_registry) {
a8c2c746 437
438 ok (! defined $weak_registry->{$slot}{weakref}, "No leaks of $slot") or do {
439 my $diag = '';
440
441 $diag .= Devel::FindRef::track ($weak_registry->{$slot}{weakref}, 20) . "\n"
66917da3 442 if ( $ENV{TEST_VERBOSE} && eval { require Devel::FindRef });
a8c2c746 443
444 if (my $stack = $weak_registry->{$slot}{strace}) {
445 $diag .= " Reference first seen$stack";
446 }
447
448 diag $diag if $diag;
449 };
551e711a 450}
451
66917da3 452# we got so far without a failure - this is a good thing
453# now let's try to rerun this script under a "persistent" environment
454# this is ugly and dirty but we do not yet have a Test::Embedded or
455# similar
456
457my @pperl_cmd = (qw/pperl --prefork=1/, __FILE__);
458my @pperl_term_cmd = @pperl_cmd;
459splice @pperl_term_cmd, 1, 0, '--kill';
460
461# scgi is smart and will auto-reap after -t amount of seconds
462my @scgi_cmd = (qw/speedy -- -t5/, __FILE__);
463
464SKIP: {
465 skip 'Test already in a persistent loop', 1
466 if $ENV{DBICTEST_IN_PERSISTENT_ENV};
467
468 skip 'Persistence test disabled on regular installs', 1
469 if DBICTest::RunMode->is_plain;
470
471 skip 'Main test failed - skipping persistent env tests', 1
472 unless $TB->is_passing;
473
474 # set up -I
475 require Config;
476 local $ENV{PERL5LIB} = join ($Config::Config{path_sep}, @INC);
477
478 local $ENV{DBICTEST_IN_PERSISTENT_ENV} = 1;
479
480 # try with pperl
481 SKIP: {
482 skip 'PPerl persistent environment tests require PPerl', 1
483 unless eval { require PPerl };
484
485 # since PPerl is racy and sucks - just prime the "server"
486 {
487 local $ENV{DBICTEST_PERSISTENT_ENV_BAIL_EARLY} = 1;
488 system(@pperl_cmd);
489 sleep 1;
490
491 # see if it actually runs - if not might as well bail now
492 skip "Something is wrong with pperl ($!)", 1
493 if system(@pperl_cmd);
494 }
495
496 for (1,2,3) {
497 system(@pperl_cmd);
498 ok (!$?, "Run in persistent env (PPerl pass $_): exit $?");
499 }
500
501 ok (! system (@pperl_term_cmd), 'killed pperl instance');
502 }
503
504 # try with speedy-cgi
505 SKIP: {
506 skip 'SPeedyCGI persistent environment tests require CGI::SpeedyCGI', 1
507 unless eval { require CGI::SpeedyCGI };
508
509 {
510 local $ENV{DBICTEST_PERSISTENT_ENV_BAIL_EARLY} = 1;
511 skip "Something is wrong with speedy ($!)", 1
512 if system(@scgi_cmd);
513 sleep 1;
514 }
515
516 for (1,2,3) {
517 system(@scgi_cmd);
518 ok (!$?, "Run in persistent env (SpeedyCGI pass $_): exit $?");
519 }
520 }
521}
522
551e711a 523done_testing;
66917da3 524
525# just an extra precaution in case we blew away from the SKIP - since there are no
526# PID files to go by (man does pperl really suck :(
527END {
528 unless ($ENV{DBICTEST_IN_PERSISTENT_ENV}) {
529 close STDOUT;
530 close STDERR;
531 local $?; # otherwise test will inherit $? of the system()
532 system (@pperl_term_cmd);
533 }
534}