From 667e67555058c20bc50ec9d31f895b920dde2c1f Mon Sep 17 00:00:00 2001 From: Jonathan Druart Date: Thu, 14 Mar 2024 14:39:56 +0100 Subject: [PATCH] Bug 36277: Improve algorithmic complexity of batch_add The 2 nested loops are terrible in term of algorithmic complexity. Especially if we are fetching from there. The goal of this patch is to fetch all the limits outside of the loop. If you have 100 libraries, it will remove 100^2 - 1 fetches! Signed-off-by: Martin Renvoize Signed-off-by: Tomas Cohen Arazi Signed-off-by: Katrin Fischer (cherry picked from commit 202628342ab9397e8b15aa5e62c0aaa041d3c8a0) Signed-off-by: Fridolin Somers (cherry picked from commit 372adf555d579c290355ff33f891cd205dc0bfac) Signed-off-by: Lucas Gass --- Koha/REST/V1/TransferLimits.pm | 33 ++++++++++++++++++++------------- 1 file changed, 20 insertions(+), 13 deletions(-) diff --git a/Koha/REST/V1/TransferLimits.pm b/Koha/REST/V1/TransferLimits.pm index 83fa6c568d..cba63776c1 100644 --- a/Koha/REST/V1/TransferLimits.pm +++ b/Koha/REST/V1/TransferLimits.pm @@ -141,32 +141,39 @@ sub batch_add { @to_branches = @library_ids unless $params->{to_library_id}; } + my $dbic_params = Koha::Item::Transfer::Limits->new->attributes_from_api($params); + my %existing_limits = + map { sprintf( "%s:%s:%s:%s", $_->fromBranch, $_->toBranch, $_->itemtype, $_->ccode ) => 1 } + Koha::Item::Transfer::Limits->search($dbic_params)->as_list; + my @results; - foreach my $from ( @from_branches ) { - foreach my $to ( @to_branches ) { - my $limit_params = { %$params }; + foreach my $from (@from_branches) { + foreach my $to (@to_branches) { + my $limit_params = {%$params}; $limit_params->{from_library_id} = $from; - $limit_params->{to_library_id} = $to; + $limit_params->{to_library_id} = $to; next if $to eq $from; - my $transfer_limit = Koha::Item::Transfer::Limit->new_from_api( $limit_params ); - my $exists = Koha::Item::Transfer::Limits->search( $transfer_limit->unblessed )->count; - unless ( $exists ) { - $transfer_limit->store; - push( @results, $transfer_limit->to_api()); - } + my $key = sprintf( + "%s:%s:%s:%s", $limit_params->{from_branch_id} || q{}, + $limit_params->{to_branch_id} || q{}, $limit_params->{item_type} || q{}, + $limit_params->{collection_code} || q{} + ); + next if exists $existing_limits{$key}; + + my $transfer_limit = Koha::Item::Transfer::Limit->new_from_api($limit_params); + $transfer_limit->store; + push( @results, $transfer_limit->to_api() ); } } - my $transfer_limit = Koha::Item::Transfer::Limit->new_from_api( $params ); return $c->render( status => 201, openapi => \@results ); - } - catch { + } catch { $c->unhandled_exception($_); }; } -- 2.39.5