1 package DBIx::Class::Relationship::Base;
6 use base qw/Class::Data::Inheritable/;
8 __PACKAGE__->mk_classdata('_relationships', { } );
12 DBIx::Class::Relationship - Inter-table relationships
18 This class handles relationships between the tables in your database
19 model. It allows your to set up relationships, and to perform joins
28 sub add_relationship {
29 my ($class, $rel, $f_class, $cond, $attrs) = @_;
30 die "Can't create relationship without join condition" unless $cond;
33 my %rels = %{ $class->_relationships };
34 $rels{$rel} = { class => $f_class,
37 $class->_relationships(\%rels);
38 #warn %{$f_class->_columns};
40 return unless eval { %{$f_class->_columns}; }; # Foreign class not loaded
41 my %join = (%$attrs, _action => 'join',
42 _aliases => { 'self' => 'me', 'foreign' => $rel },
43 _classes => { 'me' => $class, $rel => $f_class });
44 eval { $class->resolve_condition($cond, \%join) };
46 if ($@) { # If the resolve failed, back out and re-throw the error
48 $class->_relationships(\%rels);
49 $class->throw("Error creating relationship $rel: $@");
54 sub resolve_condition {
55 my ($self, $cond, $attrs) = @_;
56 if (ref $cond eq 'HASH') {
58 foreach my $key (keys %$cond) {
59 my $val = $cond->{$key};
61 $self->throw("Can't handle this yet :(");
63 $ret{$self->_cond_key($attrs => $key)}
64 = $self->_cond_value($attrs => $key => $val);
69 $self->throw("Can't handle this yet :(");
74 my ($self, $attrs, $key) = @_;
75 my $action = $attrs->{_action} || '';
76 if ($action eq 'convert') {
77 unless ($key =~ s/^foreign\.//) {
78 $self->throw("Unable to convert relationship to WHERE clause: invalid key ${key}");
81 } elsif ($action eq 'join') {
82 my ($type, $field) = split(/\./, $key);
83 if (my $alias = $attrs->{_aliases}{$type}) {
84 my $class = $attrs->{_classes}{$alias};
85 $self->throw("Unknown column $field on $class as $alias")
86 unless exists $class->_columns->{$field};
87 return join('.', $alias, $field);
89 $self->throw( "Unable to resolve type ${type}: only have aliases for ".
90 join(', ', keys %{$attrs->{_aliases} || {}}) );
93 return $self->NEXT::ACTUAL::_cond_key($attrs, $key);
97 my ($self, $attrs, $key, $value) = @_;
98 my $action = $attrs->{_action} || '';
99 if ($action eq 'convert') {
100 unless ($value =~ s/^self\.//) {
101 $self->throw( "Unable to convert relationship to WHERE clause: invalid value ${value}" );
103 unless ($self->_columns->{$value}) {
104 $self->throw( "Unable to convert relationship to WHERE clause: no such accessor ${value}" );
106 return $self->get_column($value);
107 } elsif ($action eq 'join') {
108 my ($type, $field) = split(/\./, $value);
109 if (my $alias = $attrs->{_aliases}{$type}) {
110 my $class = $attrs->{_classes}{$alias};
111 $self->throw("Unknown column $field on $class as $alias")
112 unless exists $class->_columns->{$field};
113 my $ret = join('.', $alias, $field);
114 # return { '=' => \$ret }; # SQL::Abstract doesn't handle this yet :(
118 $self->throw( "Unable to resolve type ${type}: only have aliases for ".
119 join(', ', keys %{$attrs->{_aliases} || {}}) );
123 return $self->NEXT::ACTUAL::_cond_value($attrs, $key, $value)
128 return $self->_query_related('search', @_);
133 return $self->_query_related('count', @_);
141 if (@_ > 1 && ref $_[$#_] eq 'HASH') {
142 $attrs = { %{ pop(@_) } };
144 my $rel_obj = $self->_relationships->{$rel};
145 $self->throw( "No such relationship ${rel}" ) unless $rel_obj;
146 $attrs = { %{$rel_obj->{attrs} || {}}, %{$attrs || {}} };
148 $self->throw( "Invalid query: @_" ) if (@_ > 1 && (@_ % 2 == 1));
149 my $query = ((@_ > 1) ? {@_} : shift);
151 $attrs->{_action} = 'convert'; # shouldn't we resolve the cond to something
152 # to merge into the AST really?
153 my ($cond) = $self->resolve_condition($rel_obj->{cond}, $attrs);
154 $query = ($query ? { '-and' => [ $cond, $query ] } : $cond);
155 #use Data::Dumper; warn Dumper($query);
156 #warn $rel_obj->{class}." $meth $cond ".join(', ', @{$attrs->{bind}||[]});
157 delete $attrs->{_action};
158 return $self->resolve_class($rel_obj->{class}
159 )->$meth($query, $attrs);
164 return $class->new_related(@_)->insert;
168 my ($self, $rel, $values, $attrs) = @_;
169 $self->throw( "Can't call new_related as class method" )
171 $self->throw( "new_related needs a hash" )
172 unless (ref $values eq 'HASH');
173 my $rel_obj = $self->_relationships->{$rel};
174 $self->throw( "No such relationship ${rel}" ) unless $rel_obj;
175 $self->throw( "Can't abstract implicit create for ${rel}, condition not a hash" )
176 unless ref $rel_obj->{cond} eq 'HASH';
177 $attrs = { %{$rel_obj->{attrs}}, %{$attrs || {}}, _action => 'convert' };
179 my %fields = %{$self->resolve_condition($rel_obj->{cond},$attrs)};
180 $fields{$_} = $values->{$_} for keys %$values;
182 return $self->resolve_class($rel_obj->{class})->new(\%fields);
185 sub find_or_create_related {
187 return ($self->search_related(@_))[0] || $self->create_related(@_);
190 sub set_from_related {
191 my ($self, $rel, $f_obj) = @_;
192 my $rel_obj = $self->_relationships->{$rel};
193 $self->throw( "No such relationship ${rel}" ) unless $rel_obj;
194 my $cond = $rel_obj->{cond};
195 $self->throw( "set_from_related can only handle a hash condition; the "
196 ."condition for $rel is of type ".(ref $cond ? ref $cond : 'plain scalar'))
197 unless ref $cond eq 'HASH';
198 my $f_class = $self->resolve_class($rel_obj->{class});
199 $self->throw( "Object $f_obj isn't a ".$f_class )
200 unless $f_obj->isa($f_class);
201 foreach my $key (keys %$cond) {
202 next if ref $cond->{$key}; # Skip literals and complex conditions
203 $self->throw("set_from_related can't handle $key as key")
204 unless $key =~ m/^foreign\.([^\.]+)$/;
205 my $val = $f_obj->get_column($1);
206 $self->throw("set_from_related can't handle ".$cond->{$key}." as value")
207 unless $cond->{$key} =~ m/^self\.([^\.]+)$/;
208 $self->set_column($1 => $val);
213 sub update_from_related {
215 $self->set_from_related(@_);
221 return $self->search_related(@_)->delete;
230 Matt S. Trout <mst@shadowcatsystems.co.uk>
234 You may distribute this code under the same terms as Perl itself.