rajeev rajeev - 1 month ago 12
Perl Question

index is not visible to DBIx::Class

I have this small perl code which is going to add a record to table. but i am confused why is DBIx not able to see the primary key???

$ ./test.pl
DBIx::Class::ResultSource::unique_constraint_columns(): Unknown unique constraint node_id on 'node' at ./test.pl line 80


code:

sub addNode
{
my $node = shift; my $lcNode = lc($node);
my $id = $schema
->resultset('Node')
->find_or_create
(
{ node_name => $lcNode },
{ key => 'node_id' }
);
return $id;
}


table details:

mysql> desc node;
+------------+-----------------------+------+-----+---------+----------------+
| Field | Type | Null | Key | Default | Extra |
+------------+-----------------------+------+-----+---------+----------------+
| node_id | mediumint(5) unsigned | NO | PRI | NULL | auto_increment |
| node_name | varchar(50) | NO | | NULL | |
| node_notes | varchar(1000) | YES | | NULL | |
+------------+-----------------------+------+-----+---------+----------------+
3 rows in set (0.00 sec)


DBIx resultset:

$ cat Node.pm
use utf8;
package Testdb::Schema::Result::Node;

# Created by DBIx::Class::Schema::Loader
# DO NOT MODIFY THE FIRST PART OF THIS FILE

use strict;
use warnings;

use base 'DBIx::Class::Core';
__PACKAGE__->table("node");
__PACKAGE__->add_columns(
"node_id",
{
data_type => "mediumint",
extra => { unsigned => 1 },
is_auto_increment => 1,
is_nullable => 0,
},
"node_name",
{ data_type => "varchar", is_nullable => 0, size => 50 },
"node_notes",
{ data_type => "varchar", is_nullable => 1, size => 1000 },
);
__PACKAGE__->set_primary_key("node_id");


# Created by DBIx::Class::Schema::Loader v0.07045 @ 2017-08-21 22:14:58
# DO NOT MODIFY THIS OR ANYTHING ABOVE! md5sum:bWXf98hpLJgNBU93aaRYkQ


# You can replace this text with custom code or comments, and it will be preserved on regeneration
1;


I am not able to find any ans anywhere. first the names of table and columns were camleCase, which i then changed to underscore, but it just wont run... :(

Answer Source

https://metacpan.org/pod/DBIx::Class::ResultSet#find:

To aid with preparing the correct query for the storage you may supply the key attribute, which is the name of a unique constraint (the unique constraint corresponding to the primary columns is always named primary).

(Emphasis mine.)

In other words, to use the primary key, you need to specify { key => 'primary' }. Any other key attribute is looked up as the name of an additional unique constraint.