Fix func_rs() and as_subselect_rs() to start behaving as advertised
[dbsrgits/DBIx-Class.git] / t / 88result_set_column.t
CommitLineData
c0329273 1BEGIN { do "./t/lib/ANFANG.pm" or die ( $@ || $! ) }
2
70350518 3use strict;
4e55c3ae 4use warnings;
70350518 5
6use Test::More;
4e55c3ae 7use Test::Warn;
5d1fc7dc 8use Test::Exception;
1b658919 9
10# MASSIVE FIXME - there is a hole in ::RSC / as_subselect_rs
11# losing the order. Needs a rework/extract of the realiaser,
12# and that's a whole another bag of dicks
13BEGIN { $ENV{DBIC_SHUFFLE_UNORDERED_RESULTSETS} = 0 }
14
c0329273 15
a5a7bb73 16use DBICTest ':DiffSQL';
70350518 17
a47e1233 18my $schema = DBICTest->init_schema();
2bb7b40b 19
ee12e25a 20my $rs = $schema->resultset("CD");
21
22cmp_ok (
23 $rs->count,
fb88ca2c 24 '>',
ee12e25a 25 $rs->search ({}, {columns => ['year'], distinct => 1})->count,
26 'At least one year is the same in rs'
27);
2bb7b40b 28
29my $rs_title = $rs->get_column('title');
30my $rs_year = $rs->get_column('year');
20ea4813 31my $max_year = $rs->get_column(\'MAX (year)');
2bb7b40b 32
fb88ca2c 33my @all_titles = $rs_title->all;
34cmp_ok(scalar @all_titles, '==', 5, "five titles returned");
35
36my @nexted_titles;
37while (my $r = $rs_title->next) {
38 push @nexted_titles, $r;
39}
40
41is_deeply (\@all_titles, \@nexted_titles, 'next works');
42
6c5aa1fb 43my @list_ctx;
44warnings_exist {
45 @list_ctx = $rs_year->func_rs('DISTINCT');
46} [qr/\Qfunc_rs() always returns a ResultSet instance regardless of calling context/];
47is( scalar @list_ctx, 1, 'wantarray context does not affect func_rs');
48isa_ok( $list_ctx[0], 'DBIx::Class::ResultSet' );
49isa_ok( scalar( $rs_year->func_rs('DISTINCT') ), 'DBIx::Class::ResultSet' );
5d62876f 50is_deeply( [ sort $rs_year->func('DISTINCT') ], [ 1997, 1998, 1999, 2001 ], "wantarray context okay");
20ea4813 51ok ($max_year->next == $rs_year->max, q/get_column (\'FUNC') ok/);
5d62876f 52
2bb7b40b 53cmp_ok($rs_year->max, '==', 2001, "max okay for year");
54is($rs_title->min, 'Caterwaulin\' Blues', "min okay for title");
55
56cmp_ok($rs_year->sum, '==', 9996, "three artists returned");
57
b74b15b0 58{
59 my $rso_year = $rs->search({}, { order_by => 'cdid' })->get_column('year');
60 is($rso_year->next, 1999, "reset okay");
66521001 61
b74b15b0 62 is($rso_year->first, 1999, "first okay");
66521001 63
b74b15b0 64 warnings_exist (sub {
65 is($rso_year->single, 1999, "single okay");
66 }, qr/Query returned more than one row/, 'single warned');
67}
4e55c3ae 68
ee12e25a 69
70# test distinct propagation
71is_deeply (
6f723769 72 [sort $rs->search ({}, { distinct => 1 })->get_column ('year')->all],
73 [sort $rs_year->func('distinct')],
ee12e25a 74 'distinct => 1 is passed through properly',
75);
76
eb58c082 77# test illogical distinct
78my $dist_rs = $rs->search ({}, {
79 columns => ['year'],
80 distinct => 1,
81 order_by => { -desc => [qw( cdid year )] },
82});
83
84is_same_sql_bind(
85 $dist_rs->as_query,
86 '(
87 SELECT me.year
88 FROM cd me
89 GROUP BY me.year
90 ORDER BY MAX(cdid) DESC, year DESC
91 )',
92 [],
93 'Correct SQL on external-ordered distinct',
94);
95
96is_same_sql_bind(
97 $dist_rs->count_rs->as_query,
98 '(
99 SELECT COUNT( * )
100 FROM (
101 SELECT me.year
102 FROM cd me
103 GROUP BY me.year
104 ) me
105 )',
106 [],
107 'Correct SQL on count of external-orderdd distinct',
108);
109
110is (
111 $dist_rs->count_rs->next,
112 4,
113 'Correct rs-count',
114);
115
116is (
117 $dist_rs->count,
118 4,
119 'Correct direct count',
120);
121
5d1fc7dc 122# test +select/+as for single column
ae515736 123my $psrs = $schema->resultset('CD')->search({},
124 {
472d7df3 125 '+select' => \'MAX(year)',
126 '+as' => 'last_year'
ae515736 127 }
128);
472d7df3 129lives_ok(sub { $psrs->get_column('last_year')->next }, '+select/+as additional column "last_year" present (scalar)');
5d1fc7dc 130dies_ok(sub { $psrs->get_column('noSuchColumn')->next }, '+select/+as nonexistent column throws exception');
ae515736 131
66e33361 132# test +select/+as for overriding a column
133$psrs = $schema->resultset('CD')->search({},
134 {
135 'select' => \"'The Final Countdown'",
136 'as' => 'title'
137 }
138);
139is($psrs->get_column('title')->next, 'The Final Countdown', '+select/+as overridden column "title"');
140
141
5d1fc7dc 142# test +select/+as for multiple columns
ae515736 143$psrs = $schema->resultset('CD')->search({},
144 {
472d7df3 145 '+select' => [ \'LENGTH(title) AS title_length', 'title' ],
146 '+as' => [ 'tlength', 'addedtitle' ]
ae515736 147 }
148);
472d7df3 149lives_ok(sub { $psrs->get_column('tlength')->next }, '+select/+as multiple additional columns, "tlength" column present');
5d1fc7dc 150lives_ok(sub { $psrs->get_column('addedtitle')->next }, '+select/+as multiple additional columns, "addedtitle" column present');
151
66e33361 152# test that +select/+as specs do not leak
153is_same_sql_bind (
154 $psrs->get_column('year')->as_query,
155 '(SELECT me.year FROM cd me)',
156 [],
157 'Correct SQL for get_column/as'
5d1fc7dc 158);
66e33361 159
160is_same_sql_bind (
161 $psrs->get_column('addedtitle')->as_query,
162 '(SELECT me.title FROM cd me)',
163 [],
164 'Correct SQL for get_column/+as col'
165);
166
167is_same_sql_bind (
472d7df3 168 $psrs->get_column('tlength')->as_query,
169 '(SELECT LENGTH(title) AS title_length FROM cd me)',
66e33361 170 [],
171 'Correct SQL for get_column/+as func'
172);
173
472d7df3 174# test that order_by over a function forces a subquery
175lives_ok ( sub {
176 is_deeply (
177 [ $psrs->search ({}, { order_by => { -desc => 'title_length' } })->get_column ('title')->all ],
178 [
179 "Generic Manufactured Singles",
180 "Come Be Depressed With Us",
181 "Caterwaulin' Blues",
182 "Spoonful of bees",
183 "Forkful of bees",
184 ],
185 'Subquery count induced by aliased ordering function',
186 );
187});
188
189# test for prefetch not leaking
3f6cc7e4 190{
191 my $rs = $schema->resultset("CD")->search({}, { prefetch => 'artist' });
192 my $rsc = $rs->get_column('year');
193 is( $rsc->{_parent_resultset}->{attrs}->{prefetch}, undef, 'prefetch wiped' );
194}
cda5e082 195
196# test sum()
197is ($schema->resultset('BooksInLibrary')->get_column ('price')->sum, 125, 'Sum of a resultset works correctly');
198
199# test sum over search_related
200my $owner = $schema->resultset('Owners')->find ({ name => 'Newton' });
201ok ($owner->books->count > 1, 'Owner Newton has multiple books');
202is ($owner->search_related ('books')->get_column ('price')->sum, 60, 'Correctly calculated price of all owned books');
d8dbe471 203
204
205# make sure joined/prefetched get_column of a PK dtrt
d8dbe471 206$rs->reset;
207my $j_rs = $rs->search ({}, { join => 'tracks' })->get_column ('cdid');
208is_deeply (
44976045 209 [ sort $j_rs->all ],
210 [ sort map { my $c = $rs->next; ( ($c->id) x $c->tracks->count ) } (1 .. $rs->count) ],
d8dbe471 211 'join properly explodes amount of rows from get_column',
212);
213
214$rs->reset;
215my $p_rs = $rs->search ({}, { prefetch => 'tracks' })->get_column ('cdid');
216is_deeply (
fb88ca2c 217 [ sort $p_rs->all ],
218 [ sort $rs->get_column ('cdid')->all ],
d8dbe471 219 'prefetch properly collapses amount of rows from get_column',
220);
b7c79955 221
908aa1bb 222$rs->reset;
223my $pob_rs = $rs->search({}, {
224 select => ['me.title', 'tracks.title'],
225 prefetch => 'tracks',
226 order_by => [{-asc => ['position']}],
227 group_by => ['me.title', 'tracks.title'],
228});
229is_same_sql_bind (
230 $pob_rs->get_column("me.title")->as_query,
231 '(SELECT me.title FROM (SELECT me.title, tracks.title FROM cd me LEFT JOIN track tracks ON tracks.cd = me.cdid GROUP BY me.title, tracks.title ORDER BY position ASC) me)',
232 [],
233 'Correct SQL for prefetch/order_by/group_by'
234);
235
aca094b4 236# test aggregate on a function (create an extra track on one cd)
3214abc7 237{
238 my $tr_rs = $schema->resultset("Track");
239 $tr_rs->create({ cd => 2, title => 'dealbreaker' });
240
241 is(
242 $tr_rs->get_column('cd')->max,
243 5,
244 "Correct: Max cd in Track is 5"
245 );
246
247 my $track_counts_per_cd_via_group_by = $tr_rs->search({}, {
248 columns => [ 'cd', { cnt => { count => 'trackid', -as => 'cnt' } } ],
249 group_by => 'cd',
250 })->get_column('cnt');
251
252 is ($track_counts_per_cd_via_group_by->max, 4, 'Correct max tracks per cd');
253 is ($track_counts_per_cd_via_group_by->min, 3, 'Correct min tracks per cd');
254 is (
255 sprintf('%0.1f', $track_counts_per_cd_via_group_by->func('avg') ),
256 '3.2',
257 'Correct avg tracks per cd'
258 );
259}
260
aca094b4 261# test exotic scenarious (create a track-less cd)
262# "How many CDs (not tracks) have been released per year where a given CD has at least one track and the artist isn't evancarroll?"
263{
264
265 $schema->resultset('CD')->create({ artist => 1, title => 'dealbroker no tracks', year => 2001 });
266
885c3dbd 267 my $yp1 = \[ 'year + ?', 1 ];
268
aca094b4 269 my $rs = $schema->resultset ('CD')->search (
270 { 'artist.name' => { '!=', 'evancarrol' }, 'tracks.trackid' => { '!=', undef } },
271 {
272 order_by => 'me.year',
273 join => [qw(artist tracks)],
885c3dbd 274 columns => [
275 'year',
276 { cnt => { count => 'me.cdid' } },
277 { year_plus_one => $yp1 },
278 ],
aca094b4 279 },
280 );
281
282 my $rstypes = {
885c3dbd 283 'explicitly grouped' => $rs->search_rs({}, { group_by => [ 'year', $yp1 ] } ),
aca094b4 284 'implicitly grouped' => $rs->search_rs({}, { distinct => 1 }),
285 };
286
287 for my $type (keys %$rstypes) {
288 is ($rstypes->{$type}->count, 4, "correct cd count with $type column");
289
290 is_deeply (
291 [ $rstypes->{$type}->get_column ('year')->all ],
292 [qw(1997 1998 1999 2001)],
293 "Getting $type column works",
294 );
295 }
296
297 # Why do we test this - we want to make sure that the selector *will* actually make
298 # it to the group_by as per the distinct => 1 contract. Before 0.08251 this situation
299 # would silently drop the group_by entirely, likely ending up with nonsensival results
300 # With the current behavior the user will at least get a nice fat exception from the
301 # RDBMS (or maybe the RDBMS will even decide to handle the situation sensibly...)
885c3dbd 302 for (
303 [ cnt => 'COUNT( me.cdid )' ],
304 [ year_plus_one => 'year + ?' => [ {} => 1 ] ],
305 ) {
306 my ($col, $sel_grp_sql, @sel_grp_bind) = @$_;
307
308 warnings_exist { is_same_sql_bind(
309 $rstypes->{'implicitly grouped'}->get_column($col)->as_query,
310 "(
311 SELECT $sel_grp_sql
312 FROM cd me
313 JOIN artist artist
314 ON artist.artistid = me.artist
315 LEFT JOIN track tracks
316 ON tracks.cd = me.cdid
317 WHERE artist.name != ? AND tracks.trackid IS NOT NULL
318 GROUP BY $sel_grp_sql
319 ORDER BY MIN(me.year)
320 )",
321 [
322 @sel_grp_bind,
323 [ { dbic_colname => 'artist.name', sqlt_datatype => 'varchar', sqlt_size => 100 }
324 => 'evancarrol' ],
325 @sel_grp_bind,
326 ],
327 'Expected (though nonsensical) SQL generated on rscol-with-distinct-over-function',
328 ) } qr/
329 \QUse of distinct => 1 while selecting anything other than a column \E
330 \Qdeclared on the primary ResultSource is deprecated (you selected '$col')\E
331 /x, 'deprecation warning';
332 }
aca094b4 333
334 {
335 local $TODO = 'multiplying join leaks through to the count aggregate... this may never actually work';
336 is_deeply (
337 [ $rstypes->{'explicitly grouped'}->get_column ('cnt')->all ],
338 [qw(1 1 1 2)],
339 "Get aggregate over group works",
340 );
341 }
342}
343
b7c79955 344done_testing;