Added count, count_related, and tests
[dbsrgits/DBIx-Class.git] / lib / DBIx / Class / Table.pm
index 734e1d9..ec750fe 100644 (file)
@@ -127,8 +127,9 @@ sub get_column {
 sub set_column {
   my $self = shift;
   my ($column) = @_;
+  my $old = $self->get_column($column);
   my $ret = $self->store_column(@_);
-  $self->{_dirty_columns}{$column} = 1;
+  $self->{_dirty_columns}{$column} = 1 unless defined $old && $old eq $ret;
   return $ret;
 }
 
@@ -169,6 +170,22 @@ sub retrieve_from_sql {
   return $class->sth_to_objects($sth, \@vals, \@cols, { where => $cond });
 }
 
+sub count {
+  my $class = shift;
+  my $attrs = { };
+  if (@_ > 1 && ref $_[$#_] eq 'HASH') {
+    $attrs = { %{ pop(@_) } };
+  }
+  my $query    = ref $_[0] eq "HASH" ? shift: {@_};
+  my ($cond, @param)  = $class->_cond_resolve($query, $attrs);
+  my $sth = $class->_get_sth( 'select', [ 'COUNT(*)' ],
+                                $class->_table_name, $cond );
+  $sth->execute(@param);
+  my ($count) = $sth->fetchrow_array;
+  $sth->finish;
+  return $count;
+}
+
 sub sth_to_objects {
   my ($class, $sth, $args, $cols, $attrs) = @_;
   my @cols = ((ref $cols eq 'ARRAY') ? @$cols : @{$sth->{NAME_lc}} );
@@ -241,11 +258,20 @@ sub find_or_create {
   return defined($exists) ? $exists : $class->create($hash);
 }
 
+sub insert_or_update {
+  my $self = shift;
+  return ($self->in_database ? $self->update : $self->insert);
+}
+
 sub retrieve_all {
   my ($class) = @_;
   return $class->retrieve_from_sql( '1' );
 }
 
+sub is_changed {
+  return keys %{shift->{_dirty_columns} || {}};
+}
+
 1;
 
 =back