Commit | Line | Data |
b8e1e21f |
1 | package DBIx::Class::PK::Auto; |
2 | |
773e3015 |
3 | #use base qw/DBIx::Class::PK/; |
4 | use base qw/DBIx::Class/; |
b8e1e21f |
5 | use strict; |
6 | use warnings; |
7 | |
34d52be2 |
8 | =head1 NAME |
9 | |
eb49d4e3 |
10 | DBIx::Class::PK::Auto - Automatic primary key class |
34d52be2 |
11 | |
12 | =head1 SYNOPSIS |
13 | |
77254782 |
14 | __PACKAGE__->load_components(qw/PK::Auto Core/); |
15 | __PACKAGE__->set_primary_key('id'); |
6718c5f0 |
16 | |
34d52be2 |
17 | =head1 DESCRIPTION |
18 | |
eb49d4e3 |
19 | This class overrides the insert method to get automatically incremented primary |
20 | keys. |
34d52be2 |
21 | |
77254782 |
22 | __PACKAGE__->load_components(qw/PK::Auto Core/); |
f4ccda68 |
23 | |
77254782 |
24 | Note that C<PK::Auto> is specified as the leftmost argument. |
7624b19f |
25 | |
c8f4b52b |
26 | =head1 LOGIC |
27 | |
eb49d4e3 |
28 | C<PK::Auto> does this by letting the database assign the primary key field and |
29 | fetching the assigned value afterwards. |
c8f4b52b |
30 | |
34d52be2 |
31 | =head1 METHODS |
32 | |
130c6439 |
33 | =head2 insert |
34d52be2 |
34 | |
eb49d4e3 |
35 | Overrides C<insert> so that it will get the value of autoincremented primary |
36 | keys. |
34d52be2 |
37 | |
38 | =cut |
39 | |
b8e1e21f |
40 | sub insert { |
41 | my ($self, @rest) = @_; |
147dd158 |
42 | my $ret = $self->next::method(@rest); |
0675cd04 |
43 | |
ca48cd7d |
44 | my ($pri, $too_many) = grep { !defined $self->get_column($_) } $self->primary_columns; |
45 | return $ret unless defined $pri; # if all primaries are already populated, skip auto-inc |
701da8c4 |
46 | $self->throw_exception( "More than one possible key found for auto-inc on ".ref $self ) |
ca48cd7d |
47 | if defined $too_many; |
48 | |
fefe2816 |
49 | my $storage = $self->result_source->storage; |
50 | $self->throw_exception( "Missing primary key but Storage doesn't support last_insert_id" ) unless $storage->can('last_insert_id'); |
51 | my $id = $storage->last_insert_id($self->result_source,$pri); |
ca48cd7d |
52 | $self->throw_exception( "Can't get last insert id" ) unless $id; |
53 | $self->store_column($pri => $id); |
54 | |
b8e1e21f |
55 | return $ret; |
56 | } |
57 | |
130c6439 |
58 | =head2 sequence |
97cc0025 |
59 | |
60 | Manually define the correct sequence for your table, to avoid the overhead |
61 | associated with looking up the sequence automatically. |
62 | |
63 | =cut |
64 | |
ecb6488f |
65 | sub sequence { |
66 | my ($self,$seq) = @_; |
67 | foreach my $pri ($self->primary_columns) { |
68 | $self->column_info($pri)->{sequence} = $seq; |
69 | } |
70 | } |
97cc0025 |
71 | |
b8e1e21f |
72 | 1; |
34d52be2 |
73 | |
34d52be2 |
74 | =head1 AUTHORS |
75 | |
daec44b8 |
76 | Matt S. Trout <mst@shadowcatsystems.co.uk> |
34d52be2 |
77 | |
78 | =head1 LICENSE |
79 | |
80 | You may distribute this code under the same terms as Perl itself. |
81 | |
82 | =cut |