1 package DBIx::Class::PK;
7 use base qw/DBIx::Class::Row/;
9 __PACKAGE__->mk_classdata('_primaries' => {});
13 DBIx::Class::PK - Primary Key class
19 This class represents methods handling primary keys
20 and depending on them.
30 return join(" AND ", map { "$_ = ?" } keys %{$class->_primaries});
35 return (map { $self->{_column_data}{$_} } keys %{$self->_primaries});
38 =item set_primary_key <@cols>
40 define one or more columns as primary key for this class
45 my ($class, @cols) = @_;
47 tie %pri, 'Tie::IxHash', map { $_ => {} } @cols;
48 $class->_primaries(\%pri);
53 Finds columns based on the primary key(s).
58 my ($class, @vals) = @_;
59 my $attrs = (@vals > 1 && ref $vals[$#vals] eq 'HASH' ? pop(@vals) : {});
60 my @pk = keys %{$class->_primaries};
61 $class->throw( "Can't find unless primary columns are defined" )
64 if (ref $vals[0] eq 'HASH') {
66 } elsif (@pk == @vals) {
68 @{$query}{@pk} = @vals;
69 #my $ret = ($class->search_literal($class->_ident_cond, @vals, $attrs))[0];
70 #warn "$class: ".join(', ', %{$ret->{_column_data}});
75 $class->throw( "Can't find unless all primary keys are specified" )
76 unless (keys %$query >= @pk); # If we check 'em we run afoul of uc/lc
77 # column names etc. Not sure what to do yet
78 #return $class->search($query)->next;
79 my @cols = $class->_select_columns;
80 my @row = $class->storage->select_single($class->_table_name, \@cols, $query);
81 return (@row ? $class->_row_to_object(\@cols, \@row) : ());
86 Roll back changes that hasn't been comitted to the database.
92 delete $self->{_dirty_columns};
93 return unless $self->in_storage; # Don't reload if we aren't real!
94 my ($reload) = $self->find($self->id);
95 unless ($reload) { # If we got deleted in the mean-time
99 delete @{$self}{keys %$self};
100 @{$self}{keys %$reload} = values %$reload;
106 returns the primary key(s) for the current row. Can't be called as
113 $self->throw( "Can't call id() as a class method" ) unless ref $self;
114 my @pk = $self->_ident_values;
115 return (wantarray ? @pk : $pk[0]);
118 =item primary_columns
120 read-only accessor which returns a list of primary keys.
124 sub primary_columns {
125 return keys %{shift->_primaries};
130 $self->throw( "Can't call ID() as a class method" ) unless ref $self;
131 return undef unless $self->in_storage;
132 return $self->_create_ID(map { $_ => $self->{_column_data}{$_} } keys %{$self->_primaries});
136 my ($class,%vals) = @_;
137 return undef unless 0 == grep { !defined } values %vals;
138 $class = ref $class || $class;
139 return join '|', $class, map { $_ . '=' . $vals{$_} } sort keys %vals;
142 sub ident_condition {
145 $cond{$_} = $self->get_column($_) for $self->primary_columns;
155 Matt S. Trout <mst@shadowcatsystems.co.uk>
159 You may distribute this code under the same terms as Perl itself.