[Dbix-class] patch for ResultSet::find_or_new
Matt S Trout
dbix-class at trout.me.uk
Sun Jan 13 18:20:51 GMT 2008
On Sun, Jan 13, 2008 at 10:41:43AM +0100, Patrick Weemeeuw wrote:
> There is a small bug in find_or_new: when the find part
> fails, it calls new_result with the hash containing the
> values that were used for the search. It should use no
> values at all instead.
This isn't a bug. If that's the behaviour you want, do
my $o = $rs->find({ id => $id }) || $rs->new({});
> Example buggy case: $o = $...->find_or_new( { id => $id } )
> with id a not null primary key. When $id is undefined, there
> is obviously no row in the DB, and a new result object is
> returned. However, the object returned contains the column
> id => NULL, which (1) is invalid for this kind of object,
> and (2) prevents in some backends (e.g. Pg) that the
> sequence is used to generate a unique id.
So don't pass id if it isn't a valid value. Passing undef there is a bug
in your code, not in DBIx::Class.
The usual use of find_or_new is to pass a unique key plus additional
attributes to be used for object creation (which are ignored in the find()
by specifying the key attr as well). Consider for example
my $stats = $schema->resultset('PageViews')->find_or_new(
{ page => $page, views => 0 },
{ key => 'page' }
);
$stats->views($stats->views + 1);
$stats->insert_or_update;
which would be entirely broken were your patch applied.
Also for future reference, please ensure you include a test that fails without
your patch applied and succeeds with it; any patch that doesn't come with
tests is not going to be accepted - I'm aware some things can be difficult
to test but DBIC is used by people to interact with their production
databases so the bar has to be set high.
--
Matt S Trout Need help with your Catalyst or DBIx::Class project?
Technical Director http://www.shadowcat.co.uk/catalyst/
Shadowcat Systems Ltd. Want a managed development or deployment platform?
http://chainsawblues.vox.com/ http://www.shadowcat.co.uk/servers/
More information about the DBIx-Class
mailing list