24f88107439d7767ee0453541eb571a4dedc5f6a
[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 leftmost argument.
25
26 =head1 LOGIC
27
28 C<PK::Auto> does this by letting the database assign the primary key field and
29 fetching the assigned value afterwards.
30
31 =head1 METHODS
32
33 =head2 insert
34
35 Overrides C<insert> so that it will get the value of autoincremented primary
36 keys.
37
38 =cut
39
40 sub insert {
41   my ($self, @rest) = @_;
42   my $ret = $self->next::method(@rest);
43
44   my ($pri, $too_many) = grep { !defined $self->get_column($_) } $self->primary_columns;
45   return $ret unless defined $pri; # if all primaries are already populated, skip auto-inc
46   $self->throw_exception( "More than one possible key found for auto-inc on ".ref $self )
47     if defined $too_many;
48
49   my $storage = $self->result_source->storage;
50   $self->throw_exception( "Missing primary key but Storage doesn't support last_insert_id" ) unless $storage->can('last_insert_id');
51   my $id = $storage->last_insert_id($self->result_source,$pri);
52   $self->throw_exception( "Can't get last insert id" ) unless $id;
53   $self->store_column($pri => $id);
54
55   return $ret;
56 }
57
58 =head2 sequence
59
60 Manually define the correct sequence for your table, to avoid the overhead
61 associated with looking up the sequence automatically.
62
63 =cut
64
65 sub sequence {
66     my ($self,$seq) = @_;
67     foreach my $pri ($self->primary_columns) {
68         $self->column_info($pri)->{sequence} = $seq;
69     }
70 }
71
72 1;
73
74 =head1 AUTHORS
75
76 Matt S. Trout <mst@shadowcatsystems.co.uk>
77
78 =head1 LICENSE
79
80 You may distribute this code under the same terms as Perl itself.
81
82 =cut