Fix "current rs is always first in from" brainfart introduced in 893403c81
[dbsrgits/DBIx-Class.git] / t / prefetch / via_search_related.t
index fbaeeef..e95d960 100644 (file)
@@ -9,6 +9,10 @@ use DBICTest;
 
 my $schema = DBICTest->init_schema();
 
+my $queries;
+my $debugcb = sub { $queries++; };
+my $orig_debug = $schema->storage->debug;
+
 lives_ok ( sub {
   my $no_prefetch = $schema->resultset('Track')->search_related(cd =>
     {
@@ -37,7 +41,6 @@ lives_ok ( sub {
 
 }, 'search_related prefetch with order_by works');
 
-TODO: { local $TODO = 'Unqualified columns in where clauses can not be fixed without an SQLA rewrite' if SQL::Abstract->VERSION < 2;
 lives_ok ( sub {
   my $no_prefetch = $schema->resultset('Track')->search_related(cd =>
     {
@@ -65,8 +68,6 @@ lives_ok ( sub {
   is($use_prefetch->count, $no_prefetch->count, 'counts with and without prefetch match');
 
 }, 'search_related prefetch with condition referencing unqualified column of a joined table works');
-}
-
 
 lives_ok (sub {
     my $rs = $schema->resultset("Artwork")->search(undef, {distinct => 1})
@@ -127,13 +128,47 @@ lives_ok (sub {
     is($rs->all, 1, 'distinct with prefetch (objects)');
     is($rs->count, 1, 'distinct with prefetch (count)');
 
-  TODO: {
-    local $TODO = "This makes another 2 trips to the database, it can't be right";
+    $queries = 0;
+    $schema->storage->debugcb ($debugcb);
+    $schema->storage->debug (1);
+
     # artist -> 2 cds -> 2 genres -> 2 cds for each genre + distinct = 2
     is($rs->search_related('cds')->all, 2, 'prefetched distinct with prefetch (objects)');
     is($rs->search_related('cds')->count, 2, 'prefetched distinct with prefetch (count)');
-  }
 
+    {
+      local $TODO = "This makes another 2 trips to the database, it can't be right";
+      is ($queries, 0, 'No extra queries fired (prefetch survives search_related)');
+    }
+
+    $schema->storage->debugcb (undef);
+    $schema->storage->debug ($orig_debug);
 }, 'distinct generally works with prefetch on deep search_related chains');
 
+# pathological "user knows what they're doing" case
+# lifted from production somewhere
+{
+  $schema->resultset('CD')
+   ->search({ cdid => [1,2] })
+    ->search_related('tracks', { position => [3,1] })
+     ->delete_all;
+
+  my $rs = $schema->resultset('CD')->search_related('tracks', {}, {
+    group_by => 'me.title',
+    columns => { title => 'me.title', max_trk => \ 'MAX(tracks.position)' },
+  });
+
+  is_deeply(
+    $rs->all_hri,
+    [
+      { title => "Caterwaulin' Blues", max_trk => 3 },
+      { title => "Come Be Depressed With Us", max_trk => 3 },
+      { title => "Forkful of bees", max_trk => 1 },
+      { title => "Generic Manufactured Singles", max_trk => 3 },
+      { title => "Spoonful of bees", max_trk => 1 },
+    ],
+    'Expected nonsense',
+  );
+}
+
 done_testing;