Broke out resolve_condition in ResultSource
[dbsrgits/DBIx-Class.git] / lib / DBIx / Class / ResultSource.pm
CommitLineData
9c992ba1 1package DBIx::Class::ResultSource;
2
3use strict;
4use warnings;
5
6use DBIx::Class::ResultSet;
7
8use Carp qw/croak/;
9
10use base qw/DBIx::Class/;
11__PACKAGE__->load_components(qw/AccessorGroup/);
12
13__PACKAGE__->mk_group_accessors('simple' =>
8452e496 14 qw/_ordered_columns _columns _primaries name resultset_class result_class schema from _relationships/);
9c992ba1 15
16=head1 NAME
17
18DBIx::Class::ResultSource - Result source object
19
20=head1 SYNOPSIS
21
22=head1 DESCRIPTION
23
24A ResultSource is a component of a schema from which results can be directly
25retrieved, most usually a table (see L<DBIx::Class::ResultSource::Table>)
26
27=head1 METHODS
28
29=cut
30
31sub new {
32 my ($class, $attrs) = @_;
33 $class = ref $class if ref $class;
34 my $new = bless({ %{$attrs || {}} }, $class);
35 $new->{resultset_class} ||= 'DBIx::Class::ResultSet';
571dced3 36 $new->{_ordered_columns} ||= [];
9c992ba1 37 $new->{_columns} ||= {};
8452e496 38 $new->{_relationships} ||= {};
9c992ba1 39 $new->{name} ||= "!!NAME NOT SET!!";
40 return $new;
41}
42
43sub add_columns {
44 my ($self, @cols) = @_;
571dced3 45 $self->_ordered_columns( \@cols )
46 if !$self->_ordered_columns;
47 push @{ $self->_ordered_columns }, @cols;
9c992ba1 48 while (my $col = shift @cols) {
53509665 49
50 my $column_info = ref $cols[0] ? shift : {};
51 # If next entry is { ... } use that for the column info, if not
52 # use an empty hashref
53
54 $self->_columns->{$col} = $column_info;
9c992ba1 55 }
56}
57
58*add_column = \&add_columns;
59
60=head2 add_columns
61
62 $table->add_columns(qw/col1 col2 col3/);
63
64 $table->add_columns('col1' => \%col1_info, 'col2' => \%col2_info, ...);
65
66Adds columns to the result source. If supplied key => hashref pairs uses
67the hashref as the column_info for that column.
68
69=head2 add_column
70
71 $table->add_column('col' => \%info?);
72
73Convenience alias to add_columns
74
75=cut
76
77sub resultset {
78 my $self = shift;
79 return $self->resultset_class->new($self);
80}
81
82=head2 has_column
83
84 if ($obj->has_column($col)) { ... }
85
86Returns 1 if the source has a column of this name, 0 otherwise.
87
88=cut
89
90sub has_column {
91 my ($self, $column) = @_;
92 return exists $self->_columns->{$column};
93}
94
95=head2 column_info
96
97 my $info = $obj->column_info($col);
98
99Returns the column metadata hashref for a column.
100
101=cut
102
103sub column_info {
104 my ($self, $column) = @_;
105 croak "No such column $column" unless exists $self->_columns->{$column};
106 return $self->_columns->{$column};
107}
108
109=head2 columns
110
111 my @column_names = $obj->columns;
112
113=cut
114
115sub columns {
116 croak "columns() is a read-only accessor, did you mean add_columns()?" if (@_ > 1);
117 return keys %{shift->_columns};
118}
119
571dced3 120=head2 ordered_columns
121
122 my @column_names = $obj->ordered_columns;
123
124Like columns(), but returns column names using the order in which they were
125originally supplied to add_columns().
126
127=cut
128
129sub ordered_columns {
130 return @{shift->{_ordered_columns}||[]};
131}
132
9c992ba1 133=head2 set_primary_key(@cols)
134
135Defines one or more columns as primary key for this source. Should be
136called after C<add_columns>.
137
138=cut
139
140sub set_primary_key {
141 my ($self, @cols) = @_;
142 # check if primary key columns are valid columns
143 for (@cols) {
144 $self->throw("No such column $_ on table ".$self->name)
145 unless $self->has_column($_);
146 }
147 $self->_primaries(\@cols);
148}
149
150=head2 primary_columns
151
152Read-only accessor which returns the list of primary keys.
153
154=cut
155
156sub primary_columns {
157 return @{shift->_primaries||[]};
158}
159
160=head2 from
161
162Returns an expression of the source to be supplied to storage to specify
163retrieval from this source; in the case of a database the required FROM clause
164contents.
165
166=cut
167
168=head2 storage
169
170Returns the storage handle for the current schema
171
172=cut
173
174sub storage { shift->schema->storage; }
175
8452e496 176=head2 add_relationship
177
178 $source->add_relationship('relname', 'related_source', $cond, $attrs);
179
180The relation name can be arbitrary, but must be unique for each relationship
181attached to this result source. 'related_source' should be the name with
182which the related result source was registered with the current schema
183(for simple schemas this is usally either Some::Namespace::Foo or just Foo)
184
185The condition needs to be an SQL::Abstract-style representation of the join
186between the tables. For example, if you're creating a rel from Foo to Bar,
187
188 { 'foreign.foo_id' => 'self.id' }
189
190will result in the JOIN clause
191
192 foo me JOIN bar bar ON bar.foo_id = me.id
193
194You can specify as many foreign => self mappings as necessary.
195
196Valid attributes are as follows:
197
198=over 4
199
200=item join_type
201
202Explicitly specifies the type of join to use in the relationship. Any SQL
203join type is valid, e.g. C<LEFT> or C<RIGHT>. It will be placed in the SQL
204command immediately before C<JOIN>.
205
206=item proxy
207
208An arrayref containing a list of accessors in the foreign class to proxy in
209the main class. If, for example, you do the following:
210
211 __PACKAGE__->might_have(bar => 'Bar', undef, { proxy => qw[/ margle /] });
212
213Then, assuming Bar has an accessor named margle, you can do:
214
215 my $obj = Foo->find(1);
216 $obj->margle(10); # set margle; Bar object is created if it doesn't exist
217
218=item accessor
219
220Specifies the type of accessor that should be created for the relationship.
221Valid values are C<single> (for when there is only a single related object),
222C<multi> (when there can be many), and C<filter> (for when there is a single
223related object, but you also want the relationship accessor to double as
224a column accessor). For C<multi> accessors, an add_to_* method is also
225created, which calls C<create_related> for the relationship.
226
227=back
228
229=cut
230
231sub add_relationship {
232 my ($self, $rel, $f_source_name, $cond, $attrs) = @_;
233 die "Can't create relationship without join condition" unless $cond;
234 $attrs ||= {};
87772e46 235
8452e496 236 my %rels = %{ $self->_relationships };
237 $rels{$rel} = { class => $f_source_name,
87772e46 238 source => $f_source_name,
8452e496 239 cond => $cond,
240 attrs => $attrs };
241 $self->_relationships(\%rels);
242
87772e46 243 return 1;
244
953a18ef 245 # XXX disabled. doesn't work properly currently. skip in tests.
246
8452e496 247 my $f_source = $self->schema->source($f_source_name);
248 unless ($f_source) {
249 eval "require $f_source_name;";
250 if ($@) {
251 die $@ unless $@ =~ /Can't locate/;
252 }
253 $f_source = $f_source_name->result_source;
87772e46 254 #my $s_class = ref($self->schema);
255 #$f_source_name =~ m/^${s_class}::(.*)$/;
256 #$self->schema->register_class(($1 || $f_source_name), $f_source_name);
257 #$f_source = $self->schema->source($f_source_name);
8452e496 258 }
259 return unless $f_source; # Can't test rel without f_source
260
261 eval { $self->resolve_join($rel, 'me') };
262
263 if ($@) { # If the resolve failed, back out and re-throw the error
264 delete $rels{$rel}; #
265 $self->_relationships(\%rels);
266 die "Error creating relationship $rel: $@";
267 }
268 1;
269}
270
271=head2 relationships()
272
273Returns all valid relationship names for this source
274
275=cut
276
277sub relationships {
278 return keys %{shift->_relationships};
279}
280
281=head2 relationship_info($relname)
282
283Returns the relationship information for the specified relationship name
284
285=cut
286
287sub relationship_info {
288 my ($self, $rel) = @_;
289 return $self->_relationships->{$rel};
290}
291
953a18ef 292=head2 has_relationship($rel)
293
294Returns 1 if the source has a relationship of this name, 0 otherwise.
295
296=cut
297
298sub has_relationship {
299 my ($self, $rel) = @_;
300 return exists $self->_relationships->{$rel};
301}
302
8452e496 303=head2 resolve_join($relation)
304
305Returns the join structure required for the related result source
306
307=cut
308
309sub resolve_join {
87772e46 310 my ($self, $join, $alias) = @_;
311 if (ref $join eq 'ARRAY') {
312 return map { $self->resolve_join($_, $alias) } @$join;
313 } elsif (ref $join eq 'HASH') {
314 return map { $self->resolve_join($_, $alias),
315 $self->related_source($_)->resolve_join($join->{$_}, $_) }
316 keys %$join;
317 } elsif (ref $join) {
318 die("No idea how to resolve join reftype ".ref $join);
319 } else {
953a18ef 320 die("No such relationship ${join}") unless $self->has_relationship($join);
321 my $type = $self->relationship_info($join)->{attrs}{join_type} || '';
322 return [ { $join => $self->related_source($join)->from,
323 -join_type => $type },
324 $self->resolve_condition($join, $alias) ];
325 }
326}
327
328=head2 resolve_condition($rel, $alias|$object)
329
330Returns the conditional for the specified relationship. If given an alias,
331returns a join condition; if given an object, inverts that object to produce
332a related conditional from that object.
333
334=cut
335
336sub resolve_condition {
337 my ($self, $rel, $for) = @_;
338 my $cond = $self->relationship_info($rel)->{cond};
339 #warn %$cond;
340 if (ref $cond eq 'HASH') {
341 my %ret;
342 while (my ($k, $v) = each %{$cond}) {
343 # XXX should probably check these are valid columns
344 $k =~ s/^foreign\./${rel}./ || die "Invalid rel cond key ${k}";
345 if (ref $for) { # Object
346 die "Invalid ref cond val ${v}" unless $v =~ m/^self\.(.*)$/;
347 $ret{$k} = $for->$1;
348 } else {
349 $v =~ s/^self\./${for}./ || die "Invalid rel cond val ${v}";
350 }
351 $ret{$k} = $v;
352 }
353 return \%ret;
354 } else {
355 die("Can't handle this yet :(");
87772e46 356 }
357}
358
953a18ef 359
87772e46 360=head2 related_source($relname)
361
362Returns the result source for the given relationship
363
364=cut
365
366sub related_source {
367 my ($self, $rel) = @_;
368 return $self->schema->source($self->relationship_info($rel)->{source});
8452e496 369}
370
9c992ba1 3711;
372
373=head1 AUTHORS
374
375Matt S. Trout <mst@shadowcatsystems.co.uk>
376
377=head1 LICENSE
378
379You may distribute this code under the same terms as Perl itself.
380
381=cut
382