expanded/clarified documentation
[dbsrgits/DBIx-Class.git] / lib / DBIx / Class / ResultSet.pm
CommitLineData
89c0a5a2 1package DBIx::Class::ResultSet;
2
3use strict;
4use warnings;
5use overload
ebaefbc2 6 '0+' => \&count,
a910dc57 7 'bool' => sub { 1; },
89c0a5a2 8 fallback => 1;
3c5b25c5 9use Data::Page;
ea20d0fd 10use Storable;
bcd26419 11use Scalar::Util qw/weaken/;
89c0a5a2 12
701da8c4 13use base qw/DBIx::Class/;
14__PACKAGE__->load_components(qw/AccessorGroup/);
a50bcd52 15__PACKAGE__->mk_group_accessors('simple' => qw/result_source result_class/);
701da8c4 16
ee38fa40 17=head1 NAME
18
bfab575a 19DBIx::Class::ResultSet - Responsible for fetching and creating resultset.
ee38fa40 20
bfab575a 21=head1 SYNOPSIS
ee38fa40 22
a33df5d4 23 my $rs = $schema->resultset('User')->search(registered => 1);
24d67825 24 my @rows = $schema->resultset('CD')->search(year => 2005);
ee38fa40 25
26=head1 DESCRIPTION
27
bfab575a 28The resultset is also known as an iterator. It is responsible for handling
a33df5d4 29queries that may return an arbitrary number of rows, e.g. via L</search>
bfab575a 30or a C<has_many> relationship.
ee38fa40 31
a33df5d4 32In the examples below, the following table classes are used:
33
34 package MyApp::Schema::Artist;
35 use base qw/DBIx::Class/;
f4409169 36 __PACKAGE__->load_components(qw/Core/);
a33df5d4 37 __PACKAGE__->table('artist');
38 __PACKAGE__->add_columns(qw/artistid name/);
39 __PACKAGE__->set_primary_key('artistid');
40 __PACKAGE__->has_many(cds => 'MyApp::Schema::CD');
41 1;
42
43 package MyApp::Schema::CD;
44 use base qw/DBIx::Class/;
f4409169 45 __PACKAGE__->load_components(qw/Core/);
46 __PACKAGE__->table('cd');
a33df5d4 47 __PACKAGE__->add_columns(qw/cdid artist title year/);
48 __PACKAGE__->set_primary_key('cdid');
49 __PACKAGE__->belongs_to(artist => 'MyApp::Schema::Artist');
50 1;
51
ee38fa40 52=head1 METHODS
53
87c4e602 54=head2 new
55
56=head3 Arguments: ($source, \%$attrs)
ee38fa40 57
a33df5d4 58The resultset constructor. Takes a source object (usually a
aa1088bf 59L<DBIx::Class::ResultSourceProxy::Table>) and an attribute hash (see
60L</ATTRIBUTES> below). Does not perform any queries -- these are
61executed as needed by the other methods.
a33df5d4 62
63Generally you won't need to construct a resultset manually. You'll
64automatically get one from e.g. a L</search> called in scalar context:
65
66 my $rs = $schema->resultset('CD')->search({ title => '100th Window' });
ee38fa40 67
68=cut
69
89c0a5a2 70sub new {
fea3d045 71 my $class = shift;
f9db5527 72 return $class->new_result(@_) if ref $class;
5e8b1b2a 73
fea3d045 74 my ($source, $attrs) = @_;
bcd26419 75 weaken $source;
ea20d0fd 76 $attrs = Storable::dclone($attrs || {}); # { %{ $attrs || {} } };
bcd26419 77 #use Data::Dumper; warn Dumper($attrs);
6aeb9185 78 my $alias = ($attrs->{alias} ||= 'me');
5e8b1b2a 79
80 $attrs->{columns} ||= delete $attrs->{cols} if $attrs->{cols};
1c258fc1 81 delete $attrs->{as} if $attrs->{columns};
5e8b1b2a 82 $attrs->{columns} ||= [ $source->columns ] unless $attrs->{select};
aa1088bf 83 $attrs->{select} = [
84 map { m/\./ ? $_ : "${alias}.$_" } @{delete $attrs->{columns}}
85 ] if $attrs->{columns};
86 $attrs->{as} ||= [
87 map { m/^\Q$alias.\E(.+)$/ ? $1 : $_ } @{$attrs->{select}}
88 ];
5ac6a044 89 if (my $include = delete $attrs->{include_columns}) {
90 push(@{$attrs->{select}}, @$include);
223aea40 91 push(@{$attrs->{as}}, map { m/([^.]+)$/; $1; } @$include);
5ac6a044 92 }
976f3686 93 #use Data::Dumper; warn Dumper(@{$attrs}{qw/select as/});
5e8b1b2a 94
fea3d045 95 $attrs->{from} ||= [ { $alias => $source->from } ];
8fab5eef 96 $attrs->{seen_join} ||= {};
5e8b1b2a 97 my %seen;
b52e9bf8 98 if (my $join = delete $attrs->{join}) {
5e8b1b2a 99 foreach my $j (ref $join eq 'ARRAY' ? @$join : ($join)) {
c7ce65e6 100 if (ref $j eq 'HASH') {
101 $seen{$_} = 1 foreach keys %$j;
102 } else {
103 $seen{$j} = 1;
104 }
105 }
aa1088bf 106 push(@{$attrs->{from}}, $source->resolve_join(
107 $join, $attrs->{alias}, $attrs->{seen_join})
108 );
c7ce65e6 109 }
5e8b1b2a 110
54540863 111 $attrs->{group_by} ||= $attrs->{select} if delete $attrs->{distinct};
aa1088bf 112 $attrs->{order_by} = [ $attrs->{order_by} ] if
113 $attrs->{order_by} and !ref($attrs->{order_by});
a86b1efe 114 $attrs->{order_by} ||= [];
115
555af3d9 116 my $collapse = $attrs->{collapse} || {};
b3e8ac9b 117 if (my $prefetch = delete $attrs->{prefetch}) {
0f66a01b 118 my @pre_order;
5e8b1b2a 119 foreach my $p (ref $prefetch eq 'ARRAY' ? @$prefetch : ($prefetch)) {
120 if ( ref $p eq 'HASH' ) {
b3e8ac9b 121 foreach my $key (keys %$p) {
122 push(@{$attrs->{from}}, $source->resolve_join($p, $attrs->{alias}))
123 unless $seen{$key};
124 }
5e8b1b2a 125 } else {
b3e8ac9b 126 push(@{$attrs->{from}}, $source->resolve_join($p, $attrs->{alias}))
127 unless $seen{$p};
128 }
a86b1efe 129 my @prefetch = $source->resolve_prefetch(
0f66a01b 130 $p, $attrs->{alias}, {}, \@pre_order, $collapse);
489709af 131 push(@{$attrs->{select}}, map { $_->[0] } @prefetch);
132 push(@{$attrs->{as}}, map { $_->[1] } @prefetch);
b3e8ac9b 133 }
0f66a01b 134 push(@{$attrs->{order_by}}, @pre_order);
fef5d100 135 }
555af3d9 136 $attrs->{collapse} = $collapse;
5e8b1b2a 137# use Data::Dumper; warn Dumper($collapse) if keys %{$collapse};
555af3d9 138
6aeb9185 139 if ($attrs->{page}) {
140 $attrs->{rows} ||= 10;
141 $attrs->{offset} ||= 0;
142 $attrs->{offset} += ($attrs->{rows} * ($attrs->{page} - 1));
143 }
0f66a01b 144
5e8b1b2a 145 bless {
701da8c4 146 result_source => $source,
a50bcd52 147 result_class => $attrs->{result_class} || $source->result_class,
89c0a5a2 148 cond => $attrs->{where},
0a3c5b43 149 from => $attrs->{from},
0f66a01b 150 collapse => $collapse,
3c5b25c5 151 count => undef,
93b004d3 152 page => delete $attrs->{page},
3c5b25c5 153 pager => undef,
5e8b1b2a 154 attrs => $attrs
155 }, $class;
89c0a5a2 156}
157
bfab575a 158=head2 search
0a3c5b43 159
24d67825 160 my @cds = $rs->search({ year => 2001 }); # "... WHERE year = 2001"
161 my $new_rs = $rs->search({ year => 2005 });
87f0da6a 162
6009260a 163If you need to pass in additional attributes but no additional condition,
5e8b1b2a 164call it as C<search(undef, \%attrs);>.
87f0da6a 165
24d67825 166 # "SELECT name, artistid FROM $artist_table"
167 my @all_artists = $schema->resultset('Artist')->search(undef, {
168 columns => [qw/name artistid/],
169 });
0a3c5b43 170
171=cut
172
173sub search {
174 my $self = shift;
175
ff7bb7a1 176 my $rs;
177 if( @_ ) {
178
179 my $attrs = { %{$self->{attrs}} };
8839560b 180 my $having = delete $attrs->{having};
223aea40 181 $attrs = { %$attrs, %{ pop(@_) } } if @_ > 1 and ref $_[$#_] eq 'HASH';
6009260a 182
3e0e9e27 183 my $where = (@_
184 ? ((@_ == 1 || ref $_[0] eq "HASH")
185 ? shift
186 : ((@_ % 2)
187 ? $self->throw_exception(
188 "Odd number of arguments to search")
189 : {@_}))
190 : undef());
ff7bb7a1 191 if (defined $where) {
223aea40 192 $attrs->{where} = (defined $attrs->{where}
ad3d2d7c 193 ? { '-and' =>
194 [ map { ref $_ eq 'ARRAY' ? [ -or => $_ ] : $_ }
195 $where, $attrs->{where} ] }
0a3c5b43 196 : $where);
ff7bb7a1 197 }
0a3c5b43 198
8839560b 199 if (defined $having) {
223aea40 200 $attrs->{having} = (defined $attrs->{having}
8839560b 201 ? { '-and' =>
202 [ map { ref $_ eq 'ARRAY' ? [ -or => $_ ] : $_ }
203 $having, $attrs->{having} ] }
204 : $having);
8839560b 205 }
206
ff7bb7a1 207 $rs = (ref $self)->new($self->result_source, $attrs);
208 }
209 else {
210 $rs = $self;
223aea40 211 $rs->reset;
ff7bb7a1 212 }
0a3c5b43 213 return (wantarray ? $rs->all : $rs);
214}
215
87f0da6a 216=head2 search_literal
217
6009260a 218 my @obj = $rs->search_literal($literal_where_cond, @bind);
219 my $new_rs = $rs->search_literal($literal_where_cond, @bind);
220
221Pass a literal chunk of SQL to be added to the conditional part of the
87f0da6a 222resultset.
6009260a 223
bfab575a 224=cut
fd9f5466 225
6009260a 226sub search_literal {
227 my ($self, $cond, @vals) = @_;
228 my $attrs = (ref $vals[$#vals] eq 'HASH' ? { %{ pop(@vals) } } : {});
229 $attrs->{bind} = [ @{$self->{attrs}{bind}||[]}, @vals ];
230 return $self->search(\$cond, $attrs);
231}
0a3c5b43 232
87c4e602 233=head2 find
234
235=head3 Arguments: (@colvalues) | (\%cols, \%attrs?)
87f0da6a 236
237Finds a row based on its primary key or unique constraint. For example:
238
87f0da6a 239 my $cd = $schema->resultset('CD')->find(5);
240
241Also takes an optional C<key> attribute, to search by a specific key or unique
242constraint. For example:
243
fd9f5466 244 my $cd = $schema->resultset('CD')->find(
87f0da6a 245 {
246 artist => 'Massive Attack',
247 title => 'Mezzanine',
248 },
249 { key => 'artist_title' }
250 );
251
a33df5d4 252See also L</find_or_create> and L</update_or_create>.
253
87f0da6a 254=cut
716b3d29 255
256sub find {
257 my ($self, @vals) = @_;
258 my $attrs = (@vals > 1 && ref $vals[$#vals] eq 'HASH' ? pop(@vals) : {});
87f0da6a 259
701da8c4 260 my @cols = $self->result_source->primary_columns;
87f0da6a 261 if (exists $attrs->{key}) {
701da8c4 262 my %uniq = $self->result_source->unique_constraints;
aa1088bf 263 $self->throw_exception(
264 "Unknown key $attrs->{key} on '" . $self->result_source->name . "'"
265 ) unless exists $uniq{$attrs->{key}};
87f0da6a 266 @cols = @{ $uniq{$attrs->{key}} };
267 }
268 #use Data::Dumper; warn Dumper($attrs, @vals, @cols);
aa1088bf 269 $self->throw_exception(
270 "Can't find unless a primary key or unique constraint is defined"
271 ) unless @cols;
87f0da6a 272
716b3d29 273 my $query;
274 if (ref $vals[0] eq 'HASH') {
01bc091e 275 $query = { %{$vals[0]} };
87f0da6a 276 } elsif (@cols == @vals) {
716b3d29 277 $query = {};
87f0da6a 278 @{$query}{@cols} = @vals;
716b3d29 279 } else {
280 $query = {@vals};
281 }
223aea40 282 foreach my $key (grep { ! m/\./ } keys %$query) {
283 $query->{"$self->{attrs}{alias}.$key"} = delete $query->{$key};
01bc091e 284 }
716b3d29 285 #warn Dumper($query);
8389d433 286
287 if (keys %$attrs) {
288 my $rs = $self->search($query,$attrs);
289 return keys %{$rs->{collapse}} ? $rs->next : $rs->single;
290 } else {
aa1088bf 291 return keys %{$self->{collapse}} ?
292 $self->search($query)->next :
293 $self->single($query);
8389d433 294 }
716b3d29 295}
296
b52e9bf8 297=head2 search_related
298
299 $rs->search_related('relname', $cond?, $attrs?);
300
a33df5d4 301Search the specified relationship. Optionally specify a condition for matching
302records.
303
b52e9bf8 304=cut
305
6aeb9185 306sub search_related {
64acc2bc 307 return shift->related_resultset(shift)->search(@_);
6aeb9185 308}
b52e9bf8 309
bfab575a 310=head2 cursor
ee38fa40 311
bfab575a 312Returns a storage-driven cursor to the given resultset.
ee38fa40 313
314=cut
315
73f58123 316sub cursor {
317 my ($self) = @_;
223aea40 318 my $attrs = { %{$self->{attrs}} };
73f58123 319 return $self->{cursor}
701da8c4 320 ||= $self->result_source->storage->select($self->{from}, $attrs->{select},
73f58123 321 $attrs->{where},$attrs);
322}
323
a04ab285 324=head2 single
325
326Inflates the first result without creating a cursor
327
328=cut
329
330sub single {
223aea40 331 my ($self, $where) = @_;
332 my $attrs = { %{$self->{attrs}} };
333 if ($where) {
a04ab285 334 if (defined $attrs->{where}) {
335 $attrs->{where} = {
223aea40 336 '-and' =>
337 [ map { ref $_ eq 'ARRAY' ? [ -or => $_ ] : $_ }
338 $where, delete $attrs->{where} ]
a04ab285 339 };
340 } else {
223aea40 341 $attrs->{where} = $where;
a04ab285 342 }
343 }
344 my @data = $self->result_source->storage->select_single(
345 $self->{from}, $attrs->{select},
346 $attrs->{where},$attrs);
347 return (@data ? $self->_construct_object(@data) : ());
348}
349
350
87f0da6a 351=head2 search_like
352
a33df5d4 353Perform a search, but use C<LIKE> instead of equality as the condition. Note
354that this is simply a convenience method; you most likely want to use
355L</search> with specific operators.
356
357For more information, see L<DBIx::Class::Manual::Cookbook>.
87f0da6a 358
359=cut
58a4bd18 360
361sub search_like {
223aea40 362 my $class = shift;
363 my $attrs = (@_ > 1 && ref $_[$#_] eq 'HASH' ? pop(@_) : {});
364 my $query = ref $_[0] eq 'HASH' ? { %{shift()} }: {@_};
58a4bd18 365 $query->{$_} = { 'like' => $query->{$_} } for keys %$query;
366 return $class->search($query, { %$attrs });
367}
368
87c4e602 369=head2 slice
370
371=head3 Arguments: ($first, $last)
ee38fa40 372
bfab575a 373Returns a subset of elements from the resultset.
ee38fa40 374
375=cut
376
89c0a5a2 377sub slice {
378 my ($self, $min, $max) = @_;
379 my $attrs = { %{ $self->{attrs} || {} } };
6aeb9185 380 $attrs->{offset} ||= 0;
381 $attrs->{offset} += $min;
89c0a5a2 382 $attrs->{rows} = ($max ? ($max - $min + 1) : 1);
701da8c4 383 my $slice = (ref $self)->new($self->result_source, $attrs);
89c0a5a2 384 return (wantarray ? $slice->all : $slice);
385}
386
87f0da6a 387=head2 next
ee38fa40 388
a33df5d4 389Returns the next element in the resultset (C<undef> is there is none).
390
391Can be used to efficiently iterate over records in the resultset:
392
5e8b1b2a 393 my $rs = $schema->resultset('CD')->search;
a33df5d4 394 while (my $cd = $rs->next) {
395 print $cd->title;
396 }
ee38fa40 397
398=cut
399
89c0a5a2 400sub next {
401 my ($self) = @_;
223aea40 402 if (@{$self->{all_cache} || []}) {
64acc2bc 403 $self->{all_cache_position} ||= 0;
223aea40 404 return $self->{all_cache}->[$self->{all_cache_position}++];
64acc2bc 405 }
3e0e9e27 406 if ($self->{attrs}{cache}) {
0f66a01b 407 $self->{all_cache_position} = 1;
3e0e9e27 408 return ($self->all)[0];
409 }
aa1088bf 410 my @row = (exists $self->{stashed_row} ?
411 @{delete $self->{stashed_row}} :
412 $self->cursor->next
413 );
a953d8d9 414# warn Dumper(\@row); use Data::Dumper;
89c0a5a2 415 return unless (@row);
c7ce65e6 416 return $self->_construct_object(@row);
417}
418
419sub _construct_object {
420 my ($self, @row) = @_;
b3e8ac9b 421 my @as = @{ $self->{attrs}{as} };
223aea40 422
0f66a01b 423 my $info = $self->_collapse_result(\@as, \@row);
223aea40 424
a50bcd52 425 my $new = $self->result_class->inflate_result($self->result_source, @$info);
223aea40 426
33ce49d6 427 $new = $self->{attrs}{record_filter}->($new)
428 if exists $self->{attrs}{record_filter};
429 return $new;
89c0a5a2 430}
431
0f66a01b 432sub _collapse_result {
433 my ($self, $as, $row, $prefix) = @_;
434
435 my %const;
436
437 my @copy = @$row;
5a5bec6c 438 foreach my $this_as (@$as) {
439 my $val = shift @copy;
440 if (defined $prefix) {
441 if ($this_as =~ m/^\Q${prefix}.\E(.+)$/) {
442 my $remain = $1;
223aea40 443 $remain =~ /^(?:(.*)\.)?([^.]+)$/;
5a5bec6c 444 $const{$1||''}{$2} = $val;
445 }
446 } else {
223aea40 447 $this_as =~ /^(?:(.*)\.)?([^.]+)$/;
5a5bec6c 448 $const{$1||''}{$2} = $val;
0f66a01b 449 }
0f66a01b 450 }
451
0f66a01b 452 my $info = [ {}, {} ];
453 foreach my $key (keys %const) {
454 if (length $key) {
455 my $target = $info;
456 my @parts = split(/\./, $key);
457 foreach my $p (@parts) {
458 $target = $target->[1]->{$p} ||= [];
459 }
460 $target->[0] = $const{$key};
461 } else {
462 $info->[0] = $const{$key};
463 }
464 }
465
aa1088bf 466 my @collapse;
467 if (defined $prefix) {
468 @collapse = map {
469 m/^\Q${prefix}.\E(.+)$/ ? ($1) : ()
470 } keys %{$self->{collapse}})
471 } else {
472 @collapse = keys %{$self->{collapse}};
473 );
474
5a5bec6c 475 if (@collapse) {
476 my ($c) = sort { length $a <=> length $b } @collapse;
0f66a01b 477 my $target = $info;
0f66a01b 478 foreach my $p (split(/\./, $c)) {
5a5bec6c 479 $target = $target->[1]->{$p} ||= [];
0f66a01b 480 }
5a5bec6c 481 my $c_prefix = (defined($prefix) ? "${prefix}.${c}" : $c);
482 my @co_key = @{$self->{collapse}{$c_prefix}};
0f66a01b 483 my %co_check = map { ($_, $target->[0]->{$_}); } @co_key;
5a5bec6c 484 my $tree = $self->_collapse_result($as, $row, $c_prefix);
0f66a01b 485 my (@final, @raw);
5a5bec6c 486 while ( !(grep {
aa1088bf 487 !defined($tree->[0]->{$_}) ||
488 $co_check{$_} ne $tree->[0]->{$_}
5a5bec6c 489 } @co_key) ) {
0f66a01b 490 push(@final, $tree);
491 last unless (@raw = $self->cursor->next);
492 $row = $self->{stashed_row} = \@raw;
5a5bec6c 493 $tree = $self->_collapse_result($as, $row, $c_prefix);
494 #warn Data::Dumper::Dumper($tree, $row);
0f66a01b 495 }
223aea40 496 @$target = @final;
0f66a01b 497 }
498
0f66a01b 499 return $info;
500}
501
87c4e602 502=head2 result_source
701da8c4 503
504Returns a reference to the result source for this recordset.
505
506=cut
507
508
bfab575a 509=head2 count
ee38fa40 510
bfab575a 511Performs an SQL C<COUNT> with the same query as the resultset was built
6009260a 512with to find the number of elements. If passed arguments, does a search
513on the resultset and counts the results of that.
ee38fa40 514
bda4c2b8 515Note: When using C<count> with C<group_by>, L<DBIX::Class> emulates C<GROUP BY>
516using C<COUNT( DISTINCT( columns ) )>. Some databases (notably SQLite) do
517not support C<DISTINCT> with multiple columns. If you are using such a
518database, you should only use columns from the main table in your C<group_by>
519clause.
520
ee38fa40 521=cut
522
89c0a5a2 523sub count {
6009260a 524 my $self = shift;
223aea40 525 return $self->search(@_)->count if @_ and defined $_[0];
84e3c114 526 return scalar @{ $self->get_cache } if @{ $self->get_cache };
15c382be 527
84e3c114 528 my $count = $self->_count;
529 return 0 unless $count;
15c382be 530
6aeb9185 531 $count -= $self->{attrs}{offset} if $self->{attrs}{offset};
532 $count = $self->{attrs}{rows} if
223aea40 533 $self->{attrs}{rows} and $self->{attrs}{rows} < $count;
6aeb9185 534 return $count;
89c0a5a2 535}
536
84e3c114 537sub _count { # Separated out so pager can get the full count
538 my $self = shift;
539 my $select = { count => '*' };
540 my $attrs = { %{ $self->{attrs} } };
541 if (my $group_by = delete $attrs->{group_by}) {
542 delete $attrs->{having};
543 my @distinct = (ref $group_by ? @$group_by : ($group_by));
544 # todo: try CONCAT for multi-column pk
545 my @pk = $self->result_source->primary_columns;
546 if (@pk == 1) {
547 foreach my $column (@distinct) {
548 if ($column =~ qr/^(?:\Q$attrs->{alias}.\E)?$pk[0]$/) {
549 @distinct = ($column);
550 last;
551 }
552 }
553 }
554
555 $select = { count => { distinct => \@distinct } };
556 #use Data::Dumper; die Dumper $select;
557 }
558
559 $attrs->{select} = $select;
560 $attrs->{as} = [qw/count/];
561
562 # offset, order by and page are not needed to count. record_filter is cdbi
563 delete $attrs->{$_} for qw/rows offset order_by page pager record_filter/;
564
565 my ($count) = (ref $self)->new($self->result_source, $attrs)->cursor->next;
566 return $count;
567}
568
bfab575a 569=head2 count_literal
6009260a 570
a33df5d4 571Calls L</search_literal> with the passed arguments, then L</count>.
6009260a 572
573=cut
574
575sub count_literal { shift->search_literal(@_)->count; }
576
bfab575a 577=head2 all
ee38fa40 578
bfab575a 579Returns all elements in the resultset. Called implictly if the resultset
580is returned in list context.
ee38fa40 581
582=cut
583
89c0a5a2 584sub all {
585 my ($self) = @_;
223aea40 586 return @{ $self->get_cache } if @{ $self->get_cache };
5a5bec6c 587
588 my @obj;
589
590 if (keys %{$self->{collapse}}) {
591 # Using $self->cursor->all is really just an optimisation.
592 # If we're collapsing has_many prefetches it probably makes
593 # very little difference, and this is cleaner than hacking
594 # _construct_object to survive the approach
5a5bec6c 595 $self->cursor->reset;
479ed423 596 my @row = $self->cursor->next;
597 while (@row) {
5a5bec6c 598 push(@obj, $self->_construct_object(@row));
479ed423 599 @row = (exists $self->{stashed_row}
600 ? @{delete $self->{stashed_row}}
601 : $self->cursor->next);
5a5bec6c 602 }
603 } else {
223aea40 604 @obj = map { $self->_construct_object(@$_) } $self->cursor->all;
64acc2bc 605 }
5a5bec6c 606
223aea40 607 $self->set_cache(\@obj) if $self->{attrs}{cache};
5a5bec6c 608 return @obj;
89c0a5a2 609}
610
bfab575a 611=head2 reset
ee38fa40 612
bfab575a 613Resets the resultset's cursor, so you can iterate through the elements again.
ee38fa40 614
615=cut
616
89c0a5a2 617sub reset {
618 my ($self) = @_;
64acc2bc 619 $self->{all_cache_position} = 0;
73f58123 620 $self->cursor->reset;
89c0a5a2 621 return $self;
622}
623
bfab575a 624=head2 first
ee38fa40 625
bfab575a 626Resets the resultset and returns the first element.
ee38fa40 627
628=cut
629
89c0a5a2 630sub first {
631 return $_[0]->reset->next;
632}
633
87c4e602 634=head2 update
635
636=head3 Arguments: (\%values)
c01ab172 637
a33df5d4 638Sets the specified columns in the resultset to the supplied values.
c01ab172 639
640=cut
641
642sub update {
643 my ($self, $values) = @_;
aa1088bf 644 $self->throw_exception("Values for update must be a hash")
645 unless ref $values eq 'HASH';
701da8c4 646 return $self->result_source->storage->update(
647 $self->result_source->from, $values, $self->{cond});
c01ab172 648}
649
87c4e602 650=head2 update_all
651
652=head3 Arguments: (\%values)
c01ab172 653
a33df5d4 654Fetches all objects and updates them one at a time. Note that C<update_all>
655will run cascade triggers while L</update> will not.
c01ab172 656
657=cut
658
659sub update_all {
660 my ($self, $values) = @_;
aa1088bf 661 $self->throw_exception("Values for update must be a hash")
662 unless ref $values eq 'HASH';
c01ab172 663 foreach my $obj ($self->all) {
664 $obj->set_columns($values)->update;
665 }
666 return 1;
667}
668
bfab575a 669=head2 delete
ee38fa40 670
c01ab172 671Deletes the contents of the resultset from its result source.
ee38fa40 672
673=cut
674
28927b50 675sub delete {
89c0a5a2 676 my ($self) = @_;
ca4b5ab7 677 my $del = {};
7ed3d6dc 678
679 if (!ref($self->{cond})) {
680
681 # No-op. No condition, we're deleting everything
682
683 } elsif (ref $self->{cond} eq 'ARRAY') {
684
ca4b5ab7 685 $del = [ map { my %hash;
686 foreach my $key (keys %{$_}) {
223aea40 687 $key =~ /([^.]+)$/;
ca4b5ab7 688 $hash{$1} = $_->{$key};
689 }; \%hash; } @{$self->{cond}} ];
7ed3d6dc 690
691 } elsif (ref $self->{cond} eq 'HASH') {
692
693 if ((keys %{$self->{cond}})[0] eq '-and') {
694
695 $del->{-and} = [ map { my %hash;
696 foreach my $key (keys %{$_}) {
697 $key =~ /([^.]+)$/;
698 $hash{$1} = $_->{$key};
699 }; \%hash; } @{$self->{cond}{-and}} ];
700
701 } else {
702
703 foreach my $key (keys %{$self->{cond}}) {
223aea40 704 $key =~ /([^.]+)$/;
7ed3d6dc 705 $del->{$1} = $self->{cond}{$key};
706 }
ca4b5ab7 707 }
7ed3d6dc 708 } else {
709 $self->throw_exception(
710 "Can't delete on resultset with condition unless hash or array");
ca4b5ab7 711 }
7ed3d6dc 712
ca4b5ab7 713 $self->result_source->storage->delete($self->result_source->from, $del);
89c0a5a2 714 return 1;
715}
716
c01ab172 717=head2 delete_all
718
a33df5d4 719Fetches all objects and deletes them one at a time. Note that C<delete_all>
720will run cascade triggers while L</delete> will not.
c01ab172 721
722=cut
723
724sub delete_all {
725 my ($self) = @_;
726 $_->delete for $self->all;
727 return 1;
728}
28927b50 729
bfab575a 730=head2 pager
ee38fa40 731
732Returns a L<Data::Page> object for the current resultset. Only makes
a33df5d4 733sense for queries with a C<page> attribute.
ee38fa40 734
735=cut
736
3c5b25c5 737sub pager {
738 my ($self) = @_;
739 my $attrs = $self->{attrs};
aa1088bf 740 $self->throw_exception("Can't create pager for non-paged rs")
741 unless $self->{page};
6aeb9185 742 $attrs->{rows} ||= 10;
6aeb9185 743 return $self->{pager} ||= Data::Page->new(
84e3c114 744 $self->_count, $attrs->{rows}, $self->{page});
3c5b25c5 745}
746
87c4e602 747=head2 page
748
749=head3 Arguments: ($page_num)
ee38fa40 750
bfab575a 751Returns a new resultset for the specified page.
ee38fa40 752
753=cut
754
3c5b25c5 755sub page {
756 my ($self, $page) = @_;
6aeb9185 757 my $attrs = { %{$self->{attrs}} };
3c5b25c5 758 $attrs->{page} = $page;
701da8c4 759 return (ref $self)->new($self->result_source, $attrs);
fea3d045 760}
761
87c4e602 762=head2 new_result
763
764=head3 Arguments: (\%vals)
fea3d045 765
87f0da6a 766Creates a result in the resultset's result class.
fea3d045 767
768=cut
769
770sub new_result {
771 my ($self, $values) = @_;
701da8c4 772 $self->throw_exception( "new_result needs a hash" )
fea3d045 773 unless (ref $values eq 'HASH');
aa1088bf 774 $self->throw_exception(
775 "Can't abstract implicit construct, condition not a hash"
776 ) if ($self->{cond} && !(ref $self->{cond} eq 'HASH'));
fea3d045 777 my %new = %$values;
778 my $alias = $self->{attrs}{alias};
779 foreach my $key (keys %{$self->{cond}||{}}) {
223aea40 780 $new{$1} = $self->{cond}{$key} if ($key =~ m/^(?:\Q${alias}.\E)?([^.]+)$/);
fea3d045 781 }
a50bcd52 782 my $obj = $self->result_class->new(\%new);
701da8c4 783 $obj->result_source($self->result_source) if $obj->can('result_source');
223aea40 784 return $obj;
fea3d045 785}
786
87c4e602 787=head2 create
788
789=head3 Arguments: (\%vals)
fea3d045 790
87f0da6a 791Inserts a record into the resultset and returns the object.
fea3d045 792
a33df5d4 793Effectively a shortcut for C<< ->new_result(\%vals)->insert >>.
fea3d045 794
795=cut
796
797sub create {
798 my ($self, $attrs) = @_;
aa1088bf 799 $self->throw_exception( "create needs a hashref" )
800 unless ref $attrs eq 'HASH';
fea3d045 801 return $self->new_result($attrs)->insert;
3c5b25c5 802}
803
87c4e602 804=head2 find_or_create
805
806=head3 Arguments: (\%vals, \%attrs?)
87f0da6a 807
808 $class->find_or_create({ key => $val, ... });
c2b15ecc 809
fd9f5466 810Searches for a record matching the search condition; if it doesn't find one,
811creates one and returns that instead.
87f0da6a 812
87f0da6a 813 my $cd = $schema->resultset('CD')->find_or_create({
814 cdid => 5,
815 artist => 'Massive Attack',
816 title => 'Mezzanine',
817 year => 2005,
818 });
819
820Also takes an optional C<key> attribute, to search by a specific key or unique
821constraint. For example:
822
823 my $cd = $schema->resultset('CD')->find_or_create(
824 {
825 artist => 'Massive Attack',
826 title => 'Mezzanine',
827 },
828 { key => 'artist_title' }
829 );
830
831See also L</find> and L</update_or_create>.
832
c2b15ecc 833=cut
834
835sub find_or_create {
836 my $self = shift;
87f0da6a 837 my $attrs = (@_ > 1 && ref $_[$#_] eq 'HASH' ? pop(@_) : {});
223aea40 838 my $hash = ref $_[0] eq 'HASH' ? shift : {@_};
87f0da6a 839 my $exists = $self->find($hash, $attrs);
223aea40 840 return defined $exists ? $exists : $self->create($hash);
c2b15ecc 841}
842
87f0da6a 843=head2 update_or_create
844
845 $class->update_or_create({ key => $val, ... });
846
847First, search for an existing row matching one of the unique constraints
848(including the primary key) on the source of this resultset. If a row is
849found, update it with the other given column values. Otherwise, create a new
850row.
851
852Takes an optional C<key> attribute to search on a specific unique constraint.
853For example:
854
855 # In your application
856 my $cd = $schema->resultset('CD')->update_or_create(
857 {
858 artist => 'Massive Attack',
859 title => 'Mezzanine',
860 year => 1998,
861 },
862 { key => 'artist_title' }
863 );
864
865If no C<key> is specified, it searches on all unique constraints defined on the
866source, including the primary key.
867
868If the C<key> is specified as C<primary>, search only on the primary key.
869
a33df5d4 870See also L</find> and L</find_or_create>.
871
87f0da6a 872=cut
873
874sub update_or_create {
875 my $self = shift;
87f0da6a 876 my $attrs = (@_ > 1 && ref $_[$#_] eq 'HASH' ? pop(@_) : {});
223aea40 877 my $hash = ref $_[0] eq 'HASH' ? shift : {@_};
87f0da6a 878
701da8c4 879 my %unique_constraints = $self->result_source->unique_constraints;
87f0da6a 880 my @constraint_names = (exists $attrs->{key}
881 ? ($attrs->{key})
882 : keys %unique_constraints);
883
884 my @unique_hashes;
885 foreach my $name (@constraint_names) {
886 my @unique_cols = @{ $unique_constraints{$name} };
887 my %unique_hash =
888 map { $_ => $hash->{$_} }
889 grep { exists $hash->{$_} }
890 @unique_cols;
891
892 push @unique_hashes, \%unique_hash
893 if (scalar keys %unique_hash == scalar @unique_cols);
894 }
895
87f0da6a 896 if (@unique_hashes) {
223aea40 897 my $row = $self->single(\@unique_hashes);
898 if (defined $row) {
87f0da6a 899 $row->set_columns($hash);
900 $row->update;
223aea40 901 return $row;
87f0da6a 902 }
903 }
904
223aea40 905 return $self->create($hash);
87f0da6a 906}
907
64acc2bc 908=head2 get_cache
909
910Gets the contents of the cache for the resultset.
911
912=cut
913
914sub get_cache {
223aea40 915 shift->{all_cache} || [];
64acc2bc 916}
917
918=head2 set_cache
919
aa1088bf 920Sets the contents of the cache for the resultset. Expects an arrayref
921of objects of the same class as those produced by the resultset.
64acc2bc 922
923=cut
924
925sub set_cache {
926 my ( $self, $data ) = @_;
927 $self->throw_exception("set_cache requires an arrayref")
928 if ref $data ne 'ARRAY';
a50bcd52 929 my $result_class = $self->result_class;
64acc2bc 930 foreach( @$data ) {
aa1088bf 931 $self->throw_exception(
932 "cannot cache object of type '$_', expected '$result_class'"
933 ) if ref $_ ne $result_class;
64acc2bc 934 }
935 $self->{all_cache} = $data;
936}
937
938=head2 clear_cache
939
940Clears the cache for the resultset.
941
942=cut
943
944sub clear_cache {
223aea40 945 shift->set_cache([]);
64acc2bc 946}
947
948=head2 related_resultset
949
950Returns a related resultset for the supplied relationship name.
951
24d67825 952 $artist_rs = $schema->resultset('CD')->related_resultset('Artist');
64acc2bc 953
954=cut
955
956sub related_resultset {
957 my ( $self, $rel, @rest ) = @_;
958 $self->{related_resultsets} ||= {};
223aea40 959 return $self->{related_resultsets}{$rel} ||= do {
960 #warn "fetching related resultset for rel '$rel'";
961 my $rel_obj = $self->result_source->relationship_info($rel);
962 $self->throw_exception(
963 "search_related: result source '" . $self->result_source->name .
964 "' has no such relationship ${rel}")
965 unless $rel_obj; #die Dumper $self->{attrs};
966
967 my $rs = $self->search(undef, { join => $rel });
968 my $alias = defined $rs->{attrs}{seen_join}{$rel}
969 && $rs->{attrs}{seen_join}{$rel} > 1
970 ? join('_', $rel, $rs->{attrs}{seen_join}{$rel})
971 : $rel;
972
64acc2bc 973 $self->result_source->schema->resultset($rel_obj->{class}
974 )->search( undef,
975 { %{$rs->{attrs}},
976 alias => $alias,
223aea40 977 select => undef,
978 as => undef }
979 )->search(@rest);
980 };
64acc2bc 981}
982
701da8c4 983=head2 throw_exception
984
985See Schema's throw_exception
986
987=cut
988
989sub throw_exception {
990 my $self=shift;
991 $self->result_source->schema->throw_exception(@_);
992}
993
40dbc108 994=head1 ATTRIBUTES
076652e8 995
a33df5d4 996The resultset takes various attributes that modify its behavior. Here's an
997overview of them:
bfab575a 998
999=head2 order_by
076652e8 1000
24d67825 1001Which column(s) to order the results by. This is currently passed
1002through directly to SQL, so you can give e.g. C<year DESC> for a
1003descending order on the column `year'.
076652e8 1004
5e8b1b2a 1005=head2 columns
87c4e602 1006
1007=head3 Arguments: (arrayref)
976f3686 1008
a33df5d4 1009Shortcut to request a particular set of columns to be retrieved. Adds
1010C<me.> onto the start of any column without a C<.> in it and sets C<select>
5e8b1b2a 1011from that, then auto-populates C<as> from C<select> as normal. (You may also
1012use the C<cols> attribute, as in earlier versions of DBIC.)
976f3686 1013
87c4e602 1014=head2 include_columns
1015
1016=head3 Arguments: (arrayref)
5ac6a044 1017
1018Shortcut to include additional columns in the returned results - for example
1019
24d67825 1020 $schema->resultset('CD')->search(undef, {
1021 include_columns => ['artist.name'],
1022 join => ['artist']
1023 });
5ac6a044 1024
24d67825 1025would return all CDs and include a 'name' column to the information
1026passed to object inflation
5ac6a044 1027
87c4e602 1028=head2 select
1029
1030=head3 Arguments: (arrayref)
976f3686 1031
4a28c340 1032Indicates which columns should be selected from the storage. You can use
1033column names, or in the case of RDBMS back ends, function or stored procedure
1034names:
1035
24d67825 1036 $rs = $schema->resultset('Employee')->search(undef, {
1037 select => [
1038 'name',
1039 { count => 'employeeid' },
1040 { sum => 'salary' }
1041 ]
1042 });
4a28c340 1043
1044When you use function/stored procedure names and do not supply an C<as>
1045attribute, the column names returned are storage-dependent. E.g. MySQL would
24d67825 1046return a column named C<count(employeeid)> in the above example.
976f3686 1047
87c4e602 1048=head2 as
1049
1050=head3 Arguments: (arrayref)
076652e8 1051
4a28c340 1052Indicates column names for object inflation. This is used in conjunction with
1053C<select>, usually when C<select> contains one or more function or stored
1054procedure names:
1055
24d67825 1056 $rs = $schema->resultset('Employee')->search(undef, {
1057 select => [
1058 'name',
1059 { count => 'employeeid' }
1060 ],
a0638a7b 1061 as => ['name', 'employee_count'],
24d67825 1062 });
4a28c340 1063
24d67825 1064 my $employee = $rs->first(); # get the first Employee
4a28c340 1065
1066If the object against which the search is performed already has an accessor
1067matching a column name specified in C<as>, the value can be retrieved using
1068the accessor as normal:
1069
24d67825 1070 my $name = $employee->name();
4a28c340 1071
1072If on the other hand an accessor does not exist in the object, you need to
1073use C<get_column> instead:
1074
24d67825 1075 my $employee_count = $employee->get_column('employee_count');
4a28c340 1076
1077You can create your own accessors if required - see
1078L<DBIx::Class::Manual::Cookbook> for details.
ee38fa40 1079
bfab575a 1080=head2 join
ee38fa40 1081
a33df5d4 1082Contains a list of relationships that should be joined for this query. For
1083example:
1084
1085 # Get CDs by Nine Inch Nails
1086 my $rs = $schema->resultset('CD')->search(
1087 { 'artist.name' => 'Nine Inch Nails' },
1088 { join => 'artist' }
1089 );
1090
1091Can also contain a hash reference to refer to the other relation's relations.
1092For example:
1093
1094 package MyApp::Schema::Track;
1095 use base qw/DBIx::Class/;
1096 __PACKAGE__->table('track');
1097 __PACKAGE__->add_columns(qw/trackid cd position title/);
1098 __PACKAGE__->set_primary_key('trackid');
1099 __PACKAGE__->belongs_to(cd => 'MyApp::Schema::CD');
1100 1;
1101
1102 # In your application
1103 my $rs = $schema->resultset('Artist')->search(
1104 { 'track.title' => 'Teardrop' },
1105 {
1106 join => { cd => 'track' },
1107 order_by => 'artist.name',
1108 }
1109 );
1110
2cb360cc 1111If the same join is supplied twice, it will be aliased to <rel>_2 (and
1112similarly for a third time). For e.g.
1113
24d67825 1114 my $rs = $schema->resultset('Artist')->search({
1115 'cds.title' => 'Down to Earth',
1116 'cds_2.title' => 'Popular',
1117 }, {
1118 join => [ qw/cds cds/ ],
1119 });
2cb360cc 1120
24d67825 1121will return a set of all artists that have both a cd with title 'Down
1122to Earth' and a cd with title 'Popular'.
2cb360cc 1123
1124If you want to fetch related objects from other tables as well, see C<prefetch>
ae1c90a1 1125below.
ee38fa40 1126
87c4e602 1127=head2 prefetch
1128
1129=head3 Arguments: arrayref/hashref
ee38fa40 1130
ae1c90a1 1131Contains one or more relationships that should be fetched along with the main
bfab575a 1132query (when they are accessed afterwards they will have already been
a33df5d4 1133"prefetched"). This is useful for when you know you will need the related
ae1c90a1 1134objects, because it saves at least one query:
1135
1136 my $rs = $schema->resultset('Tag')->search(
5e8b1b2a 1137 undef,
ae1c90a1 1138 {
1139 prefetch => {
1140 cd => 'artist'
1141 }
1142 }
1143 );
1144
1145The initial search results in SQL like the following:
1146
1147 SELECT tag.*, cd.*, artist.* FROM tag
1148 JOIN cd ON tag.cd = cd.cdid
1149 JOIN artist ON cd.artist = artist.artistid
1150
1151L<DBIx::Class> has no need to go back to the database when we access the
1152C<cd> or C<artist> relationships, which saves us two SQL statements in this
1153case.
1154
2cb360cc 1155Simple prefetches will be joined automatically, so there is no need
1156for a C<join> attribute in the above search. If you're prefetching to
1157depth (e.g. { cd => { artist => 'label' } or similar), you'll need to
1158specify the join as well.
ae1c90a1 1159
1160C<prefetch> can be used with the following relationship types: C<belongs_to>,
2cb360cc 1161C<has_one> (or if you're using C<add_relationship>, any relationship declared
1162with an accessor type of 'single' or 'filter').
ee38fa40 1163
87c4e602 1164=head2 from
1165
1166=head3 Arguments: (arrayref)
ee38fa40 1167
4a28c340 1168The C<from> attribute gives you manual control over the C<FROM> clause of SQL
1169statements generated by L<DBIx::Class>, allowing you to express custom C<JOIN>
1170clauses.
ee38fa40 1171
a33df5d4 1172NOTE: Use this on your own risk. This allows you to shoot off your foot!
4a28c340 1173C<join> will usually do what you need and it is strongly recommended that you
1174avoid using C<from> unless you cannot achieve the desired result using C<join>.
1175
1176In simple terms, C<from> works as follows:
1177
1178 [
1179 { <alias> => <table>, -join-type => 'inner|left|right' }
1180 [] # nested JOIN (optional)
1181 { <table.column> = <foreign_table.foreign_key> }
1182 ]
1183
1184 JOIN
1185 <alias> <table>
1186 [JOIN ...]
1187 ON <table.column> = <foreign_table.foreign_key>
1188
1189An easy way to follow the examples below is to remember the following:
1190
1191 Anything inside "[]" is a JOIN
1192 Anything inside "{}" is a condition for the enclosing JOIN
1193
1194The following examples utilize a "person" table in a family tree application.
1195In order to express parent->child relationships, this table is self-joined:
1196
1197 # Person->belongs_to('father' => 'Person');
1198 # Person->belongs_to('mother' => 'Person');
1199
1200C<from> can be used to nest joins. Here we return all children with a father,
1201then search against all mothers of those children:
1202
1203 $rs = $schema->resultset('Person')->search(
5e8b1b2a 1204 undef,
4a28c340 1205 {
1206 alias => 'mother', # alias columns in accordance with "from"
1207 from => [
1208 { mother => 'person' },
1209 [
1210 [
1211 { child => 'person' },
1212 [
1213 { father => 'person' },
1214 { 'father.person_id' => 'child.father_id' }
1215 ]
1216 ],
1217 { 'mother.person_id' => 'child.mother_id' }
fd9f5466 1218 ],
4a28c340 1219 ]
1220 },
1221 );
1222
1223 # Equivalent SQL:
1224 # SELECT mother.* FROM person mother
1225 # JOIN (
1226 # person child
1227 # JOIN person father
1228 # ON ( father.person_id = child.father_id )
1229 # )
1230 # ON ( mother.person_id = child.mother_id )
1231
1232The type of any join can be controlled manually. To search against only people
1233with a father in the person table, we could explicitly use C<INNER JOIN>:
1234
1235 $rs = $schema->resultset('Person')->search(
5e8b1b2a 1236 undef,
4a28c340 1237 {
1238 alias => 'child', # alias columns in accordance with "from"
1239 from => [
1240 { child => 'person' },
1241 [
1242 { father => 'person', -join-type => 'inner' },
1243 { 'father.id' => 'child.father_id' }
1244 ],
1245 ]
1246 },
1247 );
1248
1249 # Equivalent SQL:
1250 # SELECT child.* FROM person child
1251 # INNER JOIN person father ON child.father_id = father.id
ee38fa40 1252
bfab575a 1253=head2 page
076652e8 1254
a33df5d4 1255For a paged resultset, specifies which page to retrieve. Leave unset
bfab575a 1256for an unpaged resultset.
076652e8 1257
bfab575a 1258=head2 rows
076652e8 1259
4a28c340 1260For a paged resultset, how many rows per page:
1261
1262 rows => 10
1263
1264Can also be used to simulate an SQL C<LIMIT>.
076652e8 1265
87c4e602 1266=head2 group_by
1267
1268=head3 Arguments: (arrayref)
54540863 1269
bda4c2b8 1270A arrayref of columns to group by. Can include columns of joined tables.
54540863 1271
675ce4a6 1272 group_by => [qw/ column1 column2 ... /]
1273
54540863 1274=head2 distinct
1275
a33df5d4 1276Set to 1 to group by all columns.
1277
534ca143 1278=head2 cache
1279
1280Set to 1 to cache search results. This prevents extra SQL queries if you
1281revisit rows in your ResultSet:
1282
1283 my $resultset = $schema->resultset('Artist')->search( undef, { cache => 1 } );
1284
1285 while( my $artist = $resultset->next ) {
1286 ... do stuff ...
1287 }
1288
1289 $rs->first; # without cache, this would issue a query
1290
1291By default, searches are not cached.
1292
a33df5d4 1293For more examples of using these attributes, see
1294L<DBIx::Class::Manual::Cookbook>.
54540863 1295
bfab575a 1296=cut
076652e8 1297
89c0a5a2 12981;