Extra files for relationships, has_many support
[dbsrgits/DBIx-Class.git] / lib / DBIx / Class / CDBICompat / HasA.pm
1 package DBIx::Class::CDBICompat::HasA;
2
3 use strict;
4 use warnings;
5
6 sub has_a {
7   my ($self, $col, $f_class) = @_;
8   die "No such column ${col}" unless $self->_columns->{$col};
9   eval "require $f_class";
10   my ($pri, $too_many) = keys %{ $f_class->_primaries };
11   die "has_a only works with a single primary key; ${f_class} has more"
12     if $too_many;
13   $self->add_relationship($col, $f_class,
14                             { "foreign.${pri}" => "self.${col}" },
15                             { _type => 'has_a' } );
16   $self->delete_accessor($col);
17   $self->mk_group_accessors('has_a' => $col);
18   return 1;
19 }
20
21 sub get_has_a {
22   my ($self, $rel) = @_;
23   #warn $rel;
24   #warn join(', ', %{$self->{_column_data}});
25   return $self->{_relationship_data}{$rel}
26     if $self->{_relationship_data}{$rel};
27   return undef unless $self->get_column($rel);
28   #my ($pri) = (keys %{$self->_relationships->{$rel}{class}->_primaries})[0];
29   return $self->{_relationship_data}{$rel} =
30            ($self->search_related($rel, {}, {}))[0]
31            || do { 
32                 my $f_class = $self->_relationships->{$rel}{class};
33                 my ($pri) = keys %{$f_class->_primaries};
34                 $f_class->new({ $pri => $self->get_column($rel) }); };
35 }
36
37 sub set_has_a {
38   my ($self, $rel, @rest) = @_;
39   my $ret = $self->store_has_a($rel, @rest);
40   $self->{_dirty_columns}{$rel} = 1;
41   return $ret;
42 }
43
44 sub store_has_a {
45   my ($self, $rel, $obj) = @_;
46   return $self->set_column($rel, $obj) unless ref $obj;
47   my $rel_obj = $self->_relationships->{$rel};
48   die "Can't set $rel: object $obj is not of class ".$rel_obj->{class}
49      unless $obj->isa($rel_obj->{class});
50   $self->{_relationship_data}{$rel} = $obj;
51   $self->set_column($rel, ($obj->_ident_values)[0]);
52   return $obj;
53 }
54
55 sub new {
56   my ($class, $attrs, @rest) = @_;
57   my %hasa;
58   foreach my $key (keys %$attrs) {
59     my $rt = $class->_relationships->{$key}{attrs}{_type};
60     next unless $rt && $rt eq 'has_a' && ref $attrs->{$key};
61     $hasa{$key} = delete $attrs->{$key};
62   }
63   my $new = $class->NEXT::ACTUAL::new($attrs, @rest);
64   foreach my $key (keys %hasa) {
65     $new->store_has_a($key, $hasa{$key});
66   }
67   return $new;
68 }
69
70 sub _cond_value {
71   my ($self, $attrs, $key, $value) = @_;
72   if ( my $rel_obj = $self->_relationships->{$key} ) {
73     my $rel_type = $rel_obj->{attrs}{_type} || '';
74     if ($rel_type eq 'has_a' && ref $value) {
75       die "Object $value is not of class ".$rel_obj->{class}
76          unless $value->isa($rel_obj->{class});
77       $value = ($value->_ident_values)[0];
78       #warn $value;
79     }
80   }
81   return $self->NEXT::ACTUAL::_cond_value($attrs, $key, $value);
82 }
83
84 1;