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