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