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