1 # work around brain damage in PPerl (yes, it has to be a global)
3 warn @_ unless $_[0] =~ /\QUse of "goto" to jump into a construct is deprecated/
4 } if ($ENV{DBICTEST_IN_PERSISTENT_ENV});
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)
8 exit 0 if $ENV{DBICTEST_PERSISTENT_ENV_BAIL_EARLY};
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
14 $bless_override = sub {
15 CORE::bless( $_[0], (@_ > 1) ? $_[1] : caller() );
17 *CORE::GLOBAL::bless = sub { goto $bless_override };
25 use DBICTest::RunMode;
26 use DBICTest::Util::LeakTracer qw(populate_weakregistry assert_empty_weakregistry visit_refs);
27 use Scalar::Util qw(weaken blessed reftype);
28 use DBIx::Class::_Util qw(hrefaddr sigwarn_silencer modver_gt_or_eq modver_gt_or_eq_and_lt);
30 plan skip_all => "Your perl version $] appears to leak like a sieve - skipping test"
31 if DBIx::Class::_ENV_::PEEPEENESS;
35 my $TB = Test::More->builder;
36 if ($ENV{DBICTEST_IN_PERSISTENT_ENV}) {
37 # without this explicit close TB warns in END after a ->reset
38 close ($TB->$_) for qw(output failure_output todo_output);
40 # newer TB does not auto-reopen handles
41 if ( modver_gt_or_eq( 'Test::More', '1.200' ) ) {
42 open ($TB->$_, '>&', *STDERR)
43 for qw( failure_output todo_output );
44 open ($TB->output, '>&', *STDOUT);
47 # so done_testing can work on every persistent pass
51 # this is what holds all weakened refs to be checked for leakage
52 my $weak_registry = {};
54 # whether or to invoke IC::DT
57 # Skip the heavy-duty leak tracing when just doing an install
58 unless (DBICTest::RunMode->is_plain) {
60 # redefine the bless override so that we can catch each and every object created
61 no warnings qw/redefine once/;
64 $bless_override = sub {
66 my $obj = CORE::bless(
67 $_[0], (@_ > 1) ? $_[1] : do {
68 my ($class, $fn, $line) = caller();
69 fail ("bless() of $_[0] into $class without explicit class specification at $fn line $line")
70 if $class =~ /^ (?: DBIx\:\:Class | DBICTest ) /x;
75 # unicode is tricky, and now we happen to invoke it early via a
76 # regex in connection()
77 return $obj if (ref $obj) =~ /^utf8/;
79 # Test Builder is now making a new object for every pass/fail (que bloat?)
80 # and as such we can't really store any of its objects (since it will
81 # re-populate the registry while checking it, ewwww!)
82 return $obj if (ref $obj) =~ /^TB2::|^Test::Stream/;
84 # populate immediately to avoid weird side effects
85 return populate_weakregistry ($weak_registry, $obj );
89 for my $func (qw/try catch finally/) {
90 my $orig = \&{"Try::Tiny::$func"};
91 *{"Try::Tiny::$func"} = sub (&;@) {
92 populate_weakregistry( $weak_registry, $_[0] );
97 # Some modules are known to install singletons on-load
98 # Load them and empty the registry
100 # this loads the DT armada
101 $has_dt = DBIx::Class::Optional::Dependencies->req_ok_for('test_dt_sqlite');
109 %$weak_registry = ();
115 my $schema = DBICTest->init_schema;
116 my $rs = $schema->resultset ('Artist');
117 my $storage = $schema->storage;
119 ok ($storage->connected, 'we are connected');
121 my $row_obj = $rs->search({}, { rows => 1})->next; # so that commits/rollbacks work
122 ok ($row_obj, 'row from db');
124 # txn_do to invoke more codepaths
125 my ($mc_row_obj, $pager, $pager_explicit_count) = $schema->txn_do (sub {
127 my $artist = $schema->resultset('Artist')->create ({
128 name => 'foo artist',
136 genre => { name => 'mauve' },
140 my $pg = $rs->search({}, { rows => 1})->page(2)->pager;
142 my $pg_wcount = $rs->page(4)->pager->total_entries (66);
144 return ($artist, $pg, $pg_wcount);
147 # more codepaths - error handling in txn_do
149 eval { $schema->txn_do ( sub {
150 $storage->_dbh->begin_work;
151 fail ('how did we get so far?!');
154 eval { $schema->txn_do ( sub {
155 $schema->txn_do ( sub {
156 die "It's called EXCEPTION";
157 fail ('how did we get so far?!');
159 fail ('how did we get so far?!');
161 like( $@, qr/It\'s called EXCEPTION/, 'Exception correctly propagated in nested txn_do' );
165 my ($rs_bind_circref, $cond_rowobj) = $schema->storage->dbh_do ( sub {
166 my $row = $_[0]->schema->resultset('Artist')->new({});
167 my $rs = $_[0]->schema->resultset('Artist')->search({
168 name => $row, # this is deliberately bogus, see FIXME below!
173 is ($pager->next_page, 3, 'There is one more page available');
175 # based on 66 per 10 pages
176 is ($pager_explicit_count->last_page, 7, 'Correct last page');
178 # do some population (invokes some extra codepaths)
179 # also exercise the guard code and the manual txn control
181 my $guard = $schema->txn_scope_guard;
182 # populate with bindvars
183 $rs->populate([{ name => 'James Bound' }]);
188 $rs->populate([{ name => 'James Rebound', rank => \ '11' }]);
192 # and without bindvars
193 $rs->populate([{ name => \ '"James Unbound"' }]);
194 $schema->txn_rollback;
198 my $cds_rs = $schema->resultset('CD');
199 my $cds_with_artist = $cds_rs->search({}, { prefetch => 'artist' });
200 my $cds_with_tracks = $cds_rs->search({}, { prefetch => 'tracks' });
201 my $cds_with_stuff = $cds_rs->search({}, { prefetch => [ 'genre', { artist => { cds => { tracks => 'cd_single' } } } ] });
204 my $cds_with_impl_artist = $cds_rs->search({}, { columns => [qw/me.title artist.name/], join => 'artist' });
207 my $getcol_rs = $cds_rs->get_column('me.cdid');
208 my $pref_getcol_rs = $cds_with_stuff->get_column('me.cdid');
210 my $base_collection = {
213 pref_precursor => $cds_rs,
215 pref_rs_single => $cds_with_artist,
216 pref_rs_multi => $cds_with_tracks,
217 pref_rs_nested => $cds_with_stuff,
219 pref_rs_implicit => $cds_with_impl_artist,
221 pref_row_single => $cds_with_artist->next,
222 pref_row_multi => $cds_with_tracks->next,
223 pref_row_nested => $cds_with_stuff->next,
225 # even though this does not leak Storable croaks on it :(((
226 #pref_row_implicit => $cds_with_impl_artist->next,
228 get_column_rs_plain => $getcol_rs,
229 get_column_rs_pref => $pref_getcol_rs,
231 # twice so that we make sure only one H::M object spawned
232 chained_resultset => $rs->search_rs ({}, { '+columns' => { foo => 'artistid' } } ),
233 chained_resultset2 => $rs->search_rs ({}, { '+columns' => { bar => 'artistid' } } ),
235 row_object => $row_obj,
237 mc_row_object => $mc_row_obj,
239 result_source => $rs->result_source,
241 result_source_handle => $rs->result_source->handle,
243 pager_explicit_count => $pager_explicit_count,
245 leaky_resultset => $rs_bind_circref,
246 leaky_resultset_cond => $cond_rowobj,
249 # fire all resultsets multiple times, once here, more below
250 # some of these can't find anything (notably leaky_resultset)
255 $_->isa('DBIx::Class::ResultSet')
257 $_->isa('DBIx::Class::ResultSetColumn')
259 } values %$base_collection;
262 my $fire_resultsets = sub {
263 local $ENV{DBIC_COLUMNS_INCLUDE_FILTER_RELS} = 1;
264 local $SIG{__WARN__} = sigwarn_silencer(
265 qr/Unable to deflate 'filter'-type relationship 'artist'.+related object primary key not retrieved/
269 { $_, (blessed($_) ? { $_->get_columns } : ()) }
276 push @{$base_collection->{random_results}}, $fire_resultsets->();
278 # FIXME - something throws a Storable for a spin if we keep
279 # the results in-collection. The same problem is seen above,
280 # swept under the rug back in 0a03206a, damned lazy ribantainer
282 local $base_collection->{random_results};
285 %$base_collection = (
287 refrozen => Storable::dclone( $base_collection ),
288 rerefrozen => Storable::dclone( Storable::dclone( $base_collection ) ),
289 pref_row_implicit => $cds_with_impl_artist->next,
292 sql_maker => $storage->sql_maker,
293 dbh => $storage->_dbh,
294 fresh_pager => $rs->page(5)->pager,
299 # FIXME - ideally this kind of collector ought to be global, but attempts
300 # with an invasive debugger-based tracer did not quite work out... yet
301 # Manually scan the innards of everything we have in the base collection
302 # we assembled so far (skip the DT madness below) *recursively*
304 # Only do this when we do have the bits to look inside CVs properly,
305 # without it we are liable to pick up object defaults that are locked
307 if (DBICTest::Util::LeakTracer::CV_TRACING) {
309 refs => [ $base_collection ],
311 populate_weakregistry ($weak_registry, $_[0]);
312 1; # true means "keep descending"
316 # do a heavy-duty fire-and-compare loop on all resultsets
317 # this is expensive - not running on install
320 ! DBICTest::RunMode->is_plain
322 ! $ENV{DBICTEST_IN_PERSISTENT_ENV}
325 # FIXME - ideally we should be able to just populate an alternative
326 # registry, subtract everything from the main one, and arrive at
327 # an "empty" resulting hash
328 # However due to gross inefficiencies in the ::ResultSet code we
329 # end up recalculating a new set of aliasmaps which could have very
330 # well been cached if it wasn't for... anyhow
331 # What we do here for the time being is similar to the lazy approach
332 # of Devel::LeakTrace - we just make sure we do not end up with more
333 # reftypes than when we started. At least we are not blanket-counting
334 # SVs like D::LT does, but going by reftype... sigh...
336 for (values %$weak_registry) {
337 if ( my $r = reftype($_->{weakref}) ) {
342 # For now we can only reuse the same registry, see FIXME above/below
343 #for my $interim_wr ({}, {}) {
344 for my $interim_wr ( ($weak_registry) x 4 ) {
347 refs => [ $fire_resultsets->(), @rsets ],
349 populate_weakregistry ($interim_wr, $_[0]);
350 1; # true means "keep descending"
354 # FIXME - this is what *should* be here
356 ## anything we have seen so far is cool
357 #delete @{$interim_wr}{keys %$weak_registry};
359 ## moment of truth - the rest ought to be gone
360 #assert_empty_weakregistry($interim_wr);
363 for (values %$weak_registry) {
364 if ( my $r = reftype($_->{weakref}) ) {
370 for (keys %$typecounts) {
371 fail ("Amount of $_ refs changed by $typecounts->{$_} during resultset mass-execution")
372 if ( abs ($typecounts->{$_}) > 1 ); # there is a pad caught somewhere, the +1/-1 can be ignored
377 my $rs = $base_collection->{icdt_rs} = $schema->resultset('Event');
379 my $now = DateTime->now;
381 $base_collection->{"icdt_row_$_"} = $rs->create({
382 created_on => DateTime->new(year => 2011, month => 1, day => $_, time_zone => "-0${_}00" ),
383 starts_at => $now->clone->add(days => $_),
388 my @dummy = $rs->all;
391 # dbh's are created in XS space, so pull them separately
392 for ( grep { defined } map { @{$_->{ChildHandles}} } values %{ {DBI->installed_drivers()} } ) {
393 $base_collection->{"DBI handle $_"} = $_;
396 populate_weakregistry ($weak_registry, $base_collection->{$_}, "basic $_")
397 for keys %$base_collection;
400 # check that "phantom-chaining" works - we never lose track of the original $schema
401 # and have access to the entire tree without leaking anything
405 sub { DBICTest->init_schema( sqlite_use_file => 0 ) },
406 sub { shift->source('Artist') },
407 sub { shift->resultset },
408 sub { shift->result_source },
409 sub { shift->schema },
410 sub { shift->resultset('Artist') },
411 sub { shift->find_or_create({ name => 'detachable' }) },
412 sub { shift->result_source },
413 sub { shift->schema },
414 sub { shift->clone },
415 sub { shift->resultset('CD') },
417 sub { shift->artist },
418 sub { shift->search_related('cds') },
420 sub { shift->search_related('artist') },
421 sub { shift->result_source },
422 sub { shift->resultset },
423 sub { shift->create({ name => 'detached' }) },
424 sub { shift->update({ name => 'reattached' }) },
425 sub { shift->discard_changes },
426 sub { shift->delete },
427 sub { shift->insert },
429 $phantom = populate_weakregistry ( $weak_registry, scalar $_->($phantom) );
432 ok( $phantom->in_storage, 'Properly deleted/reinserted' );
433 is( $phantom->name, 'reattached', 'Still correct name' );
436 # Naturally we have some exceptions
438 for my $addr (keys %$weak_registry) {
439 my $names = join "\n", keys %{$weak_registry->{$addr}{slot_names}};
441 if ($names =~ /^Test::Builder/m) {
442 # T::B 2.0 has result objects and other fancyness
443 delete $weak_registry->{$addr};
445 elsif ($names =~ /^Hash::Merge/m) {
446 # only clear one object of a specific behavior - more would indicate trouble
447 delete $weak_registry->{$addr}
448 unless $cleared->{hash_merge_singleton}{$weak_registry->{$addr}{weakref}{behavior}}++;
450 elsif ($names =~ /^B::Hooks::EndOfScope::PP::_TieHintHashFieldHash/m) {
451 # there is one tied lexical which stays alive until GC time
452 # https://metacpan.org/source/ETHER/B-Hooks-EndOfScope-0.15/lib/B/Hooks/EndOfScope/PP/FieldHash.pm#L24
453 # simply ignore it here, instead of teaching the leaktracer to examine ties
454 # the latter is possible yet terrible: https://github.com/dbsrgits/dbix-class/blob/v0.082820/t/lib/DBICTest/Util/LeakTracer.pm#L113-L117
455 delete $weak_registry->{$addr}
456 unless $cleared->{bheos_pptiehinthashfieldhash}++;
458 elsif ($names =~ /^DateTime::TimeZone::UTC/m) {
459 # DT is going through a refactor it seems - let it leak zones for now
460 delete $weak_registry->{$addr};
463 # # if we can look at closed over pieces - we will register it as a global
464 # !DBICTest::Util::LeakTracer::CV_TRACING
466 $names =~ /^SQL::Translator::Generator::DDL::SQLite/m
468 # SQLT::Producer::SQLite keeps global generators around for quoted
469 # and non-quoted DDL, allow one for each quoting style
470 delete $weak_registry->{$addr}
471 unless $cleared->{sqlt_ddl_sqlite}->{@{$weak_registry->{$addr}{weakref}->quote_chars}}++;
476 # There is an actual strong circular reference taking place here, but because
477 # half of it is in XS, so it is a bit harder to track down (it stumps D::FR)
478 # (our tracker does not yet do it, but it'd be nice)
481 # $cond_object --> result_source --> schema --> storage --> $dbh --> {CachedKids}
483 # \-------- bound value on prepared/cached STH <-----------/
491 { $_->{slot_names}{'basic leaky_resultset_cond'} }
492 values %$weak_registry
494 local $TODO = 'Needs Data::Entangled or somesuch - see RT#82942';
495 ok(! defined $r, 'Self-referential RS conditions no longer leak!')
496 or push @circreffed, $r;
500 is (scalar @circreffed, 1, 'One resultset expected to leak');
502 # this is useless on its own, it is to showcase the circref-diag
503 # and eventually test it when it is operational
504 local $TODO = 'Needs Data::Entangled or somesuch - see RT#82942';
505 while (@circreffed) {
506 weaken (my $r = shift @circreffed);
508 populate_weakregistry( (my $mini_registry = {}), $r );
509 assert_empty_weakregistry( $mini_registry );
511 $r->result_source(undef);
516 assert_empty_weakregistry ($weak_registry);
518 # we got so far without a failure - this is a good thing
519 # now let's try to rerun this script under a "persistent" environment
520 # this is ugly and dirty but we do not yet have a Test::Embedded or
523 my $persistence_tests;
525 skip 'Test already in a persistent loop', 1
526 if $ENV{DBICTEST_IN_PERSISTENT_ENV};
528 skip 'Main test failed - skipping persistent env tests', 1
529 unless $TB->is_passing;
531 skip "Test::Builder\@@{[ Test::Builder->VERSION ]} known to break persistence tests", 1
532 if modver_gt_or_eq_and_lt( 'Test::More', '1.200', '1.301001_099' );
534 local $ENV{DBICTEST_IN_PERSISTENT_ENV} = 1;
536 $persistence_tests = {
538 cmd => [qw/pperl --prefork=1/, __FILE__],
540 'CGI::SpeedyCGI' => {
541 cmd => [qw/speedy -- -t5/, __FILE__],
545 # scgi is smart and will auto-reap after -t amount of seconds
546 # pperl needs an actual killer :(
547 $persistence_tests->{PPerl}{termcmd} = [
548 $persistence_tests->{PPerl}{cmd}[0],
550 @{$persistence_tests->{PPerl}{cmd}}[ 1 .. $#{$persistence_tests->{PPerl}{cmd}} ],
555 $ENV{PERL5LIB} = join ($Config::Config{path_sep}, @INC);
558 if (length $ENV{PATH}) {
559 ( $ENV{PATH} ) = join ( $Config::Config{path_sep},
560 map { length($_) ? File::Spec->rel2abs($_) : () }
561 split /\Q$Config::Config{path_sep}/, $ENV{PATH}
565 for my $type (keys %$persistence_tests) { SKIP: {
566 unless (eval "require $type") {
567 # Don't terminate what we didn't start
568 delete $persistence_tests->{$type}{termcmd};
569 skip "$type module not found", 1;
572 my @cmd = @{$persistence_tests->{$type}{cmd}};
574 # since PPerl is racy and sucks - just prime the "server"
576 local $ENV{DBICTEST_PERSISTENT_ENV_BAIL_EARLY} = 1;
580 # see if the thing actually runs, if not - might as well bail now
581 skip "Something is wrong with $type ($!)", 1
588 note ("Starting run in persistent env ($type pass $_)");
589 IPC::Open2::open2(my $out, undef, @cmd);
591 while (my $ln = <$out>) {
592 next if $ln =~ /^\s*$/;
593 push @out_lines, " $ln";
594 last if $ln =~ /^\d+\.\.\d+$/; # this is persistence, we need to terminate reading on our end
596 print $_ for @out_lines;
599 ok (!$?, "Run in persistent env ($type pass $_): exit $?");
600 ok (scalar @out_lines, "Run in persistent env ($type pass $_): got output");
603 ok (! system (@{$persistence_tests->{$type}{termcmd}}), "killed $type server instance")
604 if $persistence_tests->{$type}{termcmd};
610 # just an extra precaution in case we blew away from the SKIP - since there are no
611 # PID files to go by (man does pperl really suck :(
613 if ($persistence_tests->{PPerl}{termcmd}) {
614 local $?; # otherwise test will inherit $? of the system()
616 open my $null, ">", File::Spec->devnull;
618 IPC::Open3::open3(undef, $null, $null, @{$persistence_tests->{PPerl}{termcmd}}),