From 0866ec5fc8b1569c42926b2d8c2e0768dd90bade Mon Sep 17 00:00:00 2001
From: Jonathan Druart <jonathan.druart@bugs.koha-community.org>
Date: Tue, 4 Aug 2020 12:21:26 +0200
Subject: [PATCH] Bug 26132: Don't prefetch if not needed

We only need to prefetch items if CircControl is set to ItemHomeLibrary
---
 C4/Circulation.pm | 17 +++++++++++------
 1 file changed, 11 insertions(+), 6 deletions(-)

diff --git a/C4/Circulation.pm b/C4/Circulation.pm
index c95be4bf89..3b46264c57 100644
--- a/C4/Circulation.pm
+++ b/C4/Circulation.pm
@@ -433,14 +433,17 @@ sub TooMany {
     # rule
     if (defined($maxissueqty_rule) and $maxissueqty_rule->rule_value ne "") {
 
-        my $checkouts = $patron->checkouts->search( {}, { prefetch => 'item' } );
+        my $checkouts;
         if ( $maxissueqty_rule->branchcode ) {
             if ( C4::Context->preference('CircControl') eq 'PickupLibrary' ) {
-                $checkouts = $checkouts->search({ 'me.branchcode' => $maxissueqty_rule->branchcode });
+                $checkouts = $patron->checkouts->search(
+                    { 'me.branchcode' => $maxissueqty_rule->branchcode } );
             } elsif (C4::Context->preference('CircControl') eq 'PatronLibrary') {
                 ; # if branch is the patron's home branch, then count all loans by patron
             } else {
-                $checkouts = $checkouts->search({ 'item.homebranch' => $maxissueqty_rule->branchcode });
+                $checkouts = $patron->checkouts->search(
+                    { 'item.homebranch' => $maxissueqty_rule->branchcode },
+                    { prefetch          => 'item' } );
             }
         }
         my $sum_checkouts;
@@ -517,13 +520,15 @@ sub TooMany {
     # Now count total loans against the limit for the branch
     my $branch_borrower_circ_rule = GetBranchBorrowerCircRule($branch, $cat_borrower);
     if (defined($branch_borrower_circ_rule->{patron_maxissueqty}) and $branch_borrower_circ_rule->{patron_maxissueqty} ne '') {
-        my $checkouts = $patron->checkouts->search({}, { prefetch => 'item' });
+        my $checkouts;
         if ( C4::Context->preference('CircControl') eq 'PickupLibrary' ) {
-            $checkouts = $checkouts->search({ 'me.branchcode' => $branch });
+            $checkouts = $patron->checkouts->search(
+                { 'me.branchcode' => $branch} );
         } elsif (C4::Context->preference('CircControl') eq 'PatronLibrary') {
             ; # if branch is the patron's home branch, then count all loans by patron
         } else {
-            $checkouts = $checkouts->search({ 'item.homebranch' => $branch });
+            $checkouts = $patron->checkouts->search(
+                { 'item.homebranch' => $branch} );
         }
 
         my $checkout_count = $checkouts->count;
-- 
2.20.1