Retire the ASSERT_NO_INTERNAL_WANTARRAY macro
[dbsrgits/DBIx-Class.git] / lib / DBIx / Class / _Util.pm
CommitLineData
b1dbf716 1package # hide from PAUSE
2 DBIx::Class::_Util;
3
b78ed1e4 4# load es early as we can, usually a noop
5use DBIx::Class::StartupCheck;
399b9455 6
b1dbf716 7use warnings;
8use strict;
9
953f8eb0 10# For the love of everything that is crab-like: DO NOT reach into this
11# The entire thing is really fragile and should not be screwed with
12# unless absolutely and unavoidably necessary
13our $__describe_class_query_cache;
296248c3 14
37873f78 15BEGIN {
16 package # hide from pause
17 DBIx::Class::_ENV_;
18
19 use Config;
20
21 use constant {
3605497b 22 PERL_VERSION => "$]",
23 OS_NAME => "$^O",
24 };
25
26 use constant {
37873f78 27
28 # but of course
3605497b 29 BROKEN_FORK => (OS_NAME eq 'MSWin32') ? 1 : 0,
37873f78 30
3605497b 31 BROKEN_GOTO => ( PERL_VERSION < 5.008003 ) ? 1 : 0,
8d73fcd4 32
7bba735d 33 # perl -MScalar::Util=weaken -e 'weaken( $hash{key} = \"value" )'
3605497b 34 BROKEN_WEAK_SCALARREF_VALUES => ( PERL_VERSION < 5.008003 ) ? 1 : 0,
7bba735d 35
37873f78 36 HAS_ITHREADS => $Config{useithreads} ? 1 : 0,
37
5f0174dc 38 TAINT_MODE => 0 + ${^TAINT}, # tri-state: 0, 1, -1
39
3605497b 40 UNSTABLE_DOLLARAT => ( PERL_VERSION < 5.013002 ) ? 1 : 0,
bbf6a9a5 41
db83437e 42 ( map
43 #
44 # the "DBIC_" prefix below is crucial - this is what makes CI pick up
45 # all envvars without further adjusting its scripts
46 # DO NOT CHANGE to the more logical { $_ => !!( $ENV{"DBIC_$_"} ) }
47 #
48 { substr($_, 5) => !!( $ENV{$_} ) }
49 qw(
50 DBIC_SHUFFLE_UNORDERED_RESULTSETS
db83437e 51 DBIC_ASSERT_NO_INTERNAL_INDIRECT_CALLS
534aff61 52 DBIC_ASSERT_NO_ERRONEOUS_METAINSTANCE_USE
12e7015a 53 DBIC_ASSERT_NO_FAILING_SANITY_CHECKS
a3ae79ed 54 DBIC_ASSERT_NO_INCONSISTENT_RELATIONSHIP_RESOLUTION
db83437e 55 DBIC_STRESSTEST_UTF8_UPGRADE_GENERATED_COLLAPSER_SOURCE
56 DBIC_STRESSTEST_COLUMN_INFO_UNAWARE_STORAGE
57 )
58 ),
f45dc928 59
37873f78 60 IV_SIZE => $Config{ivsize},
61 };
62
3605497b 63 if ( PERL_VERSION < 5.009_005) {
37873f78 64 require MRO::Compat;
65 constant->import( OLD_MRO => 1 );
296248c3 66
67 #
68 # Yes, I know this is a rather PHP-ish name, but please first read
69 # https://metacpan.org/source/BOBTFISH/MRO-Compat-0.12/lib/MRO/Compat.pm#L363-368
70 #
71 # Even if we are using Class::C3::XS it still won't work, as doing
72 # defined( *{ "SubClass::"->{$_} }{CODE} )
73 # will set pkg_gen to the same value for SubClass and *ALL PARENTS*
74 #
75 *DBIx::Class::_Util::get_real_pkg_gen = sub ($) {
76 require Digest::MD5;
77 require Math::BigInt;
78
953f8eb0 79 my $cur_class;
80 no strict 'refs';
81
296248c3 82 # the non-assign-unless-there-is-a-hash is deliberate
953f8eb0 83 ( $__describe_class_query_cache->{'!internal!'} || {} )->{$_[0]}{gen} ||= (
296248c3 84 Math::BigInt->new( '0x' . ( Digest::MD5::md5_hex( join "\0", map {
85
953f8eb0 86 ( $__describe_class_query_cache->{'!internal!'} || {} )->{$_}{methlist} ||= (
87
88 $cur_class = $_
296248c3 89
953f8eb0 90 and
1c179556 91
92 # RV to be hashed up and turned into a number
93 join "\0", (
953f8eb0 94 $cur_class,
296248c3 95 map
1c179556 96 {(
97 # stringification should be sufficient, ignore names/refaddr entirely
98 $_,
92705f7f 99 do {
100 my @attrs;
101 local $@;
102 local $SIG{__DIE__} if $SIG{__DIE__};
103 # attributes::get may throw on blessed-false crefs :/
104 eval { @attrs = attributes::get( $_ ); 1 }
105 or warn "Unable to determine attributes of coderef $_ due to the following error: $@";
106 @attrs;
107 },
1c179556 108 )}
296248c3 109 map
1c179556 110 {(
111 # skip dummy C::C3 helper crefs
953f8eb0 112 ! ( ( $Class::C3::MRO{$cur_class} || {} )->{methods}{$_} )
1c179556 113 and
296248c3 114 (
953f8eb0 115 ref(\ "${cur_class}::"->{$_} ) ne 'GLOB'
296248c3 116 or
953f8eb0 117 defined( *{ "${cur_class}::"->{$_} }{CODE} )
296248c3 118 )
1c179556 119 )
953f8eb0 120 ? ( \&{"${cur_class}::$_"} )
296248c3 121 : ()
122 }
953f8eb0 123 keys %{ "${cur_class}::" }
124 )
125 )
d01688cc 126 } (
127
128 @{
953f8eb0 129 ( $__describe_class_query_cache->{'!internal!'} || {} )->{$_[0]}{linear_isa}
d01688cc 130 ||=
131 mro::get_linear_isa($_[0])
132 },
133
134 ((
953f8eb0 135 ( $__describe_class_query_cache->{'!internal!'} || {} )->{$_[0]}{is_universal}
d01688cc 136 ||=
137 mro::is_universal($_[0])
138 ) ? () : @{
953f8eb0 139 ( $__describe_class_query_cache->{'!internal!'} || {} )->{UNIVERSAL}{linear_isa}
d01688cc 140 ||=
141 mro::get_linear_isa("UNIVERSAL")
142 } ),
143
144 ) ) ) )
296248c3 145 );
146 };
37873f78 147 }
148 else {
149 require mro;
150 constant->import( OLD_MRO => 0 );
296248c3 151 *DBIx::Class::_Util::get_real_pkg_gen = \&mro::get_pkg_gen;
37873f78 152 }
4b1b44c1 153
154 # Both of these are no longer used for anything. However bring
155 # them back after they were purged in 08a8d8f1, as there appear
156 # to be outfits with *COPY PASTED* pieces of lib/DBIx/Class/Storage/*
157 # in their production codebases. There is no point in breaking these
158 # if whatever they used actually continues to work
4b1b44c1 159 my $sigh = sub {
c40b5744 160 DBIx::Class::_Util::emit_loud_diag(
161 skip_frames => 1,
162 msg => "The @{[ (caller(1))[3] ]} constant is no more - adjust your code"
163 );
4b1b44c1 164
165 0;
166 };
167 sub DBICTEST () { &$sigh }
168 sub PEEPEENESS () { &$sigh }
37873f78 169}
170
3605497b 171use constant SPURIOUS_VERSION_CHECK_WARNINGS => ( DBIx::Class::_ENV_::PERL_VERSION < 5.010 ? 1 : 0);
172
841efcb3 173# FIXME - this is not supposed to be here
174# Carp::Skip to the rescue soon
175use DBIx::Class::Carp '^DBIx::Class|^DBICTest';
176
b78ed1e4 177# Ensure it is always there, in case we need to do a $schema-less throw()
178use DBIx::Class::Exception ();
179
d7d45bdc 180use B ();
841efcb3 181use Carp 'croak';
d7d45bdc 182use Storable 'nfreeze';
3d56e026 183use Scalar::Util qw(weaken blessed reftype refaddr);
514b84f6 184use Sub::Name ();
296248c3 185use attributes ();
7f9a3f70 186
6de81918 187# Usually versions are not specified anywhere aside the Makefile.PL
188# (writing them out in-code is extremely obnoxious)
189# However without a recent enough Moo the quote_sub override fails
190# in very puzzling and hard to detect ways: so add a version check
191# just this once
192use Sub::Quote qw(qsub);
193BEGIN { Sub::Quote->VERSION('2.002002') }
194
1c30a2e4 195# Already correctly prototyped: perlbrew exec perl -MStorable -e 'warn prototype \&Storable::dclone'
196BEGIN { *deep_clone = \&Storable::dclone }
197
b1dbf716 198use base 'Exporter';
3705e3b2 199our @EXPORT_OK = qw(
a580a227 200 sigwarn_silencer modver_gt_or_eq modver_gt_or_eq_and_lt fail_on_internal_call
86a432d4 201 refdesc refcount hrefaddr set_subname get_subname describe_class_methods
c40b5744 202 scope_guard detected_reinvoked_destructor emit_loud_diag
293cb2f1 203 true false
e2741c7f 204 is_exception dbic_internal_try dbic_internal_catch visit_namespaces
86be9bcb 205 quote_sub qsub perlstring serialize deep_clone dump_value uniq bag_eq
439a7283 206 parent_dir mkdir_p
09d2e66a 207 UNRESOLVABLE_CONDITION DUMMY_ALIASPAIR
3705e3b2 208);
052a832c 209
facd0e8e 210use constant UNRESOLVABLE_CONDITION => \ '1 = 0';
211
09d2e66a 212use constant DUMMY_ALIASPAIR => (
213 foreign_alias => "!!!\xFF()!!!_DUMMY_FOREIGN_ALIAS_SHOULD_NEVER_BE_SEEN_IN_USE_!!!()\xFF!!!",
214 self_alias => "!!!\xFE()!!!_DUMMY_SELF_ALIAS_SHOULD_NEVER_BE_SEEN_IN_USE_!!!()\xFE!!!",
215);
216
e85eb407 217# Override forcing no_defer, and adding naming consistency checks
dc715747 218our %refs_closed_over_by_quote_sub_installed_crefs;
e85eb407 219sub quote_sub {
9642350a 220 Carp::confess( "Anonymous quoting not supported by the DBIC quote_sub override - supply a sub name" ) if
e85eb407 221 @_ < 2
222 or
223 ! defined $_[1]
224 or
225 length ref $_[1]
226 ;
227
9642350a 228 Carp::confess( "The DBIC quote_sub override expects sub name '$_[0]' to be fully qualified" )
229 unless (my $stash) = $_[0] =~ /^(.+)::/;
230
231 Carp::confess(
232 "The DBIC sub_quote override does not support 'no_install'"
233 ) if (
234 $_[3]
235 and
236 $_[3]->{no_install}
237 );
e85eb407 238
9642350a 239 Carp::confess(
240 'The DBIC quote_sub override expects the namespace-part of sub name '
241 . "'$_[0]' to match the supplied package argument '$_[3]->{package}'"
242 ) if (
e85eb407 243 $_[3]
244 and
245 defined $_[3]->{package}
246 and
9642350a 247 $stash ne $_[3]->{package}
248 );
e85eb407 249
250 my @caller = caller(0);
251 my $sq_opts = {
252 package => $caller[0],
253 hints => $caller[8],
254 warning_bits => $caller[9],
255 hintshash => $caller[10],
256 %{ $_[3] || {} },
257
258 # explicitly forced for everything
259 no_defer => 1,
260 };
261
dc715747 262 weaken (
263 # just use a growing counter, no need to perform neither compaction
264 # nor any special ithread-level handling
265 $refs_closed_over_by_quote_sub_installed_crefs
266 { scalar keys %refs_closed_over_by_quote_sub_installed_crefs }
267 = $_
268 ) for grep {
269 length ref $_
270 and
271 (
272 ! DBIx::Class::_ENV_::BROKEN_WEAK_SCALARREF_VALUES
273 or
274 ref $_ ne 'SCALAR'
275 )
276 } values %{ $_[2] || {} };
277
9642350a 278 Sub::Quote::quote_sub( $_[0], $_[1], $_[2]||{}, $sq_opts );
e85eb407 279}
280
bf302897 281sub sigwarn_silencer ($) {
052a832c 282 my $pattern = shift;
283
284 croak "Expecting a regexp" if ref $pattern ne 'Regexp';
285
286 my $orig_sig_warn = $SIG{__WARN__} || sub { CORE::warn(@_) };
287
288 return sub { &$orig_sig_warn unless $_[0] =~ $pattern };
289}
b1dbf716 290
01b25f12 291sub perlstring ($) { q{"}. quotemeta( shift ). q{"} };
292
3d56e026 293sub hrefaddr ($) { sprintf '0x%x', &refaddr||0 }
8433421f 294
295sub refdesc ($) {
296 croak "Expecting a reference" if ! length ref $_[0];
297
298 # be careful not to trigger stringification,
299 # reuse @_ as a scratch-pad
300 sprintf '%s%s(0x%x)',
301 ( defined( $_[1] = blessed $_[0]) ? "$_[1]=" : '' ),
302 reftype $_[0],
3d56e026 303 refaddr($_[0]),
8433421f 304 ;
305}
bf302897 306
307sub refcount ($) {
dac7972a 308 croak "Expecting a reference" if ! length ref $_[0];
309
dac7972a 310 # No tempvars - must operate on $_[0], otherwise the pad
311 # will count as an extra ref
312 B::svref_2object($_[0])->REFCNT;
313}
314
10be570e 315sub visit_namespaces {
316 my $args = { (ref $_[0]) ? %{$_[0]} : @_ };
317
318 my $visited_count = 1;
319
320 # A package and a namespace are subtly different things
321 $args->{package} ||= 'main';
322 $args->{package} = 'main' if $args->{package} =~ /^ :: (?: main )? $/x;
323 $args->{package} =~ s/^:://;
324
325 if ( $args->{action}->($args->{package}) ) {
326 my $ns =
327 ( ($args->{package} eq 'main') ? '' : $args->{package} )
328 .
329 '::'
330 ;
331
332 $visited_count += visit_namespaces( %$args, package => $_ ) for
333 grep
334 # this happens sometimes on %:: traversal
335 { $_ ne '::main' }
336 map
337 { $_ =~ /^(.+?)::$/ ? "$ns$1" : () }
338 do { no strict 'refs'; keys %$ns }
339 ;
340 }
341
342 $visited_count;
343}
344
86a432d4 345# FIXME In another life switch these to a polyfill like the ones in namespace::clean
346sub get_subname ($) {
347 my $gv = B::svref_2object( $_[0] )->GV;
348 wantarray
349 ? ( $gv->STASH->NAME, $gv->NAME )
350 : ( join '::', $gv->STASH->NAME, $gv->NAME )
351 ;
352}
514b84f6 353sub set_subname ($$) {
354
355 # fully qualify name
356 splice @_, 0, 1, caller(0) . "::$_[0]"
357 if $_[0] !~ /::|'/;
358
359 &Sub::Name::subname;
360}
361
b34d9331 362sub serialize ($) {
d6c13bfd 363 # stable hash order
b34d9331 364 local $Storable::canonical = 1;
d6c13bfd 365
366 # explicitly false - there is nothing sensible that can come out of
367 # an attempt at CODE serialization
368 local $Storable::Deparse;
369
370 # take no chances
371 local $Storable::forgive_me;
372
373 # FIXME
374 # A number of codepaths *expect* this to be Storable.pm-based so that
375 # the STORABLE_freeze hooks in the metadata subtree get executed properly
d7d45bdc 376 nfreeze($_[0]);
b34d9331 377}
378
10be570e 379sub uniq {
380 my( %seen, $seen_undef, $numeric_preserving_copy );
381 grep { not (
382 defined $_
383 ? $seen{ $numeric_preserving_copy = $_ }++
384 : $seen_undef++
385 ) } @_;
386}
387
86be9bcb 388sub bag_eq ($$) {
389 croak "bag_eq() requiress two arrayrefs as arguments" if (
390 ref($_[0]) ne 'ARRAY'
391 or
392 ref($_[1]) ne 'ARRAY'
393 );
394
395 return '' unless @{$_[0]} == @{$_[1]};
396
397 my( %seen, $numeric_preserving_copy );
398
399 ( defined $_
400 ? $seen{'value' . ( $numeric_preserving_copy = $_ )}++
401 : $seen{'undef'}++
402 ) for @{$_[0]};
403
404 ( defined $_
405 ? $seen{'value' . ( $numeric_preserving_copy = $_ )}--
406 : $seen{'undef'}--
407 ) for @{$_[1]};
408
409 return (
410 (grep { $_ } values %seen)
411 ? ''
412 : 1
413 );
414}
415
2d5ac3cf 416my $dd_obj;
8fc4291e 417sub dump_value ($) {
418 local $Data::Dumper::Indent = 1
419 unless defined $Data::Dumper::Indent;
420
2d5ac3cf 421 my $dump_str = (
8fc4291e 422 $dd_obj
423 ||=
424 do {
425 require Data::Dumper;
426 my $d = Data::Dumper->new([])
427 ->Purity(0)
428 ->Pad('')
429 ->Useqq(1)
430 ->Terse(1)
431 ->Freezer('')
432 ->Quotekeys(0)
433 ->Bless('bless')
434 ->Pair(' => ')
435 ->Sortkeys(1)
436 ->Deparse(1)
437 ;
438
d6c13bfd 439 # FIXME - this is kinda ridiculous - there ought to be a
440 # Data::Dumper->new_with_defaults or somesuch...
441 #
442 if( modver_gt_or_eq ( 'Data::Dumper', '2.136' ) ) {
443 $d->Sparseseen(1);
444
445 if( modver_gt_or_eq ( 'Data::Dumper', '2.153' ) ) {
446 $d->Maxrecurse(1000);
447
448 if( modver_gt_or_eq ( 'Data::Dumper', '2.160' ) ) {
449 $d->Trailingcomma(1);
450 }
451 }
452 }
8fc4291e 453
454 $d;
455 }
456 )->Values([$_[0]])->Dump;
457
458 $dd_obj->Reset->Values([]);
459
460 $dump_str;
461}
462
c40b5744 463my $seen_loud_screams;
464sub emit_loud_diag {
465 my $args = { ref $_[0] eq 'HASH' ? %{$_[0]} : @_ };
466
467 unless ( defined $args->{msg} and length $args->{msg} ) {
468 emit_loud_diag(
469 msg => "No 'msg' value supplied to emit_loud_diag()"
470 );
471 exit 70;
472 }
473
73f54e27 474 my $msg = "\n" . join( ': ',
475 ( $0 eq '-e' ? () : $0 ),
476 $args->{msg}
477 );
c40b5744 478
479 # when we die - we usually want to keep doing it
480 $args->{emit_dups} = !!$args->{confess}
481 unless exists $args->{emit_dups};
482
483 local $Carp::CarpLevel =
484 ( $args->{skip_frames} || 0 )
485 +
486 $Carp::CarpLevel
487 +
488 # hide our own frame
489 1
490 ;
491
492 my $longmess = Carp::longmess();
493
494 # different object references will thwart deduplication without this
495 ( my $key = "${msg}\n${longmess}" ) =~ s/\b0x[0-9a-f]+\b/0x.../gi;
496
497 return $seen_loud_screams->{$key} if
498 $seen_loud_screams->{$key}++
499 and
500 ! $args->{emit_dups}
501 ;
502
503 $msg .= $longmess
504 unless $msg =~ /\n\z/;
505
506 print STDERR "$msg\n"
507 or
508 print STDOUT "\n!!!STDERR ISN'T WRITABLE!!!:$msg\n";
509
510 return $seen_loud_screams->{$key}
511 unless $args->{confess};
512
513 # increment *again*, because... Carp.
514 $Carp::CarpLevel++;
515
516 # not $msg - Carp will reapply the longmess on its own
517 Carp::confess($args->{msg});
518}
519
520
293cb2f1 521###
522### This is *NOT* boolean.pm - deliberately not using a singleton
523###
524{
525 package # hide from pause
526 DBIx::Class::_Util::_Bool;
527 use overload
528 bool => sub { ${$_[0]} },
529 fallback => 1,
530 ;
531}
532sub true () { my $x = 1; bless \$x, "DBIx::Class::_Util::_Bool" }
533sub false () { my $x = 0; bless \$x, "DBIx::Class::_Util::_Bool" }
534
bbf6a9a5 535sub scope_guard (&) {
536 croak 'Calling scope_guard() in void context makes no sense'
537 if ! defined wantarray;
538
539 # no direct blessing of coderefs - DESTROY is buggy on those
540 bless [ $_[0] ], 'DBIx::Class::_Util::ScopeGuard';
541}
542{
543 package #
544 DBIx::Class::_Util::ScopeGuard;
545
546 sub DESTROY {
547 &DBIx::Class::_Util::detected_reinvoked_destructor;
548
549 local $@ if DBIx::Class::_ENV_::UNSTABLE_DOLLARAT;
550
551 eval {
552 $_[0]->[0]->();
553 1;
118b2c36 554 }
555 or
c40b5744 556 DBIx::Class::_Util::emit_loud_diag(
557 emit_dups => 1,
558 msg => "Execution of scope guard $_[0] resulted in the non-trappable exception:\n\n$@\n "
118b2c36 559 );
bbf6a9a5 560 }
561}
562
563
841efcb3 564sub is_exception ($) {
565 my $e = $_[0];
566
35cf7d1a 567 # FIXME
a0414138 568 # this is not strictly correct - an eval setting $@ to undef
569 # is *not* the same as an eval setting $@ to ''
570 # but for the sake of simplicity assume the following for
571 # the time being
572 return 0 unless defined $e;
573
841efcb3 574 my ($not_blank, $suberror);
575 {
5c33c8be 576 local $SIG{__DIE__} if $SIG{__DIE__};
841efcb3 577 local $@;
578 eval {
d52c4a75 579 # The ne() here is deliberate - a plain length($e), or worse "$e" ne
580 # will entirely obviate the need for the encolsing eval{}, as the
581 # condition we guard against is a missing fallback overload
582 $not_blank = ( $e ne '' );
841efcb3 583 1;
584 } or $suberror = $@;
585 }
586
587 if (defined $suberror) {
588 if (length (my $class = blessed($e) )) {
589 carp_unique( sprintf(
9bea2000 590 'External exception class %s implements partial (broken) overloading '
591 . 'preventing its instances from being used in simple ($x eq $y) '
841efcb3 592 . 'comparisons. Given Perl\'s "globally cooperative" exception '
593 . 'handling this type of brokenness is extremely dangerous on '
594 . 'exception objects, as it may (and often does) result in silent '
595 . '"exception substitution". DBIx::Class tries to work around this '
596 . 'as much as possible, but other parts of your software stack may '
597 . 'not be even aware of this. Please submit a bugreport against the '
598 . 'distribution containing %s and in the meantime apply a fix similar '
599 . 'to the one shown at %s, in order to ensure your exception handling '
600 . 'is saner application-wide. What follows is the actual error text '
601 . "as generated by Perl itself:\n\n%s\n ",
9bea2000 602 $class,
841efcb3 603 $class,
604 'http://v.gd/DBIC_overload_tempfix/',
605 $suberror,
606 ));
607
608 # workaround, keeps spice flowing
d52c4a75 609 $not_blank = !!( length $e );
841efcb3 610 }
611 else {
612 # not blessed yet failed the 'ne'... this makes 0 sense...
613 # just throw further
614 die $suberror
615 }
616 }
84e4e006 617 elsif (
618 # a ref evaluating to '' is definitively a "null object"
619 ( not $not_blank )
620 and
621 length( my $class = ref $e )
622 ) {
c40b5744 623 carp_unique(
624 "Objects of external exception class '$class' stringify to '' (the "
84e4e006 625 . 'empty string), implementing the so called null-object-pattern. '
626 . 'Given Perl\'s "globally cooperative" exception handling using this '
627 . 'class of exceptions is extremely dangerous, as it may (and often '
628 . 'does) result in silent discarding of errors. DBIx::Class tries to '
629 . 'work around this as much as possible, but other parts of your '
630 . 'software stack may not be even aware of the problem. Please submit '
c40b5744 631 . "a bugreport against the distribution containing '$class'",
632 );
84e4e006 633
634 $not_blank = 1;
635 }
841efcb3 636
637 return $not_blank;
638}
639
3d56e026 640{
ddcc02d1 641 my $callstack_state;
642
e2741c7f 643 # Recreate the logic of Try::Tiny, but without the crazy Sub::Name
644 # invocations and without support for finally() altogether
645 # ( yes, these days Try::Tiny is so "tiny" it shows *ON TOP* of most
646 # random profiles https://youtu.be/PYCbumw0Fis?t=1919 )
ddcc02d1 647 sub dbic_internal_try (&;@) {
648
649 my $try_cref = shift;
650 my $catch_cref = undef; # apparently this is a thing... https://rt.perl.org/Public/Bug/Display.html?id=119311
651
652 for my $arg (@_) {
653
e2741c7f 654 croak 'dbic_internal_try() may not be followed by multiple dbic_internal_catch() blocks'
655 if $catch_cref;
ddcc02d1 656
e2741c7f 657 ($catch_cref = $$arg), next
658 if ref($arg) eq 'DBIx::Class::_Util::Catch';
ddcc02d1 659
e2741c7f 660 croak( 'Mixing dbic_internal_try() with Try::Tiny::catch() is not supported' )
661 if ref($arg) eq 'Try::Tiny::Catch';
662
663 croak( 'dbic_internal_try() does not support finally{}' )
664 if ref($arg) eq 'Try::Tiny::Finally';
665
666 croak(
667 'dbic_internal_try() encountered an unexpected argument '
668 . "'@{[ defined $arg ? $arg : 'UNDEF' ]}' - perhaps "
669 . 'a missing semi-colon before or ' # trailing space important
670 );
ddcc02d1 671 }
672
673 my $wantarray = wantarray;
674 my $preexisting_exception = $@;
675
676 my @ret;
e2741c7f 677 my $saul_goodman = eval {
ddcc02d1 678 $@ = $preexisting_exception;
679
680 local $callstack_state->{in_internal_try} = 1
681 unless $callstack_state->{in_internal_try};
682
683 # always unset - someone may have snuck it in
5c33c8be 684 local $SIG{__DIE__} if $SIG{__DIE__};
ddcc02d1 685
686 if( $wantarray ) {
687 @ret = $try_cref->();
688 }
689 elsif( defined $wantarray ) {
690 $ret[0] = $try_cref->();
691 }
692 else {
693 $try_cref->();
694 }
695
696 1;
697 };
698
699 my $exception = $@;
700 $@ = $preexisting_exception;
701
e2741c7f 702 if ( $saul_goodman ) {
ddcc02d1 703 return $wantarray ? @ret : $ret[0]
704 }
705 elsif ( $catch_cref ) {
706 for ( $exception ) {
707 return $catch_cref->($exception);
708 }
709 }
710
711 return;
712 }
713
e2741c7f 714 sub dbic_internal_catch (&;@) {
715
716 croak( 'Useless use of bare dbic_internal_catch()' )
717 unless wantarray;
718
719 croak( 'dbic_internal_catch() must receive exactly one argument at end of expression' )
720 if @_ > 1;
721
722 bless(
723 \( $_[0] ),
724 'DBIx::Class::_Util::Catch'
725 ),
726 }
727
728 sub in_internal_try () {
729 !! $callstack_state->{in_internal_try}
730 }
ddcc02d1 731}
732
733{
3d56e026 734 my $destruction_registry = {};
735
04c1a070 736 sub DBIx::Class::__Util_iThreads_handler__::CLONE {
d098704f 737 %$destruction_registry = map {
738 (defined $_)
739 ? ( refaddr($_) => $_ )
740 : ()
741 } values %$destruction_registry;
d52fc26d 742
d098704f 743 weaken($_) for values %$destruction_registry;
29211e03 744
d52fc26d 745 # Dummy NEXTSTATE ensuring the all temporaries on the stack are garbage
746 # collected before leaving this scope. Depending on the code above, this
747 # may very well be just a preventive measure guarding future modifications
748 undef;
3d56e026 749 }
750
751 # This is almost invariably invoked from within DESTROY
752 # throwing exceptions won't work
e1d9e578 753 sub detected_reinvoked_destructor {
3d56e026 754
755 # quick "garbage collection" pass - prevents the registry
756 # from slowly growing with a bunch of undef-valued keys
757 defined $destruction_registry->{$_} or delete $destruction_registry->{$_}
758 for keys %$destruction_registry;
759
e1d9e578 760 if (! length ref $_[0]) {
c40b5744 761 emit_loud_diag(
762 emit_dups => 1,
763 msg => (caller(0))[3] . '() expects a blessed reference'
764 );
3d56e026 765 return undef; # don't know wtf to do
766 }
e1d9e578 767 elsif (! defined $destruction_registry->{ my $addr = refaddr($_[0]) } ) {
3d56e026 768 weaken( $destruction_registry->{$addr} = $_[0] );
769 return 0;
770 }
771 else {
c40b5744 772 emit_loud_diag( msg => sprintf (
3d56e026 773 'Preventing *MULTIPLE* DESTROY() invocations on %s - an *EXTREMELY '
774 . 'DANGEROUS* condition which is *ALMOST CERTAINLY GLOBAL* within your '
775 . 'application, affecting *ALL* classes without active protection against '
776 . 'this. Diagnose and fix the root cause ASAP!!!%s',
777 refdesc $_[0],
778 ( ( $INC{'Devel/StackTrace.pm'} and ! do { local $@; eval { Devel::StackTrace->VERSION(2) } } )
779 ? " (likely culprit Devel::StackTrace\@@{[ Devel::StackTrace->VERSION ]} found in %INC, http://is.gd/D_ST_refcap)"
780 : ''
781 )
782 ));
783
784 return 1;
785 }
786 }
787}
788
7302b3e0 789my $module_name_rx = qr/ \A [A-Z_a-z] [0-9A-Z_a-z]* (?: :: [0-9A-Z_a-z]+ )* \z /x;
790my $ver_rx = qr/ \A [0-9]+ (?: \. [0-9]+ )* (?: \_ [0-9]+ )* \z /x;
791
bf302897 792sub modver_gt_or_eq ($$) {
b1dbf716 793 my ($mod, $ver) = @_;
794
795 croak "Nonsensical module name supplied"
7302b3e0 796 if ! defined $mod or $mod !~ $module_name_rx;
b1dbf716 797
798 croak "Nonsensical minimum version supplied"
7302b3e0 799 if ! defined $ver or $ver !~ $ver_rx;
800
d6c13bfd 801 my $ver_cache = do {
802 no strict 'refs';
803 ${"${mod}::__DBIC_MODULE_VERSION_CHECKS__"} ||= {}
804 };
7302b3e0 805
806 ! defined $ver_cache->{$ver}
807 and
808 $ver_cache->{$ver} = do {
b1dbf716 809
7302b3e0 810 local $SIG{__WARN__} = sigwarn_silencer( qr/\Qisn't numeric in subroutine entry/ )
811 if SPURIOUS_VERSION_CHECK_WARNINGS;
b1dbf716 812
d6c13bfd 813 # prevent captures by potential __WARN__ hooks or the like:
814 # there is nothing of value that can be happening here, and
815 # leaving a hook in-place can only serve to fail some test
816 local $SIG{__WARN__} if (
817 ! SPURIOUS_VERSION_CHECK_WARNINGS
818 and
819 $SIG{__WARN__}
820 );
821
822 croak "$mod does not seem to provide a version (perhaps it never loaded)"
823 unless $mod->VERSION;
824
5c33c8be 825 local $SIG{__DIE__} if $SIG{__DIE__};
7302b3e0 826 local $@;
7302b3e0 827 eval { $mod->VERSION($ver) } ? 1 : 0;
828 };
56270bba 829
7302b3e0 830 $ver_cache->{$ver};
b1dbf716 831}
832
d634850b 833sub modver_gt_or_eq_and_lt ($$$) {
834 my ($mod, $v_ge, $v_lt) = @_;
835
836 croak "Nonsensical maximum version supplied"
7302b3e0 837 if ! defined $v_lt or $v_lt !~ $ver_rx;
d634850b 838
839 return (
840 modver_gt_or_eq($mod, $v_ge)
841 and
842 ! modver_gt_or_eq($mod, $v_lt)
843 ) ? 1 : 0;
844}
845
296248c3 846{
296248c3 847
848 sub describe_class_methods {
8eac247d 849 my $args = (
850 ref $_[0] eq 'HASH' ? $_[0]
851 : ( @_ == 1 and ! length ref $_[0] ) ? { class => $_[0] }
852 : { @_ }
853 );
854
855 my ($class, $requested_mro) = @{$args}{qw( class use_mro )};
296248c3 856
8eac247d 857 croak "Expecting a class name either as the sole argument or a 'class' option"
5e67be26 858 if not defined $class or $class !~ $module_name_rx;
296248c3 859
5f0174dc 860 croak(
861 "The supplied 'class' argument is tainted: this is *extremely* "
862 . 'dangerous, fix your code ASAP!!! ( for more details read through '
863 . 'https://is.gd/perl_mro_taint_wtf )'
864 ) if (
865 DBIx::Class::_ENV_::TAINT_MODE
866 and
867 Scalar::Util::tainted($class)
868 );
869
1cf2ad8b 870 $requested_mro ||= mro::get_mro($class);
871
872 # mro::set_mro() does not bump pkg_gen - WHAT THE FUCK?!
873 my $query_cache_key = "$class|$requested_mro";
874
953f8eb0 875 my $internal_cache_key =
1cf2ad8b 876 ( mro::get_mro($class) eq $requested_mro )
877 ? $class
878 : $query_cache_key
879 ;
880
296248c3 881 # use a cache on old MRO, since while we are recursing in this function
882 # nothing can possibly change (the speedup is immense)
883 # (yes, people could be tie()ing the stash and adding methods on access
884 # but there is a limit to how much crazy can be supported here)
885 #
886 # we use the cache for linear_isa lookups on new MRO as well - it adds
887 # a *tiny* speedup, and simplifies the code a lot
888 #
953f8eb0 889 local $__describe_class_query_cache->{'!internal!'} = {}
890 unless $__describe_class_query_cache->{'!internal!'};
296248c3 891
892 my $my_gen = 0;
893
d01688cc 894 $my_gen += get_real_pkg_gen($_) for ( my @full_ISA = (
895
896 @{
953f8eb0 897 $__describe_class_query_cache->{'!internal!'}{$internal_cache_key}{linear_isa}
296248c3 898 ||=
1cf2ad8b 899 mro::get_linear_isa($class, $requested_mro)
d01688cc 900 },
901
902 ((
953f8eb0 903 $__describe_class_query_cache->{'!internal!'}{$class}{is_universal}
d01688cc 904 ||=
905 mro::is_universal($class)
906 ) ? () : @{
953f8eb0 907 $__describe_class_query_cache->{'!internal!'}{UNIVERSAL}{linear_isa}
d01688cc 908 ||=
909 mro::get_linear_isa("UNIVERSAL")
910 }),
911
912 ));
296248c3 913
953f8eb0 914 my $slot = $__describe_class_query_cache->{$query_cache_key} ||= {};
296248c3 915
916 unless ( ($slot->{cumulative_gen}||0) == $my_gen ) {
917
918 # reset
919 %$slot = (
920 class => $class,
2603b495 921 isa => { map { $_ => 1 } @full_ISA },
922 linear_isa => [
953f8eb0 923 @{ $__describe_class_query_cache->{'!internal!'}{$internal_cache_key}{linear_isa} }
924 [ 1 .. $#{$__describe_class_query_cache->{'!internal!'}{$internal_cache_key}{linear_isa}} ]
d01688cc 925 ],
296248c3 926 mro => {
1cf2ad8b 927 type => $requested_mro,
928 is_c3 => ( ($requested_mro eq 'c3') ? 1 : 0 ),
296248c3 929 },
930 cumulative_gen => $my_gen,
931 );
296248c3 932
2603b495 933 # remove ourselves from ISA
934 shift @full_ISA;
935
296248c3 936 # ensure the cache is populated for the parents, code below can then
937 # efficiently operate over the query_cache directly
d01688cc 938 describe_class_methods($_) for reverse @full_ISA;
296248c3 939
296248c3 940 no strict 'refs';
941
942 # combine full ISA-order inherited and local method list into a
943 # "shadowing stack"
944
945 (
085dbdd6 946 unshift @{ $slot->{methods}{$_->{name}} }, $_
296248c3 947
948 and
949
085dbdd6 950 (
951 $_->{via_class} ne $class
952 or
953 $slot->{methods_defined_in_class}{$_->{name}} = $_
954 )
296248c3 955
956 and
957
958 @{ $slot->{methods}{$_->{name}} } > 1
959
960 and
961
962 $slot->{methods_with_supers}{$_->{name}} = $slot->{methods}{$_->{name}}
963
964 ) for (
965
d01688cc 966 # what describe_class_methods for @full_ISA produced above
085dbdd6 967 ( map { values %{
953f8eb0 968 $__describe_class_query_cache->{$_}{methods_defined_in_class} || {}
1cf2ad8b 969 } } map { "$_|" . mro::get_mro($_) } reverse @full_ISA ),
296248c3 970
971 # our own non-cleaned subs + their attributes
972 ( map {
973 (
1c179556 974 # need to account for dummy helper crefs under OLD_MRO
296248c3 975 (
1c179556 976 ! DBIx::Class::_ENV_::OLD_MRO
296248c3 977 or
1c179556 978 ! ( ( $Class::C3::MRO{$class} || {} )->{methods}{$_} )
296248c3 979 )
980 and
1c179556 981 # these 2 OR-ed checks are sufficient for 5.10+
296248c3 982 (
1c179556 983 ref(\ "${class}::"->{$_} ) ne 'GLOB'
296248c3 984 or
1c179556 985 defined( *{ "${class}::"->{$_} }{CODE} )
296248c3 986 )
987 ) ? {
988 via_class => $class,
989 name => $_,
92705f7f 990 attributes => { map { $_ => 1 } do {
991 my @attrs;
992 local $@;
993 local $SIG{__DIE__} if $SIG{__DIE__};
994 # attributes::get may throw on blessed-false crefs :/
995 eval { @attrs = attributes::get( \&{"${class}::${_}"} ); 1 }
996 or warn "Unable to determine attributes of the \\&${class}::$_ method due to following error: $@";
997 @attrs;
998 } },
296248c3 999 }
1000 : ()
1001 } keys %{"${class}::"} )
1002 );
1003
1004
1005 # recalculate the pkg_gen on newer perls under Taint mode,
1006 # because of shit like:
1007 # perl -T -Mmro -e 'package Foo; sub bar {}; defined( *{ "Foo::"->{bar}}{CODE} ) and warn mro::get_pkg_gen("Foo") for (1,2,3)'
1008 #
1009 if (
1010 ! DBIx::Class::_ENV_::OLD_MRO
1011 and
5f0174dc 1012 DBIx::Class::_ENV_::TAINT_MODE
296248c3 1013 ) {
1014
1015 $slot->{cumulative_gen} = 0;
1016 $slot->{cumulative_gen} += get_real_pkg_gen($_)
d01688cc 1017 for $class, @full_ISA;
296248c3 1018 }
1019 }
1020
1021 # RV
1022 +{ %$slot };
1023 }
1024}
1025
e3be2b6f 1026
1027#
1028# Why not just use some higher-level module or at least File::Spec here?
1029# Because:
1030# 1) This is a *very* rarely used function, and the deptree is large
1031# enough already as it is
1032#
1033# 2) (more importantly) Our tooling is utter shit in this area. There
1034# is no comprehensive support for UNC paths in PathTools and there
1035# are also various small bugs in representation across different
1036# path-manipulation CPAN offerings.
1037#
1038# Since this routine is strictly used for logical path processing (it
1039# *must* be able to work with not-yet-existing paths), use this seemingly
1040# simple but I *think* complete implementation to feed to other consumers
1041#
1042# If bugs are ever uncovered in this routine, *YOU ARE URGED TO RESIST*
1043# the impulse to bring in an external dependency. During runtime there
1044# is exactly one spot that could potentially maybe once in a blue moon
1045# use this function. Keep it lean.
1046#
1047sub parent_dir ($) {
1048 ( $_[0] =~ m{ [\/\\] ( \.{0,2} ) ( [\/\\]* ) \z }x )
1049 ? (
1050 $_[0]
1051 .
1052 ( ( length($1) and ! length($2) ) ? '/' : '' )
1053 .
1054 '../'
1055 )
1056 : (
1057 require File::Spec
1058 and
1059 File::Spec->catpath (
1060 ( File::Spec->splitpath( "$_[0]" ) )[0,1],
1061 '/',
1062 )
1063 )
1064 ;
1065}
1066
439a7283 1067sub mkdir_p ($) {
1068 require File::Path;
1069 # do not ask for a recent version, use 1.x API calls
1070 File::Path::mkpath([ "$_[0]" ]); # File::Path does not like objects
1071}
1072
e3be2b6f 1073
77c3a5dc 1074sub fail_on_internal_call {
7474ed3b 1075 my $fr = [ CORE::caller(1) ];
1b822bd3 1076
1077 die "\nMethod $fr->[3] is not marked with the 'DBIC_method_is_indirect_sugar' attribute\n\n" unless (
1078
1079 # unlikely but who knows...
1080 ! @$fr
1081
1082 or
1083
1084 # This is a weird-ass double-purpose method, only one branch of which is marked
1085 # as an illegal indirect call
1086 # Hence the 'indirect' attribute makes no sense
1087 # FIXME - likely need to mark this in some other manner
1088 $fr->[3] eq 'DBIx::Class::ResultSet::new'
1089
1090 or
1091
1092 # RsrcProxy stuff is special and not attr-annotated on purpose
1093 # Yet it is marked (correctly) as fail_on_internal_call(), as DBIC
1094 # itself should not call these methods as first-entry
1095 $fr->[3] =~ /^DBIx::Class::ResultSourceProxy::[^:]+$/
1096
1097 or
1098
1099 # FIXME - there is likely a more fine-graned way to escape "foreign"
1100 # callers, based on annotations... (albeit a slower one)
1101 # For the time being just skip in a dumb way
1102 $fr->[3] !~ /^DBIx::Class|^DBICx::|^DBICTest::/
1103
1104 or
1105
1106 grep
1107 { $_ eq 'DBIC_method_is_indirect_sugar' }
1108 do { no strict 'refs'; attributes::get( \&{ $fr->[3] }) }
1109 );
1110
1111
7474ed3b 1112 my @fr2;
1113 # need to make allowance for a proxy-yet-direct call
1114 # or for an exception wrapper
1115 $fr = \@fr2 if (
1116 (
1117 $fr->[3] eq '(eval)'
1118 and
1119 @fr2 = (CORE::caller(2))
1120 )
1121 or
1122 (
1123 $fr->[0] eq 'DBIx::Class::ResultSourceProxy'
1124 and
1125 @fr2 = (CORE::caller(2))
1126 and
1127 (
1128 ( $fr->[3] =~ /([^:])+$/ )[0]
1129 eq
1130 ( $fr2[3] =~ /([^:])+$/ )[0]
1131 )
1132 )
1133 );
1134
1135
77c3a5dc 1136 if (
e570488a 1137 defined $fr->[0]
77c3a5dc 1138 and
7474ed3b 1139 $fr->[0] =~ /^(?:DBIx::Class|DBICx::)/
77c3a5dc 1140 and
7474ed3b 1141 $fr->[1] !~ /\b(?:CDBICompat|ResultSetProxy)\b/ # no point touching there
c5340bfa 1142 and
1143 # one step higher
1144 @fr2 = CORE::caller(@fr2 ? 3 : 2)
1145 and
1146 # if the frame that called us is an indirect itself - nothing to see here
1147 ! grep
1148 { $_ eq 'DBIC_method_is_indirect_sugar' }
1149 do {
1150 no strict 'refs';
1151 attributes::get( \&{ $fr2[3] })
1152 }
77c3a5dc 1153 ) {
7474ed3b 1154
1155 my $argdesc;
1156
1157 {
1158 package DB;
1159
1160 my @throwaway = caller( @fr2 ? 2 : 1 );
1161
1162 # screwing with $DB::args is rather volatile - be extra careful
1163 no warnings 'uninitialized';
1164
1165 $argdesc =
1166 ( not defined $DB::args[0] ) ? 'UNAVAILABLE'
1167 : ( length ref $DB::args[0] ) ? DBIx::Class::_Util::refdesc($DB::args[0])
1168 : $DB::args[0] . ''
1169 ;
1170 };
1171
77c3a5dc 1172 DBIx::Class::Exception->throw( sprintf (
e5053694 1173 "Illegal internal call of indirect proxy-method %s() with argument '%s': examine the last lines of the proxy method deparse below to determine what to call directly instead at %s on line %d\n\n%s\n\n Stacktrace starts",
77c3a5dc 1174 $fr->[3], $argdesc, @{$fr}[1,2], ( $fr->[6] || do {
1175 require B::Deparse;
1176 no strict 'refs';
1177 B::Deparse->new->coderef2text(\&{$fr->[3]})
1178 }),
1179 ), 'with_stacktrace');
1180 }
1181}
1182
534aff61 1183if (DBIx::Class::_ENV_::ASSERT_NO_ERRONEOUS_METAINSTANCE_USE) {
1184
1185 no warnings 'redefine';
1186
1187 my $next_bless = defined(&CORE::GLOBAL::bless)
1188 ? \&CORE::GLOBAL::bless
1189 : sub { CORE::bless($_[0], $_[1]) }
1190 ;
1191
1192 *CORE::GLOBAL::bless = sub {
1193 my $class = (@_ > 1) ? $_[1] : CORE::caller();
1194
1195 # allow for reblessing (role application)
1196 return $next_bless->( $_[0], $class )
1197 if defined blessed $_[0];
1198
1199 my $obj = $next_bless->( $_[0], $class );
1200
1201 my $calling_sub = (CORE::caller(1))[3] || '';
1202
1203 (
1204 # before 5.18 ->isa() will choke on the "0" package
1205 # which we test for in several obscure cases, sigh...
1206 !( DBIx::Class::_ENV_::PERL_VERSION < 5.018 )
1207 or
1208 $class
1209 )
1210 and
1211 (
1212 (
1213 $calling_sub !~ /^ (?:
1214 DBIx::Class::Schema::clone
1215 |
1216 DBIx::Class::DB::setup_schema_instance
1217 )/x
1218 and
1219 $class->isa("DBIx::Class::Schema")
1220 )
1221 or
1222 (
1223 $calling_sub ne 'DBIx::Class::ResultSource::new'
1224 and
1225 $class->isa("DBIx::Class::ResultSource")
1226 )
1227 )
1228 and
1229 local $Carp::CarpLevel = $Carp::CarpLevel + 1
1230 and
1231 Carp::confess("Improper instantiation of '$obj': you *MUST* call the corresponding constructor");
1232
1233
1234 $obj;
1235 };
1236}
1237
b1dbf716 12381;