a77f8a31fa6b8ea1005e4199f7dfa192f5a93243
[dbsrgits/DBIx-Class.git] / lib / DBIx / Class / _Util.pm
1 package # hide from PAUSE
2   DBIx::Class::_Util;
3
4 use warnings;
5 use strict;
6
7 use constant SPURIOUS_VERSION_CHECK_WARNINGS => ($] < 5.010 ? 1 : 0);
8
9 BEGIN {
10   package # hide from pause
11     DBIx::Class::_ENV_;
12
13   use Config;
14
15   use constant {
16
17     # but of course
18     BROKEN_FORK => ($^O eq 'MSWin32') ? 1 : 0,
19
20     HAS_ITHREADS => $Config{useithreads} ? 1 : 0,
21
22     # ::Runmode would only be loaded by DBICTest, which in turn implies t/
23     DBICTEST => eval { DBICTest::RunMode->is_author } ? 1 : 0,
24
25     # During 5.13 dev cycle HELEMs started to leak on copy
26     # add an escape for these perls ON SMOKERS - a user will still get death
27     PEEPEENESS => ( eval { DBICTest::RunMode->is_smoker } && ($] >= 5.013005 and $] <= 5.013006) ),
28
29     SHUFFLE_UNORDERED_RESULTSETS => $ENV{DBIC_SHUFFLE_UNORDERED_RESULTSETS} ? 1 : 0,
30
31     ASSERT_NO_INTERNAL_WANTARRAY => $ENV{DBIC_ASSERT_NO_INTERNAL_WANTARRAY} ? 1 : 0,
32
33     IV_SIZE => $Config{ivsize},
34
35     OS_NAME => $^O,
36   };
37
38   if ($] < 5.009_005) {
39     require MRO::Compat;
40     constant->import( OLD_MRO => 1 );
41   }
42   else {
43     require mro;
44     constant->import( OLD_MRO => 0 );
45   }
46 }
47
48 # FIXME - this is not supposed to be here
49 # Carp::Skip to the rescue soon
50 use DBIx::Class::Carp '^DBIx::Class|^DBICTest';
51
52 use Carp 'croak';
53 use Scalar::Util qw(weaken blessed reftype);
54 use List::Util qw(first);
55 use overload ();
56
57 use base 'Exporter';
58 our @EXPORT_OK = qw(
59   sigwarn_silencer modver_gt_or_eq fail_on_internal_wantarray
60   refdesc refcount hrefaddr is_exception
61   is_plain_value is_literal_value
62   UNRESOLVABLE_CONDITION
63 );
64
65 use constant UNRESOLVABLE_CONDITION => \ '1 = 0';
66
67 sub sigwarn_silencer ($) {
68   my $pattern = shift;
69
70   croak "Expecting a regexp" if ref $pattern ne 'Regexp';
71
72   my $orig_sig_warn = $SIG{__WARN__} || sub { CORE::warn(@_) };
73
74   return sub { &$orig_sig_warn unless $_[0] =~ $pattern };
75 }
76
77 sub hrefaddr ($) { sprintf '0x%x', &Scalar::Util::refaddr||0 }
78
79 sub refdesc ($) {
80   croak "Expecting a reference" if ! length ref $_[0];
81
82   # be careful not to trigger stringification,
83   # reuse @_ as a scratch-pad
84   sprintf '%s%s(0x%x)',
85     ( defined( $_[1] = blessed $_[0]) ? "$_[1]=" : '' ),
86     reftype $_[0],
87     Scalar::Util::refaddr($_[0]),
88   ;
89 }
90
91 sub refcount ($) {
92   croak "Expecting a reference" if ! length ref $_[0];
93
94   require B;
95   # No tempvars - must operate on $_[0], otherwise the pad
96   # will count as an extra ref
97   B::svref_2object($_[0])->REFCNT;
98 }
99
100 sub is_exception ($) {
101   my $e = $_[0];
102
103   # this is not strictly correct - an eval setting $@ to undef
104   # is *not* the same as an eval setting $@ to ''
105   # but for the sake of simplicity assume the following for
106   # the time being
107   return 0 unless defined $e;
108
109   my ($not_blank, $suberror);
110   {
111     local $@;
112     eval {
113       $not_blank = ($e ne '') ? 1 : 0;
114       1;
115     } or $suberror = $@;
116   }
117
118   if (defined $suberror) {
119     if (length (my $class = blessed($e) )) {
120       carp_unique( sprintf(
121         'External exception class %s implements partial (broken) overloading '
122       . 'preventing its instances from being used in simple ($x eq $y) '
123       . 'comparisons. Given Perl\'s "globally cooperative" exception '
124       . 'handling this type of brokenness is extremely dangerous on '
125       . 'exception objects, as it may (and often does) result in silent '
126       . '"exception substitution". DBIx::Class tries to work around this '
127       . 'as much as possible, but other parts of your software stack may '
128       . 'not be even aware of this. Please submit a bugreport against the '
129       . 'distribution containing %s and in the meantime apply a fix similar '
130       . 'to the one shown at %s, in order to ensure your exception handling '
131       . 'is saner application-wide. What follows is the actual error text '
132       . "as generated by Perl itself:\n\n%s\n ",
133         $class,
134         $class,
135         'http://v.gd/DBIC_overload_tempfix/',
136         $suberror,
137       ));
138
139       # workaround, keeps spice flowing
140       $not_blank = ("$e" ne '') ? 1 : 0;
141     }
142     else {
143       # not blessed yet failed the 'ne'... this makes 0 sense...
144       # just throw further
145       die $suberror
146     }
147   }
148
149   return $not_blank;
150 }
151
152 sub modver_gt_or_eq ($$) {
153   my ($mod, $ver) = @_;
154
155   croak "Nonsensical module name supplied"
156     if ! defined $mod or ! length $mod;
157
158   croak "Nonsensical minimum version supplied"
159     if ! defined $ver or $ver =~ /[^0-9\.\_]/;
160
161   local $SIG{__WARN__} = sigwarn_silencer( qr/\Qisn't numeric in subroutine entry/ )
162     if SPURIOUS_VERSION_CHECK_WARNINGS;
163
164   croak "$mod does not seem to provide a version (perhaps it never loaded)"
165     unless $mod->VERSION;
166
167   local $@;
168   eval { $mod->VERSION($ver) } ? 1 : 0;
169 }
170
171 sub is_literal_value ($) {
172   (
173     ref $_[0] eq 'SCALAR'
174       or
175     ( ref $_[0] eq 'HASH' and keys %{$_[0]} == 1 and defined $_[0]->{-ident} and ! length ref $_[0]->{-ident} )
176       or
177     ( ref $_[0] eq 'REF' and ref ${$_[0]} eq 'ARRAY' )
178   ) ? 1 : 0;
179 }
180
181 # FIXME XSify - this can be done so much more efficiently
182 sub is_plain_value ($) {
183   no strict 'refs';
184   (
185     # plain scalar
186     (! length ref $_[0])
187       or
188     (
189       blessed $_[0]
190         and
191       # deliberately not using Devel::OverloadInfo - the checks we are
192       # intersted in are much more limited than the fullblown thing, and
193       # this is a relatively hot piece of code
194       (
195         # FIXME - DBI needs fixing to stringify regardless of DBD
196         #
197         # either has stringification which DBI SHOULD prefer out of the box
198         #first { *{$_ . '::(""'}{CODE} } @{ mro::get_linear_isa( ref $_[0] ) }
199         overload::Method($_[0], '""')
200           or
201         # has nummification and fallback is *not* disabled
202         (
203           $_[1] = first { *{"${_}::(0+"}{CODE} } @{ mro::get_linear_isa( ref $_[0] ) }
204             and
205           ( ! defined ${"$_[1]::()"} or ${"$_[1]::()"} )
206         )
207       )
208     )
209   ) ? 1 : 0;
210 }
211
212 {
213   my $list_ctx_ok_stack_marker;
214
215   sub fail_on_internal_wantarray {
216     return if $list_ctx_ok_stack_marker;
217
218     if (! defined wantarray) {
219       croak('fail_on_internal_wantarray() needs a tempvar to save the stack marker guard');
220     }
221
222     my $cf = 1;
223     while ( ( (caller($cf+1))[3] || '' ) =~ / :: (?:
224
225       # these are public API parts that alter behavior on wantarray
226       search | search_related | slice | search_literal
227
228         |
229
230       # these are explicitly prefixed, since we only recognize them as valid
231       # escapes when they come from the guts of CDBICompat
232       CDBICompat .*? :: (?: search_where | retrieve_from_sql | retrieve_all )
233
234     ) $/x ) {
235       $cf++;
236     }
237
238     if (
239       (caller($cf))[0] =~ /^(?:DBIx::Class|DBICx::)/
240     ) {
241       DBIx::Class::Exception->throw( sprintf (
242         "Improper use of %s instance in list context at %s line %d\n\n\tStacktrace starts",
243         refdesc($_[0]), (caller($cf))[1,2]
244       ), 'with_stacktrace');
245     }
246
247     my $mark = [];
248     weaken ( $list_ctx_ok_stack_marker = $mark );
249     $mark;
250   }
251 }
252
253 1;