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