de6e9361e379c71a32652023b2f668cfe3bf941a
[dbsrgits/DBIx-Class.git] / t / prefetch / lazy_cursor.t
1 use strict;
2 use warnings;
3
4 use Test::More;
5 use Test::Warn;
6 use Test::Exception;
7 use lib qw(t/lib);
8 use DBICTest;
9
10 my $schema = DBICTest->init_schema();
11
12 my $rs = $schema->resultset('Artist')->search({}, {
13   select => 'artistid',
14   prefetch => { cds => 'tracks' },
15 });
16
17 my $initial_artists_cnt = $rs->count;
18
19 # create one extra artist with just one cd with just one track
20 # and then an artist with nothing at all
21 # the implicit order by me.artistid will get them back in correct order
22 $rs->create({
23   name => 'foo',
24   cds => [{
25     year => 2012,
26     title => 'foocd',
27     tracks => [{
28       title => 'footrack',
29     }]
30   }],
31 });
32 $rs->create({ name => 'bar' });
33 $rs->create({ name => 'baz' });
34
35 # make sure we are reentrant, and also check with explicit order_by
36 for (undef, undef, 'me.artistid') {
37   $rs = $rs->search({}, { order_by => $_ }) if $_;
38
39   for (1 .. $initial_artists_cnt) {
40     is ($rs->next->artistid, $_, 'Default fixture artists in order') || exit;
41   }
42
43   my $foo_artist = $rs->next;
44   is ($foo_artist->cds->next->tracks->next->title, 'footrack', 'Right track');
45
46   is (
47     [$rs->cursor->next]->[0],
48     $initial_artists_cnt + 3,
49     'Very last artist still on the cursor'
50   );
51
52   is_deeply ([$rs->cursor->next], [], 'Nothing else left');
53
54   is ($rs->next->artistid, $initial_artists_cnt + 2, 'Row stashed in resultset still accessible');
55   is ($rs->next, undef, 'Nothing left in resultset either');
56
57   $rs->reset;
58 }
59
60 $rs->next;
61
62 my @objs = $rs->all;
63 is (@objs, $initial_artists_cnt + 3, '->all resets everything correctly');
64 is ( ($rs->cursor->next)[0], 1, 'Cursor auto-rewound after all()');
65 is ($rs->{_stashed_rows}, undef, 'Nothing else left in $rs stash');
66
67 my $unordered_rs = $rs->search({}, { order_by => 'cds.title' });
68
69 warnings_exist {
70   ok ($unordered_rs->next, 'got row 1');
71 } qr/performed an eager cursor slurp underneath/, 'Warned on auto-eager cursor';
72
73 is_deeply ([$unordered_rs->cursor->next], [], 'Nothing left on cursor, eager slurp');
74 ok ($unordered_rs->next, "got row $_")  for (2 .. $initial_artists_cnt + 3);
75 is ($unordered_rs->next, undef, 'End of RS reached');
76 is ($unordered_rs->next, undef, 'End of RS not lost');
77
78 {
79   my $non_uniquely_ordered_constrained = $schema->resultset('CD')->search(
80     { artist => 1 },
81     { order_by => [qw( me.genreid me.title me.year )], prefetch => 'tracks' },
82   );
83
84   isa_ok ($non_uniquely_ordered_constrained->next, 'DBICTest::CD' );
85
86   ok( defined $non_uniquely_ordered_constrained->cursor->next, 'Cursor not exhausted' );
87 }
88
89 done_testing;