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