I hate you all.
[dbsrgits/DBIx-Class.git] / lib / DBIx / Class / PK / Auto.pm
CommitLineData
b8e1e21f 1package DBIx::Class::PK::Auto;
2
773e3015 3#use base qw/DBIx::Class::PK/;
4use base qw/DBIx::Class/;
b8e1e21f 5use strict;
6use warnings;
7
75d07914 8=head1 NAME
34d52be2 9
eb49d4e3 10DBIx::Class::PK::Auto - Automatic primary key class
34d52be2 11
12=head1 SYNOPSIS
13
77254782 14__PACKAGE__->load_components(qw/PK::Auto Core/);
15__PACKAGE__->set_primary_key('id');
6718c5f0 16
34d52be2 17=head1 DESCRIPTION
18
eb49d4e3 19This class overrides the insert method to get automatically incremented primary
20keys.
34d52be2 21
77254782 22 __PACKAGE__->load_components(qw/PK::Auto Core/);
f4ccda68 23
e2441ae6 24Note that C<PK::Auto> is specified as the left of the Core component.
25See L<DBIx::Class::Manual::Component> for details of component interactions.
7624b19f 26
c8f4b52b 27=head1 LOGIC
28
eb49d4e3 29C<PK::Auto> does this by letting the database assign the primary key field and
30fetching the assigned value afterwards.
c8f4b52b 31
34d52be2 32=head1 METHODS
33
130c6439 34=head2 insert
34d52be2 35
eb49d4e3 36Overrides C<insert> so that it will get the value of autoincremented primary
37keys.
34d52be2 38
39=cut
40
b8e1e21f 41sub insert {
42 my ($self, @rest) = @_;
147dd158 43 my $ret = $self->next::method(@rest);
0675cd04 44
260129d8 45 my ($pri, $too_many) = grep { !defined $self->get_column($_) ||
46 ref($self->get_column($_)) eq 'SCALAR'} $self->primary_columns;
ca48cd7d 47 return $ret unless defined $pri; # if all primaries are already populated, skip auto-inc
701da8c4 48 $self->throw_exception( "More than one possible key found for auto-inc on ".ref $self )
ca48cd7d 49 if defined $too_many;
50
fefe2816 51 my $storage = $self->result_source->storage;
1707dd5a 52 $self->throw_exception( "Missing primary key but Storage doesn't support last_insert_id" )
53 unless $storage->can('last_insert_id');
fefe2816 54 my $id = $storage->last_insert_id($self->result_source,$pri);
ca48cd7d 55 $self->throw_exception( "Can't get last insert id" ) unless $id;
56 $self->store_column($pri => $id);
57
b8e1e21f 58 return $ret;
59}
60
130c6439 61=head2 sequence
97cc0025 62
63Manually define the correct sequence for your table, to avoid the overhead
64associated with looking up the sequence automatically.
65
66=cut
67
ecb6488f 68sub sequence {
69 my ($self,$seq) = @_;
70 foreach my $pri ($self->primary_columns) {
71 $self->column_info($pri)->{sequence} = $seq;
72 }
73}
97cc0025 74
b8e1e21f 751;
34d52be2 76
34d52be2 77=head1 AUTHORS
78
daec44b8 79Matt S. Trout <mst@shadowcatsystems.co.uk>
34d52be2 80
81=head1 LICENSE
82
83You may distribute this code under the same terms as Perl itself.
84
85=cut