1 BEGIN { do "./t/lib/ANFANG.pm" or die ( $@ || $! ) }
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
13 BEGIN { $ENV{DBIC_SHUFFLE_UNORDERED_RESULTSETS} = 0 }
16 use DBICTest ':DiffSQL';
18 my $schema = DBICTest->init_schema();
20 my $rs = $schema->resultset("CD");
25 $rs->search ({}, {columns => ['year'], distinct => 1})->count,
26 'At least one year is the same in rs'
29 my $rs_title = $rs->get_column('title');
30 my $rs_year = $rs->get_column('year');
31 my $max_year = $rs->get_column(\'MAX (year)');
33 my @all_titles = $rs_title->all;
34 cmp_ok(scalar @all_titles, '==', 5, "five titles returned");
37 while (my $r = $rs_title->next) {
38 push @nexted_titles, $r;
41 is_deeply (\@all_titles, \@nexted_titles, 'next works');
43 is_deeply( [ sort $rs_year->func('DISTINCT') ], [ 1997, 1998, 1999, 2001 ], "wantarray context okay");
44 ok ($max_year->next == $rs_year->max, q/get_column (\'FUNC') ok/);
46 cmp_ok($rs_year->max, '==', 2001, "max okay for year");
47 is($rs_title->min, 'Caterwaulin\' Blues', "min okay for title");
49 cmp_ok($rs_year->sum, '==', 9996, "three artists returned");
52 my $rso_year = $rs->search({}, { order_by => 'cdid' })->get_column('year');
53 is($rso_year->next, 1999, "reset okay");
55 is($rso_year->first, 1999, "first okay");
58 is($rso_year->single, 1999, "single okay");
59 }, qr/Query returned more than one row/, 'single warned');
63 # test distinct propagation
65 [sort $rs->search ({}, { distinct => 1 })->get_column ('year')->all],
66 [sort $rs_year->func('distinct')],
67 'distinct => 1 is passed through properly',
70 # test illogical distinct
71 my $dist_rs = $rs->search ({}, {
74 order_by => { -desc => [qw( cdid year )] },
83 ORDER BY MAX(cdid) DESC, year DESC
86 'Correct SQL on external-ordered distinct',
90 $dist_rs->count_rs->as_query,
100 'Correct SQL on count of external-orderdd distinct',
104 $dist_rs->count_rs->next,
112 'Correct direct count',
115 # test +select/+as for single column
116 my $psrs = $schema->resultset('CD')->search({},
118 '+select' => \'MAX(year)',
122 lives_ok(sub { $psrs->get_column('last_year')->next }, '+select/+as additional column "last_year" present (scalar)');
123 dies_ok(sub { $psrs->get_column('noSuchColumn')->next }, '+select/+as nonexistent column throws exception');
125 # test +select/+as for overriding a column
126 $psrs = $schema->resultset('CD')->search({},
128 'select' => \"'The Final Countdown'",
132 is($psrs->get_column('title')->next, 'The Final Countdown', '+select/+as overridden column "title"');
135 # test +select/+as for multiple columns
136 $psrs = $schema->resultset('CD')->search({},
138 '+select' => [ \'LENGTH(title) AS title_length', 'title' ],
139 '+as' => [ 'tlength', 'addedtitle' ]
142 lives_ok(sub { $psrs->get_column('tlength')->next }, '+select/+as multiple additional columns, "tlength" column present');
143 lives_ok(sub { $psrs->get_column('addedtitle')->next }, '+select/+as multiple additional columns, "addedtitle" column present');
145 # test that +select/+as specs do not leak
147 $psrs->get_column('year')->as_query,
148 '(SELECT me.year FROM cd me)',
150 'Correct SQL for get_column/as'
154 $psrs->get_column('addedtitle')->as_query,
155 '(SELECT me.title FROM cd me)',
157 'Correct SQL for get_column/+as col'
161 $psrs->get_column('tlength')->as_query,
162 '(SELECT LENGTH(title) AS title_length FROM cd me)',
164 'Correct SQL for get_column/+as func'
167 # test that order_by over a function forces a subquery
170 [ $psrs->search ({}, { order_by => { -desc => 'title_length' } })->get_column ('title')->all ],
172 "Generic Manufactured Singles",
173 "Come Be Depressed With Us",
174 "Caterwaulin' Blues",
178 'Subquery count induced by aliased ordering function',
182 # test for prefetch not leaking
184 my $rs = $schema->resultset("CD")->search({}, { prefetch => 'artist' });
185 my $rsc = $rs->get_column('year');
186 is( $rsc->{_parent_resultset}->{attrs}->{prefetch}, undef, 'prefetch wiped' );
190 is ($schema->resultset('BooksInLibrary')->get_column ('price')->sum, 125, 'Sum of a resultset works correctly');
192 # test sum over search_related
193 my $owner = $schema->resultset('Owners')->find ({ name => 'Newton' });
194 ok ($owner->books->count > 1, 'Owner Newton has multiple books');
195 is ($owner->search_related ('books')->get_column ('price')->sum, 60, 'Correctly calculated price of all owned books');
198 # make sure joined/prefetched get_column of a PK dtrt
200 my $j_rs = $rs->search ({}, { join => 'tracks' })->get_column ('cdid');
203 [ sort map { my $c = $rs->next; ( ($c->id) x $c->tracks->count ) } (1 .. $rs->count) ],
204 'join properly explodes amount of rows from get_column',
208 my $p_rs = $rs->search ({}, { prefetch => 'tracks' })->get_column ('cdid');
211 [ sort $rs->get_column ('cdid')->all ],
212 'prefetch properly collapses amount of rows from get_column',
216 my $pob_rs = $rs->search({}, {
217 select => ['me.title', 'tracks.title'],
218 prefetch => 'tracks',
219 order_by => [{-asc => ['position']}],
220 group_by => ['me.title', 'tracks.title'],
223 $pob_rs->get_column("me.title")->as_query,
224 '(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)',
226 'Correct SQL for prefetch/order_by/group_by'
229 # test aggregate on a function (create an extra track on one cd)
231 my $tr_rs = $schema->resultset("Track");
232 $tr_rs->create({ cd => 2, title => 'dealbreaker' });
235 $tr_rs->get_column('cd')->max,
237 "Correct: Max cd in Track is 5"
240 my $track_counts_per_cd_via_group_by = $tr_rs->search({}, {
241 columns => [ 'cd', { cnt => { count => 'trackid', -as => 'cnt' } } ],
243 })->get_column('cnt');
245 is ($track_counts_per_cd_via_group_by->max, 4, 'Correct max tracks per cd');
246 is ($track_counts_per_cd_via_group_by->min, 3, 'Correct min tracks per cd');
248 sprintf('%0.1f', $track_counts_per_cd_via_group_by->func('avg') ),
250 'Correct avg tracks per cd'
254 # test exotic scenarious (create a track-less cd)
255 # "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?"
258 $schema->resultset('CD')->create({ artist => 1, title => 'dealbroker no tracks', year => 2001 });
260 my $yp1 = \[ 'year + ?', 1 ];
262 my $rs = $schema->resultset ('CD')->search (
263 { 'artist.name' => { '!=', 'evancarrol' }, 'tracks.trackid' => { '!=', undef } },
265 order_by => 'me.year',
266 join => [qw(artist tracks)],
269 { cnt => { count => 'me.cdid' } },
270 { year_plus_one => $yp1 },
276 'explicitly grouped' => $rs->search_rs({}, { group_by => [ 'year', $yp1 ] } ),
277 'implicitly grouped' => $rs->search_rs({}, { distinct => 1 }),
280 for my $type (keys %$rstypes) {
281 is ($rstypes->{$type}->count, 4, "correct cd count with $type column");
284 [ $rstypes->{$type}->get_column ('year')->all ],
285 [qw(1997 1998 1999 2001)],
286 "Getting $type column works",
290 # Why do we test this - we want to make sure that the selector *will* actually make
291 # it to the group_by as per the distinct => 1 contract. Before 0.08251 this situation
292 # would silently drop the group_by entirely, likely ending up with nonsensival results
293 # With the current behavior the user will at least get a nice fat exception from the
294 # RDBMS (or maybe the RDBMS will even decide to handle the situation sensibly...)
296 [ cnt => 'COUNT( me.cdid )' ],
297 [ year_plus_one => 'year + ?' => [ {} => 1 ] ],
299 my ($col, $sel_grp_sql, @sel_grp_bind) = @$_;
301 warnings_exist { is_same_sql_bind(
302 $rstypes->{'implicitly grouped'}->get_column($col)->as_query,
307 ON artist.artistid = me.artist
308 LEFT JOIN track tracks
309 ON tracks.cd = me.cdid
310 WHERE artist.name != ? AND tracks.trackid IS NOT NULL
311 GROUP BY $sel_grp_sql
312 ORDER BY MIN(me.year)
316 [ { dbic_colname => 'artist.name', sqlt_datatype => 'varchar', sqlt_size => 100 }
320 'Expected (though nonsensical) SQL generated on rscol-with-distinct-over-function',
322 \QUse of distinct => 1 while selecting anything other than a column \E
323 \Qdeclared on the primary ResultSource is deprecated (you selected '$col')\E
324 /x, 'deprecation warning';
328 local $TODO = 'multiplying join leaks through to the count aggregate... this may never actually work';
330 [ $rstypes->{'explicitly grouped'}->get_column ('cnt')->all ],
332 "Get aggregate over group works",