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