1 package DBIx::Class::PK::Auto;
3 #use base qw/DBIx::Class::PK/;
4 use base qw/DBIx::Class/;
10 DBIx::Class::PK::Auto - Automatic primary key class
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');
20 This class overrides the insert method to get automatically incremented primary
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:
26 __PACKAGE__->load_components(qw/PK::Auto::SQLite Core/);
28 Note that C<PK::Auto::SQLite> is specified as the leftmost argument.
30 Alternatively, you can load the components separately:
32 __PACKAGE__->load_components(qw/Core/);
33 __PACKAGE__->load_components(qw/PK::Auto::SQLite/);
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.
40 C<PK::Auto> does this by letting the database assign the primary key field and
41 fetching the assigned value afterwards.
47 Overrides C<insert> so that it will get the value of autoincremented primary
53 my ($self, @rest) = @_;
54 my $ret = $self->next::method(@rest);
56 # if all primaries are already populated, skip auto-inc
58 map { $populated++ if defined $self->get_column($_) } $self->primary_columns;
59 return $ret if ( $populated == scalar $self->primary_columns );
61 my ($pri, $too_many) =
62 (grep { $self->column_info($_)->{'auto_increment'} }
63 $self->primary_columns)
64 || $self->primary_columns;
65 $self->throw_exception( "More than one possible key found for auto-inc on ".ref $self )
67 unless (defined $self->get_column($pri)) {
68 $self->throw_exception( "Can't auto-inc for $pri on ".ref $self.": no _last_insert_id method" )
69 unless $self->can('last_insert_id');
70 my $id = $self->last_insert_id;
71 $self->throw_exception( "Can't get last insert id" ) unless $id;
72 $self->store_column($pri => $id);
79 Manually define the correct sequence for your table, to avoid the overhead
80 associated with looking up the sequence automatically.
84 __PACKAGE__->mk_classdata('sequence');
90 Matt S. Trout <mst@shadowcatsystems.co.uk>
94 You may distribute this code under the same terms as Perl itself.