Patches from Andreas Hartmeier applied to PK::Auto
[dbsrgits/DBIx-Class-Historic.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 =head1 DESCRIPTION
15
16 This class overrides the insert method to get automatically
17 incremented primary keys.
18
19 You don't want to be using this directly - instead load the appropriate
20 one for your database, e.g. PK::Auto::SQLite
21
22 =head1 LOGIC
23
24 PK::Auto does this by letting the database assign the primary key field
25 and fetching the assigned value afterwards.
26
27 =head1 METHODS
28
29 =head2 insert
30
31 Overrides insert so that it will get the value of autoincremented
32 primary keys.
33
34 =cut
35
36 sub insert {
37   my ($self, @rest) = @_;
38   my $ret = $self->next::method(@rest);
39
40   # if all primaries are already populated, skip auto-inc
41   my $populated = 0;
42   map { $populated++ if defined $self->get_column($_) } $self->primary_columns;
43   return $ret if ( $populated == scalar $self->primary_columns );
44
45   my ($pri, $too_many) =
46     (grep { $self->column_info($_)->{'auto_increment'} }
47        $self->primary_columns)
48     || $self->primary_columns;
49   $self->throw( "More than one possible key found for auto-inc on ".ref $self )
50     if $too_many;
51   unless (defined $self->get_column($pri)) {
52     $self->throw( "Can't auto-inc for $pri on ".ref $self.": no _last_insert_id method" )
53       unless $self->can('last_insert_id');
54     my $id = $self->last_insert_id;
55     $self->throw( "Can't get last insert id" ) unless $id;
56     $self->store_column($pri => $id);
57   }
58   return $ret;
59 }
60
61 =head2 sequence
62
63 Manually define the correct sequence for your table, to avoid the overhead
64 associated with looking up the sequence automatically.
65
66 =cut
67
68 __PACKAGE__->mk_classdata('sequence');
69
70 1;
71
72 =head1 AUTHORS
73
74 Matt S. Trout <mst@shadowcatsystems.co.uk>
75
76 =head1 LICENSE
77
78 You may distribute this code under the same terms as Perl itself.
79
80 =cut
81