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