Refactor unique constraint access to ResultSource
[dbsrgits/DBIx-Class.git] / lib / DBIx / Class / ResultSet.pm
index 954daa3..8263f11 100644 (file)
@@ -272,12 +272,17 @@ sub search_literal {
 
 =back
 
-Finds a row based on its primary key or unique constraint. For example:
+Finds a row based on its primary key or unique constraint. For example, to find
+a row by its primary key:
 
   my $cd = $schema->resultset('CD')->find(5);
 
-Also takes an optional C<key> attribute, to search by a specific key or unique
-constraint. For example:
+You can also find a row by a specific key or unique constraint by specifying
+the C<key> attribute. For example:
+
+  my $cd = $schema->resultset('CD')->find('Massive Attack', 'Mezzanine', { key => 'artist_title' });
+
+Additionally, you can specify the columns explicitly by name:
 
   my $cd = $schema->resultset('CD')->find(
     {
@@ -287,7 +292,14 @@ constraint. For example:
     { key => 'artist_title' }
   );
 
-See also L</find_or_create> and L</update_or_create>.
+If no C<key> is specified and you explicitly name columns, it searches on all
+unique constraints defined on the source, including the primary key.
+
+If the C<key> is specified as C<primary>, it searches only on the primary key.
+
+See also L</find_or_create> and L</update_or_create>. For information on how to
+declare unique constraints, see
+L<DBIx::Class::ResultSource/add_unique_constraint>.
 
 =cut
 
@@ -295,51 +307,51 @@ sub find {
   my ($self, @vals) = @_;
   my $attrs = (@vals > 1 && ref $vals[$#vals] eq 'HASH' ? pop(@vals) : {});
 
-  my %unique_constraints = $self->result_source->unique_constraints;
-  $self->throw_exception(
-    "Can't find unless a primary key or unique constraint is defined"
-  ) unless %unique_constraints;
+  # Build a list of queries
+  my @unique_hashes;
 
-  my @constraint_names = keys %unique_constraints;
-  if (exists $attrs->{key}) {
+  if (ref $vals[0] eq 'HASH') {
+    my @constraint_names = exists $attrs->{key}
+      ? ($attrs->{key})
+      : $self->result_source->unique_constraint_names;
     $self->throw_exception(
-      "Unknown key $attrs->{key} on '" . $self->result_source->name . "'"
-    ) unless exists $unique_constraints{$attrs->{key}};
+      "Can't find by explicitly named columns unless a primary key or unique constraint is defined"
+    ) unless @constraint_names;
 
-    @constraint_names = ($attrs->{key});
-  }
-
-  my @unique_hashes;
-  foreach my $name (@constraint_names) {
-    my @unique_cols = @{ $unique_constraints{$name} };
-    my %unique_hash;
-    if (ref $vals[0] eq 'HASH') {
-      # Stupid hack for CDBICompat
-      my %hash = %{ $vals[0] };
-      foreach my $key (keys %hash) {
-        $hash{lc $key} = delete $hash{$key};
-      }
+    foreach my $name (@constraint_names) {
+      my @unique_cols = $self->result_source->unique_constraint_columns($name);
+      my $unique_hash = $self->_unique_hash($vals[0], \@unique_cols);
 
-      %unique_hash =
-        map  { $_ => $hash{$_} }
-        grep { exists $hash{$_} }
-        @unique_cols;
+      # TODO: Check that the ResultSet defines the rest of the query
+      push @unique_hashes, $unique_hash
+        if scalar keys %$unique_hash;# == scalar @unique_cols;
     }
-    elsif (@unique_cols == @vals) {
-      # Assume the argument order corresponds to the constraint definition
+  }
+  else {
+    my @unique_cols = exists $attrs->{key}
+      ? $self->result_source->unique_constraint_columns($attrs->{key})
+      : $self->result_source->primary_columns;
+    $self->throw_exception(
+      "Can't find unless a primary key is defined or a unique constraint is specified"
+    ) unless @unique_cols;
+
+    if (@vals == @unique_cols) {
+      my %unique_hash;
       @unique_hash{@unique_cols} = @vals;
+      push @unique_hashes, \%unique_hash;
     }
-    elsif (@vals % 2 == 0) {
-      # Fix for CDBI calling with a hash
-      %unique_hash = @vals;
+    else {
+      # Hack for CDBI queries
+      my %hash = @vals;
+      push @unique_hashes, \%hash;
     }
+  }
 
-    foreach my $key (grep { ! m/\./ } keys %unique_hash) {
-      $unique_hash{"$self->{attrs}{alias}.$key"} = delete $unique_hash{$key};
+  # Add the ResultSet's alias
+  foreach my $unique_hash (@unique_hashes) {
+    foreach my $key (grep { ! m/\./ } keys %$unique_hash) {
+      $unique_hash->{"$self->{attrs}{alias}.$key"} = delete $unique_hash->{$key};
     }
-
-    #use Data::Dumper; warn Dumper \@vals, \@unique_cols, \%unique_hash;
-    push @unique_hashes, \%unique_hash if %unique_hash;
   }
 
   # Handle cases where the ResultSet already defines the query
@@ -356,6 +368,28 @@ sub find {
   }
 }
 
+# _unique_hash
+#
+# Constrain the specified hash based on the specific column names.
+
+sub _unique_hash {
+  my ($self, $hash, $unique_cols) = @_;
+
+  # Ugh, CDBI lowercases column names
+  if (exists $INC{'DBIx/Class/CDBICompat/ColumnCase.pm'}) {
+    foreach my $key (keys %$hash) {
+      $hash->{lc $key} = delete $hash->{$key};
+    }
+  }
+
+  my %unique_hash =
+    map  { $_ => $hash->{$_} }
+    grep { exists $hash->{$_} }
+    @$unique_cols;
+
+  return \%unique_hash;
+}
+
 =head2 search_related
 
 =over 4
@@ -415,7 +449,7 @@ sub cursor {
   my $cd = $schema->resultset('CD')->single({ year => 2001 });
 
 Inflates the first result without creating a cursor if the resultset has
-any records in it; if not returns nothing. Used by find() as an optimisation.
+any records in it; if not returns nothing. Used by L</find> as an optimisation.
 
 =cut
 
@@ -1074,6 +1108,32 @@ sub new_result {
   return $obj;
 }
 
+=head2 find_or_new
+
+=over 4
+
+=item Arguments: \%vals, \%attrs?
+
+=item Return Value: $object
+
+=back
+
+Find an existing record from this resultset. If none exists, instantiate a new
+result object and return it. The object will not be saved into your storage
+until you call L<DBIx::Class::Row/insert> on it.
+
+If you want objects to be saved immediately, use L</find_or_create> instead.
+
+=cut
+
+sub find_or_new {
+  my $self     = shift;
+  my $attrs    = (@_ > 1 && ref $_[$#_] eq 'HASH' ? pop(@_) : {});
+  my $hash     = ref $_[0] eq 'HASH' ? shift : {@_};
+  my $exists   = $self->find($hash, $attrs);
+  return defined $exists ? $exists : $self->new_result($hash);
+}
+
 =head2 create
 
 =over 4
@@ -1130,7 +1190,8 @@ constraint. For example:
     { key => 'artist_title' }
   );
 
-See also L</find> and L</update_or_create>.
+See also L</find> and L</update_or_create>. For information on how to declare
+unique constraints, see L<DBIx::Class::ResultSource/add_unique_constraint>.
 
 =cut
 
@@ -1177,7 +1238,8 @@ source, including the primary key.
 
 If the C<key> is specified as C<primary>, it searches only on the primary key.
 
-See also L</find> and L</find_or_create>.
+See also L</find> and L</find_or_create>. For information on how to declare
+unique constraints, see L<DBIx::Class::ResultSource/add_unique_constraint>.
 
 =cut