On 05/13/2014 03:07 PM, Alex Vandiver wrote:
> [snip] As such, the attached patch (which has only been briefly tested) may 
> suffice.

Updated version, with one more close paren, attached.
 - Alex
>From 7c229f0164f3fc45281a2195338eff501b3b7d4e Mon Sep 17 00:00:00 2001
From: Alex Vandiver <[email protected]>
Date: Tue, 13 May 2014 15:04:30 -0400
Subject: [PATCH] We can omit the (heavy on Pg) ->Fields call on 9.1 and above

---
 lib/DBIx/SearchBuilder/Handle/Pg.pm | 12 +++++++++---
 1 file changed, 9 insertions(+), 3 deletions(-)

diff --git a/lib/DBIx/SearchBuilder/Handle/Pg.pm b/lib/DBIx/SearchBuilder/Handle/Pg.pm
index 14be2bf..a170e8c 100755
--- a/lib/DBIx/SearchBuilder/Handle/Pg.pm
+++ b/lib/DBIx/SearchBuilder/Handle/Pg.pm
@@ -235,9 +235,15 @@ sub DistinctQuery {
     # It's hard to show with tests. Pg's optimizer can choose execution
     # plan not guaranting order
 
-    # So if we are ordering by something that is not in 'main', the we GROUP
-    # BY all columns and adjust the ORDER_BY accordingly
-    local $sb->{group_by} = [ map {+{FIELD => $_}} $self->Fields($table) ];
+    my $groups;
+    if ($self->DatabaseVersion =~ /^(\d+)\.(\d+)/ and ($1 > 9 or ($1 == 9 and $2 >= 1))) {
+        # Pg 9.1 supports "SELECT main.foo ... GROUP BY main.id" if id is the primary key
+        $groups = [ {FIELD => "id"} ];
+    } else {
+        # For earlier versions, we have to list out all of the columns
+        $groups = [ map {+{FIELD => $_}} $self->Fields($table) ];
+    }
+    local $sb->{group_by} = $groups;
     local $sb->{'order_by'} = [
         map {
             ($_->{'ALIAS'}||'') ne "main"
-- 
1.9.3

-- 
RT Training - Dallas May 20-21
http://bestpractical.com/training

Reply via email to