From 4ce2f3055860c1f20ed66f298762ddc92c28fc0c Mon Sep 17 00:00:00 2001 From: Tomas Cohen Arazi Date: Mon, 29 Jul 2024 09:16:56 -0300 Subject: [PATCH] Bug 37510: Make Koha::Object->delete throw Koha::Exception This patch makes Koha::Object->delete wrap DBIC exceptions on FK constraints and throw a Koha::Exception::Object::FKConstraint exception instead. This will allow us better handling it from the callers. To test: 1. Apply the unit tests patch 2. Run: $ ktd --shell k$ prove t/db_dependent/Koha/Object.t => FAIL: A DBIC exception is thrown instead, tests fail 3. Apply this patch 4. Repeat 2 => SUCCESS: Tests pass! 5. Sign off :-D --- Koha/Object.pm | 22 ++++++++++++++++++++-- 1 file changed, 20 insertions(+), 2 deletions(-) diff --git a/Koha/Object.pm b/Koha/Object.pm index a833f30580d..2c5c17b1dd8 100644 --- a/Koha/Object.pm +++ b/Koha/Object.pm @@ -233,11 +233,29 @@ Returns: sub delete { my ($self) = @_; - my $deleted = $self->_result()->delete; + my $deleted; + + try { + $deleted = $self->_result()->delete; + } catch { + if ( ref($_) eq 'DBIx::Class::Exception' ) { + if ( $_->{msg} =~ /Cannot delete or update a parent row\: a foreign key constraint fails/ ) { + if ( $_->{msg} =~ /FOREIGN KEY \(\`(?.*?)\`\)/ ) { + Koha::Exceptions::Object::FKConstraint->throw( + error => 'Broken FK constraint', + broken_fk => $+{column} + ); + } + } + $_->rethrow(); + } + }; + if ( ref $deleted ) { - my $object_class = Koha::Object::_get_object_class( $self->_result->result_class ); + my $object_class = Koha::Object::_get_object_class( $self->_result->result_class ); $deleted = $object_class->_new_from_dbic($deleted); } + return $deleted; } -- 2.45.2