Release 0.08126
[dbsrgits/DBIx-Class.git] / t / prefetch / correlated.t
CommitLineData
4c2b30d6 1use strict;
2use warnings;
3
4use Test::More;
5use Test::Exception;
6use lib qw(t/lib);
7use DBICTest;
8use DBIC::SqlMakerTest;
9
10my $schema = DBICTest->init_schema();
11my $orig_debug = $schema->storage->debug;
12
13my $cdrs = $schema->resultset('CD')->search({ 'me.artist' => { '!=', 2 }});
14
15my $cd_data = { map {
16 $_->cdid => {
17 siblings => $cdrs->search ({ artist => $_->get_column('artist') })->count - 1,
18 track_titles => [ map { $_->title } ($_->tracks->all) ],
19 },
20} ( $cdrs->all ) };
21
22my $queries = 0;
23$schema->storage->debugcb(sub { $queries++; });
24$schema->storage->debug(1);
25
26my $c_rs = $cdrs->search ({}, {
27 prefetch => 'tracks',
28 '+columns' => { sibling_count => $cdrs->search(
29 {
30 'siblings.artist' => { -ident => 'me.artist' },
31 'siblings.cdid' => { '!=' => ['-and', { -ident => 'me.cdid' }, 'bogus condition'] },
32 }, { alias => 'siblings' },
33 )->count_rs->as_query,
34 },
35});
36
37is_same_sql_bind(
38 $c_rs->as_query,
39 '(
40 SELECT me.cdid, me.artist, me.title, me.year, me.genreid, me.single_track,
41 (SELECT COUNT( * )
42 FROM cd siblings
43 WHERE siblings.artist = me.artist
44 AND siblings.cdid != me.cdid
45 AND siblings.cdid != ?
46 AND me.artist != ?
47 ),
48 tracks.trackid, tracks.cd, tracks.position, tracks.title, tracks.last_updated_on, tracks.last_updated_at
49 FROM cd me
50 LEFT JOIN track tracks
51 ON tracks.cd = me.cdid
52 WHERE me.artist != ?
53 ORDER BY tracks.cd
54 )',
55 [
56 [ 'siblings.cdid' => 'bogus condition' ],
57 [ 'me.artist' => 2 ],
58 [ 'me.artist' => 2 ],
59 ],
60 'Expected SQL on correlated realiased subquery'
61);
62
63is_deeply (
64 { map
65 { $_->cdid => {
66 track_titles => [ map { $_->title } ($_->tracks->all) ],
67 siblings => $_->get_column ('sibling_count'),
68 } }
69 $c_rs->all
70 },
71 $cd_data,
72 'Proper information retrieved from correlated subquery'
73);
74
75is ($queries, 1, 'Only 1 query fired to retrieve everything');
76
77$schema->storage->debug($orig_debug);
78$schema->storage->debugcb(undef);
79
80done_testing;