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

Signed-off-by: David Nind <david@davidnind.com>
Signed-off-by: Pedro Amorim <pedro.amorim@ptfs-europe.com>
Signed-off-by: Katrin Fischer <katrin.fischer@bsz-bw.de>
This commit is contained in:
Tomas Cohen Arazi 2024-07-29 09:16:56 -03:00 committed by Katrin Fischer
parent 30a5baa706
commit 923dc5e078
No known key found for this signature in database
GPG Key ID: 0EF6E2C03357A834
2 changed files with 28 additions and 2 deletions

View File

@ -33,6 +33,11 @@ use Exception::Class (
description => "Foreign key constraint broken",
fields => ['broken_fk', 'value'],
},
'Koha::Exceptions::Object::FKConstraintDeletion' => {
isa => 'Koha::Exceptions::Object',
description => "Foreign key constraint broken on deleting resource",
fields => [ 'column', 'fk', 'table', 'constraint' ],
},
'Koha::Exceptions::Object::MethodNotFound' => {
isa => 'Koha::Exceptions::Object',
description => "Invalid method",

View File

@ -233,11 +233,32 @@ 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 \(\`(?<database>.*?)\`\.\`(?<table>.*?)\`, CONSTRAINT \`(?<constraint>.*?)\` FOREIGN KEY \(\`(?<fk>.*?)\`\) REFERENCES \`.*\` \(\`(?<column>.*?)\`\)/
)
{
Koha::Exceptions::Object::FKConstraintDeletion->throw(
column => $+{column},
constraint => $+{constraint},
fk => $+{fk},
table => $+{table},
);
}
$_->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;
}