Move even more utils into DBIC::_Util (see next commit)
[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 use constant SPURIOUS_VERSION_CHECK_WARNINGS => ( "$]" < 5.010 ? 1 : 0);
10
11 BEGIN {
12   package # hide from pause
13     DBIx::Class::_ENV_;
14
15   use Config;
16
17   use constant {
18
19     # but of course
20     BROKEN_FORK => ($^O eq 'MSWin32') ? 1 : 0,
21
22     BROKEN_GOTO => ( "$]" < 5.008003 ) ? 1 : 0,
23
24     HAS_ITHREADS => $Config{useithreads} ? 1 : 0,
25
26     UNSTABLE_DOLLARAT => ( "$]" < 5.013002 ) ? 1 : 0,
27
28     ( map
29       #
30       # the "DBIC_" prefix below is crucial - this is what makes CI pick up
31       # all envvars without further adjusting its scripts
32       # DO NOT CHANGE to the more logical { $_ => !!( $ENV{"DBIC_$_"} ) }
33       #
34       { substr($_, 5) => !!( $ENV{$_} ) }
35       qw(
36         DBIC_SHUFFLE_UNORDERED_RESULTSETS
37         DBIC_ASSERT_NO_INTERNAL_WANTARRAY
38         DBIC_ASSERT_NO_INTERNAL_INDIRECT_CALLS
39         DBIC_STRESSTEST_UTF8_UPGRADE_GENERATED_COLLAPSER_SOURCE
40         DBIC_STRESSTEST_COLUMN_INFO_UNAWARE_STORAGE
41       )
42     ),
43
44     IV_SIZE => $Config{ivsize},
45
46     OS_NAME => $^O,
47   };
48
49   if ( "$]" < 5.009_005) {
50     require MRO::Compat;
51     constant->import( OLD_MRO => 1 );
52   }
53   else {
54     require mro;
55     constant->import( OLD_MRO => 0 );
56   }
57
58   # Both of these are no longer used for anything. However bring
59   # them back after they were purged in 08a8d8f1, as there appear
60   # to be outfits with *COPY PASTED* pieces of lib/DBIx/Class/Storage/*
61   # in their production codebases. There is no point in breaking these
62   # if whatever they used actually continues to work
63   my $warned;
64   my $sigh = sub {
65
66     require Carp;
67     my $cluck = "The @{[ (caller(1))[3] ]} constant is no more - adjust your code" . Carp::longmess();
68
69     warn $cluck unless $warned->{$cluck}++;
70
71     0;
72   };
73   sub DBICTEST () { &$sigh }
74   sub PEEPEENESS () { &$sigh }
75 }
76
77 # FIXME - this is not supposed to be here
78 # Carp::Skip to the rescue soon
79 use DBIx::Class::Carp '^DBIx::Class|^DBICTest';
80
81 use B ();
82 use Carp 'croak';
83 use Storable 'nfreeze';
84 use Scalar::Util qw(weaken blessed reftype refaddr);
85 use Sub::Quote qw(qsub);
86 use Sub::Name ();
87
88 # Already correctly prototyped: perlbrew exec perl -MStorable -e 'warn prototype \&Storable::dclone'
89 BEGIN { *deep_clone = \&Storable::dclone }
90
91 use base 'Exporter';
92 our @EXPORT_OK = qw(
93   sigwarn_silencer modver_gt_or_eq modver_gt_or_eq_and_lt
94   fail_on_internal_wantarray fail_on_internal_call
95   refdesc refcount hrefaddr set_subname
96   scope_guard detected_reinvoked_destructor
97   is_exception dbic_internal_try visit_namespaces
98   quote_sub qsub perlstring serialize deep_clone dump_value uniq
99   parent_dir mkdir_p
100   UNRESOLVABLE_CONDITION
101 );
102
103 use constant UNRESOLVABLE_CONDITION => \ '1 = 0';
104
105 BEGIN {
106   # add preliminary attribute support
107   # FIXME FIXME FIXME
108   # To be revisited when Moo with proper attr support ships
109   Sub::Quote->VERSION(2.002);
110   require attributes;
111 }
112 # Override forcing no_defer, and adding naming consistency checks
113 sub quote_sub {
114   Carp::confess( "Anonymous quoting not supported by the DBIC sub_quote override - supply a sub name" ) if
115     @_ < 2
116       or
117     ! defined $_[1]
118       or
119     length ref $_[1]
120   ;
121
122   Carp::confess( "The DBIC sub_quote override expects sub name '$_[0]' to be fully qualified" )
123     unless $_[0] =~ /::/;
124
125   Carp::confess( "The DBIC sub_quote override expects the sub name '$_[0]' to match the supplied 'package' argument" ) if
126     $_[3]
127       and
128     defined $_[3]->{package}
129       and
130     index( $_[0], $_[3]->{package} ) != 0
131   ;
132
133   my @caller = caller(0);
134   my $sq_opts = {
135     package => $caller[0],
136     hints => $caller[8],
137     warning_bits => $caller[9],
138     hintshash => $caller[10],
139     %{ $_[3] || {} },
140
141     # explicitly forced for everything
142     no_defer => 1,
143   };
144
145   my $cref = Sub::Quote::quote_sub( $_[0], $_[1], $_[2]||{}, $sq_opts );
146
147   # FIXME FIXME FIXME
148   # To be revisited when Moo with proper attr support ships
149   if(
150     # external application does not work on things like :prototype(...), :lvalue, etc
151     my @attrs = grep {
152       $_ !~ /^[a-z]/
153         or
154       Carp::confess( "The DBIC sub_quote override does not support applying of reserved attribute '$_'" )
155     } @{ $sq_opts->{attributes} || []}
156   ) {
157     Carp::confess( "The DBIC sub_quote override does not allow mixing 'attributes' with 'no_install'" )
158       if $sq_opts->{no_install};
159
160     # might be different from $sq_opts->{package};
161     my ($install_into) = $_[0] =~ /(.+)::[^:]+$/;
162
163     attributes->import( $install_into, $cref, @attrs );
164   }
165
166   $cref;
167 }
168
169 sub sigwarn_silencer ($) {
170   my $pattern = shift;
171
172   croak "Expecting a regexp" if ref $pattern ne 'Regexp';
173
174   my $orig_sig_warn = $SIG{__WARN__} || sub { CORE::warn(@_) };
175
176   return sub { &$orig_sig_warn unless $_[0] =~ $pattern };
177 }
178
179 sub perlstring ($) { q{"}. quotemeta( shift ). q{"} };
180
181 sub hrefaddr ($) { sprintf '0x%x', &refaddr||0 }
182
183 sub refdesc ($) {
184   croak "Expecting a reference" if ! length ref $_[0];
185
186   # be careful not to trigger stringification,
187   # reuse @_ as a scratch-pad
188   sprintf '%s%s(0x%x)',
189     ( defined( $_[1] = blessed $_[0]) ? "$_[1]=" : '' ),
190     reftype $_[0],
191     refaddr($_[0]),
192   ;
193 }
194
195 sub refcount ($) {
196   croak "Expecting a reference" if ! length ref $_[0];
197
198   # No tempvars - must operate on $_[0], otherwise the pad
199   # will count as an extra ref
200   B::svref_2object($_[0])->REFCNT;
201 }
202
203 sub visit_namespaces {
204   my $args = { (ref $_[0]) ? %{$_[0]} : @_ };
205
206   my $visited_count = 1;
207
208   # A package and a namespace are subtly different things
209   $args->{package} ||= 'main';
210   $args->{package} = 'main' if $args->{package} =~ /^ :: (?: main )? $/x;
211   $args->{package} =~ s/^:://;
212
213   if ( $args->{action}->($args->{package}) ) {
214     my $ns =
215       ( ($args->{package} eq 'main') ? '' :  $args->{package} )
216         .
217       '::'
218     ;
219
220     $visited_count += visit_namespaces( %$args, package => $_ ) for
221       grep
222         # this happens sometimes on %:: traversal
223         { $_ ne '::main' }
224         map
225           { $_ =~ /^(.+?)::$/ ? "$ns$1" : () }
226           do { no strict 'refs'; keys %$ns }
227     ;
228   }
229
230   $visited_count;
231 }
232
233 # FIXME In another life switch this to a polyfill like the one in namespace::clean
234 sub set_subname ($$) {
235
236   # fully qualify name
237   splice @_, 0, 1, caller(0) . "::$_[0]"
238     if $_[0] !~ /::|'/;
239
240   &Sub::Name::subname;
241 }
242
243 sub serialize ($) {
244   local $Storable::canonical = 1;
245   nfreeze($_[0]);
246 }
247
248 sub uniq {
249   my( %seen, $seen_undef, $numeric_preserving_copy );
250   grep { not (
251     defined $_
252       ? $seen{ $numeric_preserving_copy = $_ }++
253       : $seen_undef++
254   ) } @_;
255 }
256
257 my $dd_obj;
258 sub dump_value ($) {
259   local $Data::Dumper::Indent = 1
260     unless defined $Data::Dumper::Indent;
261
262   my $dump_str = (
263     $dd_obj
264       ||=
265     do {
266       require Data::Dumper;
267       my $d = Data::Dumper->new([])
268         ->Purity(0)
269         ->Pad('')
270         ->Useqq(1)
271         ->Terse(1)
272         ->Freezer('')
273         ->Quotekeys(0)
274         ->Bless('bless')
275         ->Pair(' => ')
276         ->Sortkeys(1)
277         ->Deparse(1)
278       ;
279
280       $d->Sparseseen(1) if modver_gt_or_eq (
281         'Data::Dumper', '2.136'
282       );
283
284       $d;
285     }
286   )->Values([$_[0]])->Dump;
287
288   $dd_obj->Reset->Values([]);
289
290   $dump_str;
291 }
292
293 sub scope_guard (&) {
294   croak 'Calling scope_guard() in void context makes no sense'
295     if ! defined wantarray;
296
297   # no direct blessing of coderefs - DESTROY is buggy on those
298   bless [ $_[0] ], 'DBIx::Class::_Util::ScopeGuard';
299 }
300 {
301   package #
302     DBIx::Class::_Util::ScopeGuard;
303
304   sub DESTROY {
305     &DBIx::Class::_Util::detected_reinvoked_destructor;
306
307     local $@ if DBIx::Class::_ENV_::UNSTABLE_DOLLARAT;
308
309     eval {
310       $_[0]->[0]->();
311       1;
312     }
313       or
314     Carp::cluck(
315       "Execution of scope guard $_[0] resulted in the non-trappable exception:\n\n$@"
316     );
317   }
318 }
319
320
321 sub is_exception ($) {
322   my $e = $_[0];
323
324   # FIXME
325   # this is not strictly correct - an eval setting $@ to undef
326   # is *not* the same as an eval setting $@ to ''
327   # but for the sake of simplicity assume the following for
328   # the time being
329   return 0 unless defined $e;
330
331   my ($not_blank, $suberror);
332   {
333     local $SIG{__DIE__} if $SIG{__DIE__};
334     local $@;
335     eval {
336       # The ne() here is deliberate - a plain length($e), or worse "$e" ne
337       # will entirely obviate the need for the encolsing eval{}, as the
338       # condition we guard against is a missing fallback overload
339       $not_blank = ( $e ne '' );
340       1;
341     } or $suberror = $@;
342   }
343
344   if (defined $suberror) {
345     if (length (my $class = blessed($e) )) {
346       carp_unique( sprintf(
347         'External exception class %s implements partial (broken) overloading '
348       . 'preventing its instances from being used in simple ($x eq $y) '
349       . 'comparisons. Given Perl\'s "globally cooperative" exception '
350       . 'handling this type of brokenness is extremely dangerous on '
351       . 'exception objects, as it may (and often does) result in silent '
352       . '"exception substitution". DBIx::Class tries to work around this '
353       . 'as much as possible, but other parts of your software stack may '
354       . 'not be even aware of this. Please submit a bugreport against the '
355       . 'distribution containing %s and in the meantime apply a fix similar '
356       . 'to the one shown at %s, in order to ensure your exception handling '
357       . 'is saner application-wide. What follows is the actual error text '
358       . "as generated by Perl itself:\n\n%s\n ",
359         $class,
360         $class,
361         'http://v.gd/DBIC_overload_tempfix/',
362         $suberror,
363       ));
364
365       # workaround, keeps spice flowing
366       $not_blank = !!( length $e );
367     }
368     else {
369       # not blessed yet failed the 'ne'... this makes 0 sense...
370       # just throw further
371       die $suberror
372     }
373   }
374   elsif (
375     # a ref evaluating to '' is definitively a "null object"
376     ( not $not_blank )
377       and
378     length( my $class = ref $e )
379   ) {
380     carp_unique( sprintf(
381       "Objects of external exception class '%s' stringify to '' (the "
382     . 'empty string), implementing the so called null-object-pattern. '
383     . 'Given Perl\'s "globally cooperative" exception handling using this '
384     . 'class of exceptions is extremely dangerous, as it may (and often '
385     . 'does) result in silent discarding of errors. DBIx::Class tries to '
386     . 'work around this as much as possible, but other parts of your '
387     . 'software stack may not be even aware of the problem. Please submit '
388     . 'a bugreport against the distribution containing %s',
389
390       ($class) x 2,
391     ));
392
393     $not_blank = 1;
394   }
395
396   return $not_blank;
397 }
398
399 {
400   my $callstack_state;
401
402   # Recreate the logic of try(), while reusing the catch()/finally() as-is
403   #
404   # FIXME: We need to move away from Try::Tiny entirely (way too heavy and
405   # yes, shows up ON TOP of profiles) but this is a batle for another maint
406   sub dbic_internal_try (&;@) {
407
408     my $try_cref = shift;
409     my $catch_cref = undef;  # apparently this is a thing... https://rt.perl.org/Public/Bug/Display.html?id=119311
410
411     for my $arg (@_) {
412
413       if( ref($arg) eq 'Try::Tiny::Catch' ) {
414
415         croak 'dbic_internal_try() may not be followed by multiple catch() blocks'
416           if $catch_cref;
417
418         $catch_cref = $$arg;
419       }
420       elsif ( ref($arg) eq 'Try::Tiny::Finally' ) {
421         croak 'dbic_internal_try() does not support finally{}';
422       }
423       else {
424         croak(
425           'dbic_internal_try() encountered an unexpected argument '
426         . "'@{[ defined $arg ? $arg : 'UNDEF' ]}' - perhaps "
427         . 'a missing semi-colon before or ' # trailing space important
428         );
429       }
430     }
431
432     my $wantarray = wantarray;
433     my $preexisting_exception = $@;
434
435     my @ret;
436     my $all_good = eval {
437       $@ = $preexisting_exception;
438
439       local $callstack_state->{in_internal_try} = 1
440         unless $callstack_state->{in_internal_try};
441
442       # always unset - someone may have snuck it in
443       local $SIG{__DIE__} if $SIG{__DIE__};
444
445       if( $wantarray ) {
446         @ret = $try_cref->();
447       }
448       elsif( defined $wantarray ) {
449         $ret[0] = $try_cref->();
450       }
451       else {
452         $try_cref->();
453       }
454
455       1;
456     };
457
458     my $exception = $@;
459     $@ = $preexisting_exception;
460
461     if ( $all_good ) {
462       return $wantarray ? @ret : $ret[0]
463     }
464     elsif ( $catch_cref ) {
465       for ( $exception ) {
466         return $catch_cref->($exception);
467       }
468     }
469
470     return;
471   }
472
473   sub in_internal_try { !! $callstack_state->{in_internal_try} }
474 }
475
476 {
477   my $destruction_registry = {};
478
479   sub DBIx::Class::__Util_iThreads_handler__::CLONE {
480     %$destruction_registry = map {
481       (defined $_)
482         ? ( refaddr($_) => $_ )
483         : ()
484     } values %$destruction_registry;
485
486     weaken($_) for values %$destruction_registry;
487
488     # Dummy NEXTSTATE ensuring the all temporaries on the stack are garbage
489     # collected before leaving this scope. Depending on the code above, this
490     # may very well be just a preventive measure guarding future modifications
491     undef;
492   }
493
494   # This is almost invariably invoked from within DESTROY
495   # throwing exceptions won't work
496   sub detected_reinvoked_destructor {
497
498     # quick "garbage collection" pass - prevents the registry
499     # from slowly growing with a bunch of undef-valued keys
500     defined $destruction_registry->{$_} or delete $destruction_registry->{$_}
501       for keys %$destruction_registry;
502
503     if (! length ref $_[0]) {
504       printf STDERR '%s() expects a blessed reference %s',
505         (caller(0))[3],
506         Carp::longmess,
507       ;
508       return undef; # don't know wtf to do
509     }
510     elsif (! defined $destruction_registry->{ my $addr = refaddr($_[0]) } ) {
511       weaken( $destruction_registry->{$addr} = $_[0] );
512       return 0;
513     }
514     else {
515       carp_unique ( sprintf (
516         'Preventing *MULTIPLE* DESTROY() invocations on %s - an *EXTREMELY '
517       . 'DANGEROUS* condition which is *ALMOST CERTAINLY GLOBAL* within your '
518       . 'application, affecting *ALL* classes without active protection against '
519       . 'this. Diagnose and fix the root cause ASAP!!!%s',
520       refdesc $_[0],
521         ( ( $INC{'Devel/StackTrace.pm'} and ! do { local $@; eval { Devel::StackTrace->VERSION(2) } } )
522           ? " (likely culprit Devel::StackTrace\@@{[ Devel::StackTrace->VERSION ]} found in %INC, http://is.gd/D_ST_refcap)"
523           : ''
524         )
525       ));
526
527       return 1;
528     }
529   }
530 }
531
532 my $module_name_rx = qr/ \A [A-Z_a-z] [0-9A-Z_a-z]* (?: :: [0-9A-Z_a-z]+ )* \z /x;
533 my $ver_rx =         qr/ \A [0-9]+ (?: \. [0-9]+ )* (?: \_ [0-9]+ )*        \z /x;
534
535 sub modver_gt_or_eq ($$) {
536   my ($mod, $ver) = @_;
537
538   croak "Nonsensical module name supplied"
539     if ! defined $mod or $mod !~ $module_name_rx;
540
541   croak "Nonsensical minimum version supplied"
542     if ! defined $ver or $ver !~ $ver_rx;
543
544   no strict 'refs';
545   my $ver_cache = ${"${mod}::__DBIC_MODULE_VERSION_CHECKS__"} ||= ( $mod->VERSION
546     ? {}
547     : croak "$mod does not seem to provide a version (perhaps it never loaded)"
548   );
549
550   ! defined $ver_cache->{$ver}
551     and
552   $ver_cache->{$ver} = do {
553
554     local $SIG{__WARN__} = sigwarn_silencer( qr/\Qisn't numeric in subroutine entry/ )
555       if SPURIOUS_VERSION_CHECK_WARNINGS;
556
557     local $SIG{__DIE__} if $SIG{__DIE__};
558     local $@;
559     eval { $mod->VERSION($ver) } ? 1 : 0;
560   };
561
562   $ver_cache->{$ver};
563 }
564
565 sub modver_gt_or_eq_and_lt ($$$) {
566   my ($mod, $v_ge, $v_lt) = @_;
567
568   croak "Nonsensical maximum version supplied"
569     if ! defined $v_lt or $v_lt !~ $ver_rx;
570
571   return (
572     modver_gt_or_eq($mod, $v_ge)
573       and
574     ! modver_gt_or_eq($mod, $v_lt)
575   ) ? 1 : 0;
576 }
577
578
579 #
580 # Why not just use some higher-level module or at least File::Spec here?
581 # Because:
582 # 1)  This is a *very* rarely used function, and the deptree is large
583 #     enough already as it is
584 #
585 # 2)  (more importantly) Our tooling is utter shit in this area. There
586 #     is no comprehensive support for UNC paths in PathTools and there
587 #     are also various small bugs in representation across different
588 #     path-manipulation CPAN offerings.
589 #
590 # Since this routine is strictly used for logical path processing (it
591 # *must* be able to work with not-yet-existing paths), use this seemingly
592 # simple but I *think* complete implementation to feed to other consumers
593 #
594 # If bugs are ever uncovered in this routine, *YOU ARE URGED TO RESIST*
595 # the impulse to bring in an external dependency. During runtime there
596 # is exactly one spot that could potentially maybe once in a blue moon
597 # use this function. Keep it lean.
598 #
599 sub parent_dir ($) {
600   ( $_[0] =~ m{  [\/\\]  ( \.{0,2} ) ( [\/\\]* ) \z }x )
601     ? (
602       $_[0]
603         .
604       ( ( length($1) and ! length($2) ) ? '/' : '' )
605         .
606       '../'
607     )
608     : (
609       require File::Spec
610         and
611       File::Spec->catpath (
612         ( File::Spec->splitpath( "$_[0]" ) )[0,1],
613         '/',
614       )
615     )
616   ;
617 }
618
619 sub mkdir_p ($) {
620   require File::Path;
621   # do not ask for a recent version, use 1.x API calls
622   File::Path::mkpath([ "$_[0]" ]);  # File::Path does not like objects
623 }
624
625
626 {
627   my $list_ctx_ok_stack_marker;
628
629   sub fail_on_internal_wantarray () {
630     return if $list_ctx_ok_stack_marker;
631
632     if (! defined wantarray) {
633       croak('fail_on_internal_wantarray() needs a tempvar to save the stack marker guard');
634     }
635
636     my $cf = 1;
637     while ( ( (CORE::caller($cf+1))[3] || '' ) =~ / :: (?:
638
639       # these are public API parts that alter behavior on wantarray
640       search | search_related | slice | search_literal
641
642         |
643
644       # these are explicitly prefixed, since we only recognize them as valid
645       # escapes when they come from the guts of CDBICompat
646       CDBICompat .*? :: (?: search_where | retrieve_from_sql | retrieve_all )
647
648     ) $/x ) {
649       $cf++;
650     }
651
652     my ($fr, $want, $argdesc);
653     {
654       package DB;
655       $fr = [ CORE::caller($cf) ];
656       $want = ( CORE::caller($cf-1) )[5];
657       $argdesc = ref $DB::args[0]
658         ? DBIx::Class::_Util::refdesc($DB::args[0])
659         : 'non '
660       ;
661     };
662
663     if (
664       $want and $fr->[0] =~ /^(?:DBIx::Class|DBICx::)/
665     ) {
666       DBIx::Class::Exception->throw( sprintf (
667         "Improper use of %s instance in list context at %s line %d\n\n    Stacktrace starts",
668         $argdesc, @{$fr}[1,2]
669       ), 'with_stacktrace');
670     }
671
672     weaken( $list_ctx_ok_stack_marker = my $mark = [] );
673
674     $mark;
675   }
676 }
677
678 sub fail_on_internal_call {
679   my ($fr, $argdesc);
680   {
681     package DB;
682     $fr = [ CORE::caller(1) ];
683     $argdesc = ref $DB::args[0]
684       ? DBIx::Class::_Util::refdesc($DB::args[0])
685       : ( $DB::args[0] . '' )
686     ;
687   };
688
689   if (
690     $argdesc
691       and
692     $fr->[0] =~ /^(?:DBIx::Class|DBICx::)/
693       and
694     $fr->[1] !~ /\b(?:CDBICompat|ResultSetProxy)\b/  # no point touching there
695   ) {
696     DBIx::Class::Exception->throw( sprintf (
697       "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",
698       $fr->[3], $argdesc, @{$fr}[1,2], ( $fr->[6] || do {
699         require B::Deparse;
700         no strict 'refs';
701         B::Deparse->new->coderef2text(\&{$fr->[3]})
702       }),
703     ), 'with_stacktrace');
704   }
705 }
706
707 1;