9 use DBIC::SqlMakerTest;
11 my $schema = DBICTest->init_schema();
13 my $rs = $schema->resultset("CD");
18 $rs->search ({}, {columns => ['year'], distinct => 1})->count,
19 'At least one year is the same in rs'
22 my $rs_title = $rs->get_column('title');
23 my $rs_year = $rs->get_column('year');
24 my $max_year = $rs->get_column(\'MAX (year)');
26 my @all_titles = $rs_title->all;
27 cmp_ok(scalar @all_titles, '==', 5, "five titles returned");
30 while (my $r = $rs_title->next) {
31 push @nexted_titles, $r;
34 is_deeply (\@all_titles, \@nexted_titles, 'next works');
36 is_deeply( [ sort $rs_year->func('DISTINCT') ], [ 1997, 1998, 1999, 2001 ], "wantarray context okay");
37 ok ($max_year->next == $rs_year->max, q/get_column (\'FUNC') ok/);
39 cmp_ok($rs_year->max, '==', 2001, "max okay for year");
40 is($rs_title->min, 'Caterwaulin\' Blues', "min okay for title");
42 cmp_ok($rs_year->sum, '==', 9996, "three artists returned");
44 my $rso_year = $rs->search({}, { order_by => 'cdid' })->get_column('year');
45 is($rso_year->next, 1999, "reset okay");
47 is($rso_year->first, 1999, "first okay");
50 is($rso_year->single, 1999, "single okay");
51 }, qr/Query returned more than one row/, 'single warned');
54 # test distinct propagation
56 [sort $rs->search ({}, { distinct => 1 })->get_column ('year')->all],
57 [sort $rs_year->func('distinct')],
58 'distinct => 1 is passed through properly',
61 # test illogical distinct
62 my $dist_rs = $rs->search ({}, {
65 order_by => { -desc => [qw( cdid year )] },
74 ORDER BY MAX(cdid) DESC, year DESC
77 'Correct SQL on external-ordered distinct',
81 $dist_rs->count_rs->as_query,
91 'Correct SQL on count of external-orderdd distinct',
95 $dist_rs->count_rs->next,
103 'Correct direct count',
106 # test +select/+as for single column
107 my $psrs = $schema->resultset('CD')->search({},
109 '+select' => \'MAX(year)',
113 lives_ok(sub { $psrs->get_column('last_year')->next }, '+select/+as additional column "last_year" present (scalar)');
114 dies_ok(sub { $psrs->get_column('noSuchColumn')->next }, '+select/+as nonexistent column throws exception');
116 # test +select/+as for overriding a column
117 $psrs = $schema->resultset('CD')->search({},
119 'select' => \"'The Final Countdown'",
123 is($psrs->get_column('title')->next, 'The Final Countdown', '+select/+as overridden column "title"');
126 # test +select/+as for multiple columns
127 $psrs = $schema->resultset('CD')->search({},
129 '+select' => [ \'LENGTH(title) AS title_length', 'title' ],
130 '+as' => [ 'tlength', 'addedtitle' ]
133 lives_ok(sub { $psrs->get_column('tlength')->next }, '+select/+as multiple additional columns, "tlength" column present');
134 lives_ok(sub { $psrs->get_column('addedtitle')->next }, '+select/+as multiple additional columns, "addedtitle" column present');
136 # test that +select/+as specs do not leak
138 $psrs->get_column('year')->as_query,
139 '(SELECT me.year FROM cd me)',
141 'Correct SQL for get_column/as'
145 $psrs->get_column('addedtitle')->as_query,
146 '(SELECT me.title FROM cd me)',
148 'Correct SQL for get_column/+as col'
152 $psrs->get_column('tlength')->as_query,
153 '(SELECT LENGTH(title) AS title_length FROM cd me)',
155 'Correct SQL for get_column/+as func'
158 # test that order_by over a function forces a subquery
161 [ $psrs->search ({}, { order_by => { -desc => 'title_length' } })->get_column ('title')->all ],
163 "Generic Manufactured Singles",
164 "Come Be Depressed With Us",
165 "Caterwaulin' Blues",
169 'Subquery count induced by aliased ordering function',
173 # test for prefetch not leaking
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' );
181 is ($schema->resultset('BooksInLibrary')->get_column ('price')->sum, 125, 'Sum of a resultset works correctly');
183 # test sum over search_related
184 my $owner = $schema->resultset('Owners')->find ({ name => 'Newton' });
185 ok ($owner->books->count > 1, 'Owner Newton has multiple books');
186 is ($owner->search_related ('books')->get_column ('price')->sum, 60, 'Correctly calculated price of all owned books');
189 # make sure joined/prefetched get_column of a PK dtrt
191 my $j_rs = $rs->search ({}, { join => 'tracks' })->get_column ('cdid');
194 [ sort map { my $c = $rs->next; ( ($c->id) x $c->tracks->count ) } (1 .. $rs->count) ],
195 'join properly explodes amount of rows from get_column',
199 my $p_rs = $rs->search ({}, { prefetch => 'tracks' })->get_column ('cdid');
202 [ sort $rs->get_column ('cdid')->all ],
203 'prefetch properly collapses amount of rows from get_column',
207 my $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'],
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)',
217 'Correct SQL for prefetch/order_by/group_by'
220 # test aggregate on a function (create an extra track on one cd)
222 my $tr_rs = $schema->resultset("Track");
223 $tr_rs->create({ cd => 2, title => 'dealbreaker' });
226 $tr_rs->get_column('cd')->max,
228 "Correct: Max cd in Track is 5"
231 my $track_counts_per_cd_via_group_by = $tr_rs->search({}, {
232 columns => [ 'cd', { cnt => { count => 'trackid', -as => 'cnt' } } ],
234 })->get_column('cnt');
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');
239 sprintf('%0.1f', $track_counts_per_cd_via_group_by->func('avg') ),
241 'Correct avg tracks per cd'
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?"
249 $schema->resultset('CD')->create({ artist => 1, title => 'dealbroker no tracks', year => 2001 });
251 my $rs = $schema->resultset ('CD')->search (
252 { 'artist.name' => { '!=', 'evancarrol' }, 'tracks.trackid' => { '!=', undef } },
254 order_by => 'me.year',
255 join => [qw(artist tracks)],
256 columns => [ 'year', { cnt => { count => 'me.cdid' }} ],
261 'explicitly grouped' => $rs->search_rs({}, { group_by => 'year' }),
262 'implicitly grouped' => $rs->search_rs({}, { distinct => 1 }),
265 for my $type (keys %$rstypes) {
266 is ($rstypes->{$type}->count, 4, "correct cd count with $type column");
269 [ $rstypes->{$type}->get_column ('year')->all ],
270 [qw(1997 1998 1999 2001)],
271 "Getting $type column works",
275 # Why do we test this - we want to make sure that the selector *will* actually make
276 # it to the group_by as per the distinct => 1 contract. Before 0.08251 this situation
277 # would silently drop the group_by entirely, likely ending up with nonsensival results
278 # With the current behavior the user will at least get a nice fat exception from the
279 # RDBMS (or maybe the RDBMS will even decide to handle the situation sensibly...)
280 warnings_exist { is_same_sql_bind(
281 $rstypes->{'implicitly grouped'}->get_column('cnt')->as_query,
283 SELECT COUNT( me.cdid )
286 ON artist.artistid = me.artist
287 LEFT JOIN track tracks
288 ON tracks.cd = me.cdid
289 WHERE artist.name != ? AND tracks.trackid IS NOT NULL
290 GROUP BY COUNT( me.cdid )
291 ORDER BY MIN(me.year)
293 [ [ { dbic_colname => 'artist.name', sqlt_datatype => 'varchar', sqlt_size => 100 }
296 'Expected (though nonsensical) SQL generated on rscol-with-distinct-over-function',
298 \QUse of distinct => 1 while selecting anything other than a column \E
299 \Qdeclared on the primary ResultSource is deprecated\E
300 /x, 'deprecation warning';
303 local $TODO = 'multiplying join leaks through to the count aggregate... this may never actually work';
305 [ $rstypes->{'explicitly grouped'}->get_column ('cnt')->all ],
307 "Get aggregate over group works",