Fix and guard against erroneous use of list context in internal DBIC code
[dbsrgits/DBIx-Class.git] / lib / DBIx / Class / _Util.pm
index d4760bc..e6cf2a9 100644 (file)
@@ -7,9 +7,10 @@ use strict;
 use constant SPURIOUS_VERSION_CHECK_WARNINGS => ($] < 5.010 ? 1 : 0);
 
 use Carp;
+use Scalar::Util qw(refaddr weaken);
 
 use base 'Exporter';
-our @EXPORT_OK = qw(modver_gt_or_eq);
+our @EXPORT_OK = qw(modver_gt_or_eq fail_on_internal_wantarray);
 
 sub modver_gt_or_eq {
   my ($mod, $ver) = @_;
@@ -31,4 +32,47 @@ sub modver_gt_or_eq {
   eval { $mod->VERSION($ver) } ? 1 : 0;
 }
 
+{
+  my $list_ctx_ok_stack_marker;
+
+  sub fail_on_internal_wantarray {
+    return if $list_ctx_ok_stack_marker;
+
+    if (! defined wantarray) {
+      croak('fail_on_internal_wantarray() needs a tempvar to save the stack marker guard');
+    }
+
+    my $cf = 1;
+    while ( ( (caller($cf+1))[3] || '' ) =~ / :: (?:
+
+      # these are public API parts that alter behavior on wantarray
+      search | search_related | slice | search_literal
+
+        |
+
+      # these are explicitly prefixed, since we only recognize them as valid
+      # escapes when they come from the guts of CDBICompat
+      CDBICompat .*? :: (?: search_where | retrieve_from_sql | retrieve_all )
+
+    ) $/x ) {
+      $cf++;
+    }
+
+    if (
+      (caller($cf))[0] =~ /^(?:DBIx::Class|DBICx::)/
+    ) {
+      my $obj = shift;
+
+      DBIx::Class::Exception->throw( sprintf (
+        "Improper use of %s(0x%x) instance in list context at %s line %d\n\n\tStacktrace starts",
+        ref($obj), refaddr($obj), (caller($cf))[1,2]
+      ), 'with_stacktrace');
+    }
+
+    my $mark = [];
+    weaken ( $list_ctx_ok_stack_marker = $mark );
+    $mark;
+  }
+}
+
 1;