Subject: | Cascading deletes and prefetch |
I have a problem with cascading deletes and multi-step prefetches. See
the test case. The relationships are:
Table1 has_many Table2
Table2 belongs_to Table3 (with cascade_delete => 1)
I get the following error when I try to delete a row from Table1 that
has prefetched rows from Table2 and Table3:
Can't call method "delete" on an undefined value at
lib/DBIx/Class/ResultSet.pm line 1583.
The test case also contains two queries that illustrate the problem. The
second query returns (undef, undef, undef, undef) instead of an empty list.
Subject: | test.pl |
#!/usr/bin/perl
use strict;
use lib qw(lib);
=head1
CREATE TABLE table1 (
id INTEGER PRIMARY KEY
);
CREATE TABLE table2 (
id INTEGER PRIMARY KEY,
table1 INTEGER,
table3 INTEGER
);
CREATE TABLE table3 (
id INTEGER
);
=cut
package My::Table1;
use base qw(DBIx::Class);
__PACKAGE__->load_components(qw(Core));
__PACKAGE__->table('table1');
__PACKAGE__->add_columns(qw(id));
__PACKAGE__->set_primary_key('id');
__PACKAGE__->has_many(table2 => 'My::Table2');
package My::Table3;
use base qw(DBIx::Class);
__PACKAGE__->load_components(qw(Core));
__PACKAGE__->table('table3');
__PACKAGE__->add_columns(qw(id));
__PACKAGE__->set_primary_key('id');
package My::Table2;
use base qw(DBIx::Class);
__PACKAGE__->load_components(qw(Core));
__PACKAGE__->table('table2');
__PACKAGE__->add_columns(qw(id table1 table3));
__PACKAGE__->set_primary_key('id');
__PACKAGE__->belongs_to(table3 => 'My::Table3', undef, { cascade_delete => 1 });
package My::Schema;
use base qw(DBIx::Class::Schema);
__PACKAGE__->register_class(Table1 => 'My::Table1');
__PACKAGE__->register_class(Table2 => 'My::Table2');
__PACKAGE__->register_class(Table3 => 'My::Table3');
package main;
my $schema = My::Schema->connection(
'dsn', 'user', 'pass'
);
$schema->resultset('Table1')->delete();
$schema->resultset('Table2')->delete();
$schema->resultset('Table1')->create({ id => 1 });
$schema->resultset('Table2')->create({ id => $_, table1 => 1 }) for 1..4;
my @rows;
# This query works as expected
@rows = $schema->
resultset('Table1')->
find(1, { prefetch => 'table2' })->
related_resultset('table2')->
related_resultset('table3')->
all();
print join('-', @rows), "\n";
# This query returns a list of undef values instead of an empty list
@rows = $schema->
resultset('Table1')->
find(1, { prefetch => { table2 => 'table3' } })->
related_resultset('table2')->
related_resultset('table3')->
all();
print join('-', @rows), "\n";
# This delete fails
$schema->
resultset('Table1')->
find(1, { prefetch => { table2 => 'table3' } })->
delete();