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