Extra test and count fixes for prefetch + distinct
[dbsrgits/DBIx-Class-Historic.git] / lib / DBIx / Class / ResultSet.pm
index f6cc3ba..05e4c00 100644 (file)
@@ -1171,6 +1171,14 @@ sub _count_subq {
 
   # if needed force a group_by and the same set of columns (most databases require this)
   if ($add_group_by) {
+
+    # if we prefetch, we group_by primary keys only as this is what we would get out of the rs via ->next/->all
+    # simply deleting group_by suffices, as the code below will re-fill it
+    # Note: we check $attrs, as $sub_attrs has collapse deleted
+    if (ref $attrs->{collapse} and keys %{$attrs->{collapse}} ) { 
+      delete $sub_attrs->{group_by};
+    }
+
     $sub_attrs->{columns} = $sub_attrs->{group_by} ||= [ map { "$attrs->{alias}.$_" } ($self->result_source->primary_columns) ];
   }
 
@@ -2608,8 +2616,6 @@ sub _resolved_attrs {
 
   }
 
-  $attrs->{group_by} ||= [ grep { !ref($_) || (ref($_) ne 'HASH') } @{$attrs->{select}} ]
-    if delete $attrs->{distinct};
   if ( $attrs->{order_by} ) {
     $attrs->{order_by} = (
       ref( $attrs->{order_by} ) eq 'ARRAY'
@@ -2636,6 +2642,11 @@ sub _resolved_attrs {
     }
     push( @{ $attrs->{order_by} }, @pre_order );
   }
+
+  if (delete $attrs->{distinct}) {
+    $attrs->{group_by} ||= [ grep { !ref($_) || (ref($_) ne 'HASH') } @{$attrs->{select}} ];
+  }
+
   $attrs->{collapse} = $collapse;
 
   if ( $attrs->{page} and not defined $attrs->{offset} ) {