UNIQUEを設定したフィールドを使って検索する

UNIQUEフィールドを持つテーブルをつくる。

CREATE TABLE table2(
    c1 integer CONSTRAINT c1_unique UNIQUE
);
INSERT INTO table2 VALUES(1),(2),(3),(4),(5);
% psql -f testdb2.sql -d testdb

1つのテーブルについて複数のUNIQUE制約を設定することができるため、どのUNIQUE制約を使うのかを名前で指定する必要がある。

package TestDB::Schema;
use base qw/DBIx::Class::Schema::Loader/;

__PACKAGE__->loader_options(
    relationships => 1,
);
1;

package main;

my $db_schema = TestDB::Schema->connect("dbi:Pg:dbname=testdb","","",undef);

$row = $db_schema->resultset('Table2')->find(4, {key => 'c1_unique'});
print $row->c1, "\n";
% perl select.pl
DBIx::Class::Schema::connect(): table2 has no primary key at select2.pl line 11
4