[Bps-public-commit] r18938 - DBIx-SearchBuilder/trunk/SearchBuilder/Handle

ruz at bestpractical.com ruz at bestpractical.com
Wed Mar 25 20:16:37 EDT 2009


Author: ruz
Date: Wed Mar 25 20:16:36 2009
New Revision: 18938

Modified:
   DBIx-SearchBuilder/trunk/SearchBuilder/Handle/Pg.pm

Log:
* Pg can not guaranty order in the following queries:
  SELECT ... FROM (SELECT... ORDER BY ...)
  we use them to build distinct sets with ordering by columns
  in joined tables. We have to try to use group by instead of
  sub-selects.

Modified: DBIx-SearchBuilder/trunk/SearchBuilder/Handle/Pg.pm
==============================================================================
--- DBIx-SearchBuilder/trunk/SearchBuilder/Handle/Pg.pm	(original)
+++ DBIx-SearchBuilder/trunk/SearchBuilder/Handle/Pg.pm	Wed Mar 25 20:16:36 2009
@@ -214,6 +214,7 @@
     }
 }
 
+
 =head2 DistinctQuery STATEMENTREF
 
 takes an incomplete SQL SELECT statement and massages it to return a DISTINCT result set.
@@ -226,26 +227,23 @@
     my $sb = shift;
     my $table = $sb->Table;
 
-    if ($sb->_OrderClause =~ /(?<!main)\./) {
-        # If we are ordering by something not in 'main', we need to GROUP
-        # BY and adjust the ORDER_BY accordingly
-        local $sb->{group_by} = [@{$sb->{group_by} || []}, {FIELD => 'id'}];
-        local $sb->{'order_by'} = [
-            map {
-                ($_->{'ALIAS'}||'') ne "main"
-                ? { %{$_}, FIELD => ((($_->{'ORDER'}||'') =~ /^des/i)?'MAX':'MIN') ."(".$_->{FIELD}.")" }
-                : $_
-            }
-            @{$sb->{'order_by'}}
-        ];
-        my $group = $sb->_GroupClause;
-        my $order = $sb->_OrderClause;
-        $$statementref = "SELECT main.* FROM ( SELECT main.id FROM $$statementref $group $order ) distinctquery, $table main WHERE (main.id = distinctquery.id)";
-    } else {
-        $$statementref = "SELECT DISTINCT main.* FROM $$statementref";
-        $$statementref .= $sb->_GroupClause;
-        $$statementref .= $sb->_OrderClause;
-    }
+    return $self->SUPER::DistinctQuery( $statementref, $sb, @_ )
+        if $sb->_GroupClause || $sb->_OrderClause !~ /(?<!main)\./;
+
+    # If we are ordering by something not in 'main', we need to GROUP
+    # BY and adjust the ORDER_BY accordingly
+    local $sb->{group_by} = [ map {+{FIELD => $_}} $self->Fields($table) ];
+    local $sb->{'order_by'} = [
+        map {
+            ($_->{'ALIAS'}||'') ne "main"
+            ? { %{$_}, FIELD => ((($_->{'ORDER'}||'') =~ /^des/i)?'MAX':'MIN') ."(".$_->{FIELD}.")" }
+            : $_
+        }
+        @{$sb->{'order_by'}}
+    ];
+    my $group = $sb->_GroupClause;
+    my $order = $sb->_OrderClause;
+    $$statementref = "SELECT main.* FROM $$statementref $group $order";
 }
 
 1;



More information about the Bps-public-commit mailing list