Added has_column and column_info methods
[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
36   # if all primaries are already populated, skip auto-inc
37   my $populated = 0;
38   map { $populated++ if $self->$_ } $self->primary_columns;
39   return $ret if ( $populated == scalar $self->primary_columns );
40
41   my ($pri, $too_many) =
42     (grep { $self->column_info($_)->{'auto_increment'} }
43        $self->primary_columns)
44     || $self->primary_columns;
45   $self->throw( "More than one possible key found for auto-inc on ".ref $self )
46     if $too_many;
47   unless (defined $self->get_column($pri)) {
48     $self->throw( "Can't auto-inc for $pri on ".ref $self.": no _last_insert_id method" )
49       unless $self->can('last_insert_id');
50     my $id = $self->last_insert_id;
51     $self->throw( "Can't get last insert id" ) unless $id;
52     $self->store_column($pri => $id);
53   }
54   return $ret;
55 }
56
57 =item sequence
58
59 Manually define the correct sequence for your table, to avoid the overhead
60 associated with looking up the sequence automatically.
61
62 =cut
63
64 __PACKAGE__->mk_classdata('sequence');
65
66 1;
67
68 =back
69
70 =head1 AUTHORS
71
72 Matt S. Trout <mst@shadowcatsystems.co.uk>
73
74 =head1 LICENSE
75
76 You may distribute this code under the same terms as Perl itself.
77
78 =cut
79