Reorder relationship sanity checks, run them only on known loaded classes
[dbsrgits/DBIx-Class.git] / lib / DBIx / Class / Relationship / BelongsTo.pm
index e55d1bd..b594d3a 100644 (file)
@@ -17,7 +17,7 @@ our %_pod_inherit_config =
 sub belongs_to {
   my ($class, $rel, $f_class, $cond, $attrs) = @_;
 
-  # assume a foreign key contraint unless defined otherwise
+  # assume a foreign key constraint unless defined otherwise
   $attrs->{is_foreign_key_constraint} = 1
     if not exists $attrs->{is_foreign_key_constraint};
   $attrs->{undef_on_null_fk} = 1
@@ -25,29 +25,39 @@ sub belongs_to {
 
   # no join condition or just a column name
   if (!ref $cond) {
-    $class->ensure_class_loaded($f_class);
-    my %f_primaries = map { $_ => 1 } try { $f_class->_pri_cols }
-      catch {
-        $class->throw_exception( "Can't infer join condition for '$rel' on ${class}: $_");
-      };
 
-    my ($pri, $too_many) = keys %f_primaries;
-    $class->throw_exception(
-      "Can't infer join condition for '$rel' on ${class}: "
-    . "${f_class} has multiple primary keys"
-    ) if $too_many;
+    my ($f_key, $guess);
+    if (defined $cond and length $cond) {
+      $f_key = $cond;
+      $guess = "caller specified foreign key '$f_key'";
+    }
+    else {
+      $f_key = $rel;
+      $guess = "using given relationship name '$rel' as foreign key column name";
+    }
 
-    my $fk = defined $cond ? $cond : $rel;
     $class->throw_exception(
-      "Can't infer join condition for '$rel' on ${class}: "
-    . "'$fk' is not a column of $class"
-    ) unless $class->has_column($fk);
+      "No such column '$f_key' declared yet on ${class} ($guess)"
+    )  unless $class->has_column($f_key);
+
+    $class->ensure_class_loaded($f_class);
+    my $f_rsrc = try {
+      $f_class->result_source_instance;
+    }
+    catch {
+      $class->throw_exception(
+        "Foreign class '$f_class' does not seem to be a Result class "
+      . "(or it simply did not load entirely due to a circular relation chain)"
+      );
+    };
 
-    $cond = { "foreign.${pri}" => "self.${fk}" };
+    my $pri = $f_rsrc->_single_pri_col_or_die;
+
+    $cond = { "foreign.${pri}" => "self.${f_key}" };
 
   }
   # explicit join condition
-  elsif (ref $cond) {
+  else {
     if (ref $cond eq 'HASH') { # ARRAY is also valid
       my $cond_rel;
       for (keys %$cond) {
@@ -60,19 +70,14 @@ sub belongs_to {
       $cond = $cond_rel;
     }
   }
-  # dunno
-  else {
-    $class->throw_exception(
-      'third argument for belongs_to must be undef, a column name, '.
-      'or a join condition'
-    );
-  }
 
   my $acc_type = (
     ref $cond eq 'HASH'
       and
     keys %$cond == 1
       and
+    (keys %$cond)[0] =~ /^foreign\./
+      and
     $class->has_column($rel)
   ) ? 'filter' : 'single';