PK::Auto doc patch from dwc
[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
34d52be2 8=head1 NAME
9
10DBIx::Class::PK::Auto - Automatic Primary Key class
11
12=head1 SYNOPSIS
13
6718c5f0 14 # In your table classes (replace PK::Auto::SQLite with your
15 # database)
16 __PACKAGE__->load_components(qw/PK::Auto::SQLite Core/);
17 __PACKAGE__->set_primary_key('id');
18
34d52be2 19=head1 DESCRIPTION
20
21This class overrides the insert method to get automatically
22incremented primary keys.
23
6718c5f0 24You don't want to be using this directly - instead load the
25appropriate one for your database, e.g. C<PK::Auto::SQLite>, before
26C<Core>.
7624b19f 27
c8f4b52b 28=head1 LOGIC
29
6718c5f0 30PK::Auto does this by letting the database assign the primary key
31field and fetching the assigned value afterwards.
c8f4b52b 32
34d52be2 33=head1 METHODS
34
130c6439 35=head2 insert
34d52be2 36
37Overrides insert so that it will get the value of autoincremented
38primary keys.
39
40=cut
41
b8e1e21f 42sub insert {
43 my ($self, @rest) = @_;
147dd158 44 my $ret = $self->next::method(@rest);
0675cd04 45
46 # if all primaries are already populated, skip auto-inc
47 my $populated = 0;
9a15732e 48 map { $populated++ if defined $self->get_column($_) } $self->primary_columns;
103647d5 49 return $ret if ( $populated == scalar $self->primary_columns );
0675cd04 50
b8e1e21f 51 my ($pri, $too_many) =
103647d5 52 (grep { $self->column_info($_)->{'auto_increment'} }
53 $self->primary_columns)
54 || $self->primary_columns;
78bab9ca 55 $self->throw( "More than one possible key found for auto-inc on ".ref $self )
b8e1e21f 56 if $too_many;
c1d23573 57 unless (defined $self->get_column($pri)) {
78bab9ca 58 $self->throw( "Can't auto-inc for $pri on ".ref $self.": no _last_insert_id method" )
126042ee 59 unless $self->can('last_insert_id');
60 my $id = $self->last_insert_id;
78bab9ca 61 $self->throw( "Can't get last insert id" ) unless $id;
b8e1e21f 62 $self->store_column($pri => $id);
63 }
64 return $ret;
65}
66
130c6439 67=head2 sequence
97cc0025 68
69Manually define the correct sequence for your table, to avoid the overhead
70associated with looking up the sequence automatically.
71
72=cut
73
74__PACKAGE__->mk_classdata('sequence');
75
b8e1e21f 761;
34d52be2 77
34d52be2 78=head1 AUTHORS
79
daec44b8 80Matt S. Trout <mst@shadowcatsystems.co.uk>
34d52be2 81
82=head1 LICENSE
83
84You may distribute this code under the same terms as Perl itself.
85
86=cut
87