75b017b0ffcef48158b14f64441b25b25913d8c7
[dbsrgits/DBIx-Class.git] / lib / DBIx / Class / PK / Auto.pm
1 package DBIx::Class::PK::Auto;
2
3 use base qw/Class::Data::Inheritable/;
4 use strict;
5 use warnings;
6
7 =head1 NAME 
8
9 DBIx::Class::PK::Auto - Automatic Primary Key class
10
11 =head1 SYNOPSIS
12
13 =head1 DESCRIPTION
14
15 This class overrides the insert method to get automatically
16 incremented primary keys.
17
18 You don't want to be using this directly - instead load the appropriate
19 one for your database, e.g. PK::Auto::SQLite
20
21 =head1 METHODS
22
23 =over 4
24
25 =item insert
26
27 Overrides insert so that it will get the value of autoincremented
28 primary keys.
29
30 =cut
31
32 sub insert {
33   my ($self, @rest) = @_;
34   my $ret = $self->NEXT::ACTUAL::insert(@rest);
35   my ($pri, $too_many) =
36     (grep { $self->_primaries->{$_}{'auto_increment'} }
37        keys %{ $self->_primaries })
38     || (keys %{ $self->_primaries });
39   $self->throw( "More than one possible key found for auto-inc on ".ref $self )
40     if $too_many;
41   unless (defined $self->get_column($pri)) {
42     $self->throw( "Can't auto-inc for $pri on ".ref $self.": no _last_insert_id method" )
43       unless $self->can('last_insert_id');
44     my $id = $self->last_insert_id;
45     $self->throw( "Can't get last insert id" ) unless $id;
46     $self->store_column($pri => $id);
47   }
48   return $ret;
49 }
50
51 =item sequence
52
53 Manually define the correct sequence for your table, to avoid the overhead
54 associated with looking up the sequence automatically.
55
56 =cut
57
58 __PACKAGE__->mk_classdata('sequence');
59
60 1;
61
62 =back
63
64 =head1 AUTHORS
65
66 Matt S. Trout <mst@shadowcatsystems.co.uk>
67
68 =head1 LICENSE
69
70 You may distribute this code under the same terms as Perl itself.
71
72 =cut
73