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