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 };
24 my $TB = Test::More->builder;
25 if ($ENV{DBICTEST_IN_PERSISTENT_ENV}) {
26 # without this explicit close older TBs warn in END after a ->reset
27 if ($TB->VERSION < 1.005) {
28 close ($TB->$_) for (qw/output failure_output todo_output/);
31 # if I do not do this, I get happy sigpipes on new TB, no idea why
32 # (the above close-and-forget doesn't work - new TB does *not* reopen
33 # its handles automatically anymore)
35 for (qw/failure_output todo_output/) {
37 open ($TB->$_, '>&', *STDERR);
41 open ($TB->output, '>&', *STDOUT);
44 # so done_testing can work on every persistent pass
49 use DBICTest::RunMode;
50 use DBICTest::Util::LeakTracer qw(populate_weakregistry assert_empty_weakregistry visit_refs);
51 use Scalar::Util qw(weaken blessed reftype);
53 use DBIx::Class::_Util qw(hrefaddr sigwarn_silencer);
55 plan skip_all => "Your perl version $] appears to leak like a sieve - skipping test"
56 if DBIx::Class::_ENV_::PEEPEENESS;
59 # this is what holds all weakened refs to be checked for leakage
60 my $weak_registry = {};
62 # whether or to invoke IC::DT
65 # Skip the heavy-duty leak tracing when just doing an install
66 unless (DBICTest::RunMode->is_plain) {
68 # redefine the bless override so that we can catch each and every object created
69 no warnings qw/redefine once/;
72 $bless_override = sub {
74 my $obj = CORE::bless(
75 $_[0], (@_ > 1) ? $_[1] : do {
76 my ($class, $fn, $line) = caller();
77 fail ("bless() of $_[0] into $class without explicit class specification at $fn line $line")
78 if $class =~ /^ (?: DBIx\:\:Class | DBICTest ) /x;
83 # unicode is tricky, and now we happen to invoke it early via a
84 # regex in connection()
85 return $obj if (ref $obj) =~ /^utf8/;
87 # Test Builder is now making a new object for every pass/fail (que bloat?)
88 # and as such we can't really store any of its objects (since it will
89 # re-populate the registry while checking it, ewwww!)
90 return $obj if (ref $obj) =~ /^TB2::/;
92 # populate immediately to avoid weird side effects
93 return populate_weakregistry ($weak_registry, $obj );
97 for my $func (qw/try catch finally/) {
98 my $orig = \&{"Try::Tiny::$func"};
99 *{"Try::Tiny::$func"} = sub (&;@) {
100 populate_weakregistry( $weak_registry, $_[0] );
105 # Some modules are known to install singletons on-load
106 # Load them and empty the registry
108 # this loads the DT armada
109 $has_dt = DBIx::Class::Optional::Dependencies->req_ok_for('test_dt_sqlite');
117 %$weak_registry = ();
123 my $schema = DBICTest->init_schema;
124 my $rs = $schema->resultset ('Artist');
125 my $storage = $schema->storage;
127 ok ($storage->connected, 'we are connected');
129 my $row_obj = $rs->search({}, { rows => 1})->next; # so that commits/rollbacks work
130 ok ($row_obj, 'row from db');
132 # txn_do to invoke more codepaths
133 my ($mc_row_obj, $pager, $pager_explicit_count) = $schema->txn_do (sub {
135 my $artist = $schema->resultset('Artist')->create ({
136 name => 'foo artist',
144 genre => { name => 'mauve' },
148 my $pg = $rs->search({}, { rows => 1})->page(2)->pager;
150 my $pg_wcount = $rs->page(4)->pager->total_entries (66);
152 return ($artist, $pg, $pg_wcount);
155 # more codepaths - error handling in txn_do
157 eval { $schema->txn_do ( sub {
158 $storage->_dbh->begin_work;
159 fail ('how did we get so far?!');
162 eval { $schema->txn_do ( sub {
163 $schema->txn_do ( sub {
164 die "It's called EXCEPTION";
165 fail ('how did we get so far?!');
167 fail ('how did we get so far?!');
169 like( $@, qr/It\'s called EXCEPTION/, 'Exception correctly propagated in nested txn_do' );
173 my ($rs_bind_circref, $cond_rowobj) = $schema->storage->dbh_do ( sub {
174 my $row = $_[0]->schema->resultset('Artist')->new({});
175 my $rs = $_[0]->schema->resultset('Artist')->search({
176 name => $row, # this is deliberately bogus, see FIXME below!
181 is ($pager->next_page, 3, 'There is one more page available');
183 # based on 66 per 10 pages
184 is ($pager_explicit_count->last_page, 7, 'Correct last page');
186 # do some population (invokes some extra codepaths)
187 # also exercise the guard code and the manual txn control
189 my $guard = $schema->txn_scope_guard;
190 # populate with bindvars
191 $rs->populate([{ name => 'James Bound' }]);
196 $rs->populate([{ name => 'James Rebound', rank => \ '11' }]);
200 # and without bindvars
201 $rs->populate([{ name => \ '"James Unbound"' }]);
202 $schema->txn_rollback;
206 my $cds_rs = $schema->resultset('CD');
207 my $cds_with_artist = $cds_rs->search({}, { prefetch => 'artist' });
208 my $cds_with_tracks = $cds_rs->search({}, { prefetch => 'tracks' });
209 my $cds_with_stuff = $cds_rs->search({}, { prefetch => [ 'genre', { artist => { cds => { tracks => 'cd_single' } } } ] });
212 my $cds_with_impl_artist = $cds_rs->search({}, { columns => [qw/me.title artist.name/], join => 'artist' });
215 my $getcol_rs = $cds_rs->get_column('me.cdid');
216 my $pref_getcol_rs = $cds_with_stuff->get_column('me.cdid');
218 my $base_collection = {
221 pref_precursor => $cds_rs,
223 pref_rs_single => $cds_with_artist,
224 pref_rs_multi => $cds_with_tracks,
225 pref_rs_nested => $cds_with_stuff,
227 pref_rs_implicit => $cds_with_impl_artist,
229 pref_row_single => $cds_with_artist->next,
230 pref_row_multi => $cds_with_tracks->next,
231 pref_row_nested => $cds_with_stuff->next,
233 # even though this does not leak Storable croaks on it :(((
234 #pref_row_implicit => $cds_with_impl_artist->next,
236 get_column_rs_plain => $getcol_rs,
237 get_column_rs_pref => $pref_getcol_rs,
239 # twice so that we make sure only one H::M object spawned
240 chained_resultset => $rs->search_rs ({}, { '+columns' => { foo => 'artistid' } } ),
241 chained_resultset2 => $rs->search_rs ({}, { '+columns' => { bar => 'artistid' } } ),
243 row_object => $row_obj,
245 mc_row_object => $mc_row_obj,
247 result_source => $rs->result_source,
249 result_source_handle => $rs->result_source->handle,
251 pager_explicit_count => $pager_explicit_count,
253 leaky_resultset => $rs_bind_circref,
254 leaky_resultset_cond => $cond_rowobj,
257 # fire all resultsets multiple times, once here, more below
258 # some of these can't find anything (notably leaky_resultset)
263 $_->isa('DBIx::Class::ResultSet')
265 $_->isa('DBIx::Class::ResultSetColumn')
267 } values %$base_collection;
270 my $fire_resultsets = sub {
271 local $ENV{DBIC_COLUMNS_INCLUDE_FILTER_RELS} = 1;
272 local $SIG{__WARN__} = sigwarn_silencer(
273 qr/Unable to deflate 'filter'-type relationship 'artist'.+related object primary key not retrieved/
277 { $_, (blessed($_) ? { $_->get_columns } : ()) }
284 push @{$base_collection->{random_results}}, $fire_resultsets->();
286 # FIXME - something throws a Storable for a spin if we keep
287 # the results in-collection. The same problem is seen above,
288 # swept under the rug back in 0a03206a, damned lazy ribantainer
290 local $base_collection->{random_results};
293 %$base_collection = (
295 refrozen => Storable::dclone( $base_collection ),
296 rerefrozen => Storable::dclone( Storable::dclone( $base_collection ) ),
297 pref_row_implicit => $cds_with_impl_artist->next,
300 sql_maker => $storage->sql_maker,
301 dbh => $storage->_dbh,
302 fresh_pager => $rs->page(5)->pager,
307 # FIXME - ideally this kind of collector ought to be global, but attempts
308 # with an invasive debugger-based tracer did not quite work out... yet
309 # Manually scan the innards of everything we have in the base collection
310 # we assembled so far (skip the DT madness below) *recursively*
312 # Only do this when we do have the bits to look inside CVs properly,
313 # without it we are liable to pick up object defaults that are locked
315 if (DBICTest::Util::LeakTracer::CV_TRACING) {
317 refs => [ $base_collection ],
319 populate_weakregistry ($weak_registry, $_[0]);
320 1; # true means "keep descending"
324 # do a heavy-duty fire-and-compare loop on all resultsets
325 # this is expensive - not running on install
328 ! DBICTest::RunMode->is_plain
330 ! $ENV{DBICTEST_IN_PERSISTENT_ENV}
332 # FIXME - investigate wtf is going on with 5.18
333 ! ( $] > 5.017 and $ENV{DBIC_TRACE_PROFILE} )
336 # FIXME - ideally we should be able to just populate an alternative
337 # registry, subtract everything from the main one, and arrive at
338 # an "empty" resulting hash
339 # However due to gross inefficiencies in the ::ResultSet code we
340 # end up recalculating a new set of aliasmaps which could have very
341 # well been cached if it wasn't for... anyhow
342 # What we do here for the time being is similar to the lazy approach
343 # of Devel::LeakTrace - we just make sure we do not end up with more
344 # reftypes than when we started. At least we are not blanket-counting
345 # SVs like D::LT does, but going by reftype... sigh...
347 for (values %$weak_registry) {
348 if ( my $r = reftype($_->{weakref}) ) {
353 # For now we can only reuse the same registry, see FIXME above/below
354 #for my $interim_wr ({}, {}) {
355 for my $interim_wr ( ($weak_registry) x 4 ) {
358 refs => [ $fire_resultsets->(), @rsets ],
360 populate_weakregistry ($interim_wr, $_[0]);
361 1; # true means "keep descending"
365 # FIXME - this is what *should* be here
367 ## anything we have seen so far is cool
368 #delete @{$interim_wr}{keys %$weak_registry};
370 ## moment of truth - the rest ought to be gone
371 #assert_empty_weakregistry($interim_wr);
374 for (values %$weak_registry) {
375 if ( my $r = reftype($_->{weakref}) ) {
381 for (keys %$typecounts) {
382 fail ("Amount of $_ refs changed by $typecounts->{$_} during resultset mass-execution")
383 if ( abs ($typecounts->{$_}) > 1 ); # there is a pad caught somewhere, the +1/-1 can be ignored
388 my $rs = $base_collection->{icdt_rs} = $schema->resultset('Event');
390 my $now = DateTime->now;
392 $base_collection->{"icdt_row_$_"} = $rs->create({
393 created_on => DateTime->new(year => 2011, month => 1, day => $_, time_zone => "-0${_}00" ),
394 starts_at => $now->clone->add(days => $_),
399 my @dummy = $rs->all;
402 # dbh's are created in XS space, so pull them separately
403 for ( grep { defined } map { @{$_->{ChildHandles}} } values %{ {DBI->installed_drivers()} } ) {
404 $base_collection->{"DBI handle $_"} = $_;
407 populate_weakregistry ($weak_registry, $base_collection->{$_}, "basic $_")
408 for keys %$base_collection;
411 # check that "phantom-chaining" works - we never lose track of the original $schema
412 # and have access to the entire tree without leaking anything
416 sub { DBICTest->init_schema( sqlite_use_file => 0 ) },
417 sub { shift->source('Artist') },
418 sub { shift->resultset },
419 sub { shift->result_source },
420 sub { shift->schema },
421 sub { shift->resultset('Artist') },
422 sub { shift->find_or_create({ name => 'detachable' }) },
423 sub { shift->result_source },
424 sub { shift->schema },
425 sub { shift->clone },
426 sub { shift->resultset('CD') },
428 sub { shift->artist },
429 sub { shift->search_related('cds') },
431 sub { shift->search_related('artist') },
432 sub { shift->result_source },
433 sub { shift->resultset },
434 sub { shift->create({ name => 'detached' }) },
435 sub { shift->update({ name => 'reattached' }) },
436 sub { shift->discard_changes },
437 sub { shift->delete },
438 sub { shift->insert },
440 $phantom = populate_weakregistry ( $weak_registry, scalar $_->($phantom) );
443 ok( $phantom->in_storage, 'Properly deleted/reinserted' );
444 is( $phantom->name, 'reattached', 'Still correct name' );
447 # Naturally we have some exceptions
449 for my $addr (keys %$weak_registry) {
450 my $names = join "\n", keys %{$weak_registry->{$addr}{slot_names}};
452 if ($names =~ /^Test::Builder/m) {
453 # T::B 2.0 has result objects and other fancyness
454 delete $weak_registry->{$addr};
456 elsif ($names =~ /^Hash::Merge/m) {
457 # only clear one object of a specific behavior - more would indicate trouble
458 delete $weak_registry->{$addr}
459 unless $cleared->{hash_merge_singleton}{$weak_registry->{$addr}{weakref}{behavior}}++;
462 # # if we can look at closed over pieces - we will register it as a global
463 # !DBICTest::Util::LeakTracer::CV_TRACING
465 $names =~ /^SQL::Translator::Generator::DDL::SQLite/m
467 # SQLT::Producer::SQLite keeps global generators around for quoted
468 # and non-quoted DDL, allow one for each quoting style
469 delete $weak_registry->{$addr}
470 unless $cleared->{sqlt_ddl_sqlite}->{@{$weak_registry->{$addr}{weakref}->quote_chars}}++;
475 # There is an actual strong circular reference taking place here, but because
476 # half of it is in XS, so it is a bit harder to track down (it stumps D::FR)
477 # (our tracker does not yet do it, but it'd be nice)
480 # $cond_object --> result_source --> schema --> storage --> $dbh --> {CachedKids}
482 # \-------- bound value on prepared/cached STH <-----------/
490 { $_->{slot_names}{'basic leaky_resultset_cond'} }
491 values %$weak_registry
493 local $TODO = 'Needs Data::Entangled or somesuch - see RT#82942';
494 ok(! defined $r, 'Self-referential RS conditions no longer leak!')
495 or push @circreffed, $r;
499 is (scalar @circreffed, 1, 'One resultset expected to leak');
501 # this is useless on its own, it is to showcase the circref-diag
502 # and eventually test it when it is operational
503 local $TODO = 'Needs Data::Entangled or somesuch - see RT#82942';
504 while (@circreffed) {
505 weaken (my $r = shift @circreffed);
507 populate_weakregistry( (my $mini_registry = {}), $r );
508 assert_empty_weakregistry( $mini_registry );
510 $r->result_source(undef);
515 assert_empty_weakregistry ($weak_registry);
517 # we got so far without a failure - this is a good thing
518 # now let's try to rerun this script under a "persistent" environment
519 # this is ugly and dirty but we do not yet have a Test::Embedded or
524 $ENV{PERL5LIB} = join ($Config::Config{path_sep}, @INC);
525 ($ENV{PATH}) = $ENV{PATH} =~ /(.+)/;
528 my $persistence_tests = {
530 cmd => [qw/pperl --prefork=1/, __FILE__],
532 'CGI::SpeedyCGI' => {
533 cmd => [qw/speedy -- -t5/, __FILE__],
537 # scgi is smart and will auto-reap after -t amount of seconds
538 # pperl needs an actual killer :(
539 $persistence_tests->{PPerl}{termcmd} = [
540 $persistence_tests->{PPerl}{cmd}[0],
542 @{$persistence_tests->{PPerl}{cmd}}[ 1 .. $#{$persistence_tests->{PPerl}{cmd}} ],
546 skip 'Test already in a persistent loop', 1
547 if $ENV{DBICTEST_IN_PERSISTENT_ENV};
549 skip 'Main test failed - skipping persistent env tests', 1
550 unless $TB->is_passing;
552 local $ENV{DBICTEST_IN_PERSISTENT_ENV} = 1;
556 for my $type (keys %$persistence_tests) { SKIP: {
557 unless (eval "require $type") {
558 # Don't terminate what we didn't start
559 delete $persistence_tests->{$type}{termcmd};
560 skip "$type module not found", 1;
563 my @cmd = @{$persistence_tests->{$type}{cmd}};
565 # since PPerl is racy and sucks - just prime the "server"
567 local $ENV{DBICTEST_PERSISTENT_ENV_BAIL_EARLY} = 1;
571 # see if the thing actually runs, if not - might as well bail now
572 skip "Something is wrong with $type ($!)", 1
577 note ("Starting run in persistent env ($type pass $_)");
578 IPC::Open2::open2(my $out, undef, @cmd);
580 while (my $ln = <$out>) {
581 next if $ln =~ /^\s*$/;
582 push @out_lines, " $ln";
583 last if $ln =~ /^\d+\.\.\d+$/; # this is persistence, we need to terminate reading on our end
585 print $_ for @out_lines;
588 ok (!$?, "Run in persistent env ($type pass $_): exit $?");
589 ok (scalar @out_lines, "Run in persistent env ($type pass $_): got output");
592 ok (! system (@{$persistence_tests->{$type}{termcmd}}), "killed $type server instance")
593 if $persistence_tests->{$type}{termcmd};
599 # just an extra precaution in case we blew away from the SKIP - since there are no
600 # PID files to go by (man does pperl really suck :(
602 unless ($ENV{DBICTEST_IN_PERSISTENT_ENV}) {
603 close $_ for (*STDIN, *STDOUT, *STDERR);
604 local $?; # otherwise test will inherit $? of the system()
605 system (@{$persistence_tests->{PPerl}{termcmd}})
606 if $persistence_tests->{PPerl}{termcmd};