From 48a068b92fc345a36ef4bf842199a1af27ad60c6 Mon Sep 17 00:00:00 2001 From: Nathan Wallach Date: Thu, 1 Dec 2022 23:47:27 +0200 Subject: [PATCH] Modify addUserMultipleProblems of lib/WeBWorK/DB.pm to use eval { $self->{problem_user}->insert_records([@problemList]); }; so that a single DB call makes all the inserts. Test that no records for this user and set exist before making that call. --- lib/WeBWorK/DB.pm | 39 ++++++++++++++------------------------- 1 file changed, 14 insertions(+), 25 deletions(-) diff --git a/lib/WeBWorK/DB.pm b/lib/WeBWorK/DB.pm index f0908a277a..2414479671 100644 --- a/lib/WeBWorK/DB.pm +++ b/lib/WeBWorK/DB.pm @@ -2057,8 +2057,10 @@ sub addUserMultipleProblems { my ($self, @problemList) = @_; my $firstUserProblem = $problemList[0]; + my $user_id = $firstUserProblem->user_id; + my $set_id = $firstUserProblem->set_id; - my ($nv_set_id, $versionNum) = grok_vsetID($firstUserProblem->set_id); + my ($nv_set_id, $versionNum) = grok_vsetID($set_id); croak "addUserMultipleProblems does not support versioned sets" if defined($versionNum); @@ -2068,32 +2070,19 @@ sub addUserMultipleProblems { my @tmp = ($firstUserProblem); $self->checkArgs(\@tmp, qw/VREC:problem_user/); - # Just needed once - croak 'addMultipleUserProblems: user set ', $firstUserProblem->set_id, ' for user ', $firstUserProblem->user_id, - ' not found' - unless $self->{set_user}->exists($firstUserProblem->user_id, $firstUserProblem->set_id); + croak "addMultipleUserProblems: user set $set_id for user $user_id not found" + unless $self->{set_user}->exists($user_id, $set_id); - my @sawRecordExists; - my @otherErrors; + # Test whether there are already problem records for this user in this set, as in that case + # inserting multiple records at once would trigger an error. + my $where = [ user_id_eq_set_id_eq => $user_id, $set_id ]; - for my $userProblem (@problemList) { - eval { $self->{problem_user}->add($userProblem); }; - if (my $ex = caught WeBWorK::DB::Ex::RecordExists) { - push(@sawRecordExists, $userProblem->problem_id); - } elsif ($@) { - push(@otherErrors, "for problem_id $userProblem->problem_id) saw error: $@\n"); - } - } - if (@sawRecordExists || @otherErrors) { - croak join( - '', - @sawRecordExists - ? join('', - 'addUserMultipleProblems: the following user problems existed before ', - join(', ', @sawRecordExists), "\n") - : '', - @otherErrors - ); + croak "addMultipleUserProblems cannot be run as set $set_id already contains some problems for user $user_id" + if $self->{problem_user}->count_where($where); + + eval { $self->{problem_user}->insert_records([@problemList]); }; + if ($@) { + croak "addUserMultipleProblems: $@"; } }