[Dbix-class] How you unique do I have to make this constraint? (looks like DBIx::Class bug)

Chisel Wright chisel at herlpacker.co.uk
Sun Dec 28 11:27:43 GMT 2008


On Sun, Dec 28, 2008 at 12:00:32PM +0100, Matija Grabnar wrote:

# the column we're interested in
>  user          int not null primary key,

# where it's marked at the primary key in DBIC
> __PACKAGE__->set_primary_key("user");
> #__PACKAGE__->add_unique_constraint("user_i", ["user"]);
> __PACKAGE__->belongs_to(
>  "user",
>  "FeedMaker::Model::FeedMakerDB::User",
>  { id => "user" },
> );
>
> Without the code I show commented above, the code below fails with  
> "unknown unique constraint"
>     $prog  = $schema->resultset('InProgress')->find_or_create
>      ({
>        user          => $sub->user->id,
>        lock_count    => \$lock_inc,
>       },{
> #        key => 'user_i'
>          key => 'user'
>      });
>
> I would have thought that making "user" a primary key would have been  
> enough to mark it as unique.
> Is that being masked by it's being a foreign key? Or do I really have to  
> declare a primary key as unique
> to have it recognized by find_or_create?

I would expect find_or_create to use the same criteria for "uniqueness"
as find():

   If the "key" is specified as "primary", it searches only on the
   primary key.

  If no "key" is specified, it searches on all unique constraints
  defined on the source, including the primary key.

As user is your primary key, you should be able to:

  ->find(
    { user => $user_id_to_look_for },
	{ key  => 'primary' }
  );

Or in your case:

  ->find_or_create(
    { user => $cub->user->id, lock_count => \$lock_inc },
	{ key  => 'primary' }
  );

It's worth (re)reading the find() docs in DBIx::Class::ResultSet; I know
I made assumptions and incorrect guesses about the behaviour of find()
a while back that caused me some head-scratching.

Chisel
-- 
Chisel Wright
e: chisel at herlpacker.co.uk
w: http://www.herlpacker.co.uk/

  Pointy corners are the future man. Web 3.0.



More information about the DBIx-Class mailing list