undo changes that should have been in TRUNK. /me thwaps self
[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   # In your table classes (replace PK::Auto::SQLite with your database)
15   __PACKAGE__->load_components(qw/PK::Auto::SQLite Core/);
16   __PACKAGE__->set_primary_key('id');
17
18 =head1 DESCRIPTION
19
20 This class overrides the insert method to get automatically incremented primary
21 keys.
22
23 You don't want to be using this directly - instead load the appropriate one for
24 your database, e.g. C<PK::Auto::SQLite>, in your table classes:
25
26   __PACKAGE__->load_components(qw/PK::Auto::SQLite Core/);
27
28 Note that C<PK::Auto::SQLite> is specified as the leftmost argument.
29
30 Alternatively, you can load the components separately:
31
32   __PACKAGE__->load_components(qw/Core/);
33   __PACKAGE__->load_components(qw/PK::Auto::SQLite/);
34
35 This can be used, for example, if you have different databases and need to
36 determine the appropriate C<PK::Auto> class at runtime.
37
38 =head1 LOGIC
39
40 C<PK::Auto> does this by letting the database assign the primary key field and
41 fetching the assigned value afterwards.
42
43 =head1 METHODS
44
45 =head2 insert
46
47 Overrides C<insert> so that it will get the value of autoincremented primary
48 keys.
49
50 =cut
51
52 sub insert {
53   my ($self, @rest) = @_;
54   my $ret = $self->next::method(@rest);
55
56   my ($pri, $too_many) = grep { !defined $self->get_column($_) } $self->primary_columns;
57   return $ret unless defined $pri; # if all primaries are already populated, skip auto-inc
58   $self->throw_exception( "More than one possible key found for auto-inc on ".ref $self )
59     if defined $too_many;
60
61   my $storage = $self->result_source->storage;
62   $self->throw_exception( "Missing primary key but Storage doesn't support last_insert_id" ) unless $storage->can('last_insert_id');
63   my $id = $storage->last_insert_id($self->result_source,$pri);
64   $self->throw_exception( "Can't get last insert id" ) unless $id;
65   $self->store_column($pri => $id);
66
67   return $ret;
68 }
69
70 =head2 sequence
71
72 Manually define the correct sequence for your table, to avoid the overhead
73 associated with looking up the sequence automatically.
74
75 =cut
76
77 sub sequence {
78     my ($self,$seq) = @_;
79     foreach my $pri ($self->primary_columns) {
80         $self->column_info($pri)->{sequence} = $seq;
81     }
82 }
83
84 1;
85
86 =head1 AUTHORS
87
88 Matt S. Trout <mst@shadowcatsystems.co.uk>
89
90 =head1 LICENSE
91
92 You may distribute this code under the same terms as Perl itself.
93
94 =cut