Extended tests to check new syntax
[dbsrgits/DBIx-Class.git] / t / 60core.t
1 use strict;
2 use warnings;  
3
4 use Test::More;
5 use lib qw(t/lib);
6 use DBICTest;
7
8 my $schema = DBICTest->init_schema();
9
10 plan tests => 89;
11
12 eval { require DateTime::Format::MySQL };
13 my $NO_DTFM = $@ ? 1 : 0;
14
15 # figure out if we've got a version of sqlite that is older than 3.2.6, in
16 # which case COUNT(DISTINCT()) doesn't work
17 my $is_broken_sqlite = 0;
18 my ($sqlite_major_ver,$sqlite_minor_ver,$sqlite_patch_ver) =
19     split /\./, $schema->storage->dbh->get_info(18);
20 if( $schema->storage->dbh->get_info(17) eq 'SQLite' &&
21     ( ($sqlite_major_ver < 3) ||
22       ($sqlite_major_ver == 3 && $sqlite_minor_ver < 2) ||
23       ($sqlite_major_ver == 3 && $sqlite_minor_ver == 2 && $sqlite_patch_ver < 6) ) ) {
24     $is_broken_sqlite = 1;
25 }
26
27
28 my @art = $schema->resultset("Artist")->search({ }, { order_by => 'name DESC'});
29
30 cmp_ok(@art, '==', 3, "Three artists returned");
31
32 my $art = $art[0];
33
34 is($art->name, 'We Are Goth', "Correct order too");
35
36 $art->name('We Are In Rehab');
37
38 is($art->name, 'We Are In Rehab', "Accessor update ok");
39
40 my %dirty = $art->get_dirty_columns();
41 cmp_ok(scalar(keys(%dirty)), '==', 1, '1 dirty column');
42 ok(grep($_ eq 'name', keys(%dirty)), 'name is dirty');
43
44 is($art->get_column("name"), 'We Are In Rehab', 'And via get_column');
45
46 ok($art->update, 'Update run');
47
48 my %not_dirty = $art->get_dirty_columns();
49 cmp_ok(scalar(keys(%not_dirty)), '==', 0, 'Nothing is dirty');
50
51 eval {
52   my $ret = $art->make_column_dirty('name2');
53 };
54 ok(defined($@), 'Failed to make non-existent column dirty');
55 $art->make_column_dirty('name');
56 my %fake_dirty = $art->get_dirty_columns();
57 cmp_ok(scalar(keys(%fake_dirty)), '==', 1, '1 fake dirty column');
58 ok(grep($_ eq 'name', keys(%fake_dirty)), 'name is fake dirty');
59
60 my $record_jp = $schema->resultset("Artist")->search(undef, { join => 'cds' })->search(undef, { prefetch => 'cds' })->next;
61
62 ok($record_jp, "prefetch on same rel okay");
63
64 my $record_fn = $schema->resultset("Artist")->search(undef, { join => 'cds' })->search({'cds.cdid' => '1'}, {join => 'artist_undirected_maps'})->next;
65
66 ok($record_fn, "funny join is okay");
67
68 @art = $schema->resultset("Artist")->search({ name => 'We Are In Rehab' });
69
70 cmp_ok(@art, '==', 1, "Changed artist returned by search");
71
72 cmp_ok($art[0]->artistid, '==', 3,'Correct artist too');
73
74 $art->delete;
75
76 @art = $schema->resultset("Artist")->search({ });
77
78 cmp_ok(@art, '==', 2, 'And then there were two');
79
80 ok(!$art->in_storage, "It knows it's dead");
81
82 eval { $art->delete; };
83
84 ok($@, "Can't delete twice: $@");
85
86 is($art->name, 'We Are In Rehab', 'But the object is still live');
87
88 $art->insert;
89
90 ok($art->in_storage, "Re-created");
91
92 @art = $schema->resultset("Artist")->search({ });
93
94 cmp_ok(@art, '==', 3, 'And now there are three again');
95
96 my $new = $schema->resultset("Artist")->create({ artistid => 4 });
97
98 cmp_ok($new->artistid, '==', 4, 'Create produced record ok');
99
100 @art = $schema->resultset("Artist")->search({ });
101
102 cmp_ok(@art, '==', 4, "Oh my god! There's four of them!");
103
104 $new->set_column('name' => 'Man With A Fork');
105
106 is($new->name, 'Man With A Fork', 'set_column ok');
107
108 $new->discard_changes;
109
110 ok(!defined $new->name, 'Discard ok');
111
112 $new->name('Man With A Spoon');
113
114 $new->update;
115
116 my $new_again = $schema->resultset("Artist")->find(4);
117
118 is($new_again->name, 'Man With A Spoon', 'Retrieved correctly');
119
120 is($new_again->ID, 'DBICTest::Artist|artist|artistid=4', 'unique object id generated correctly');
121
122 # Test backwards compatibility
123 {
124   my $warnings = '';
125   local $SIG{__WARN__} = sub { $warnings .= $_[0] };
126
127   my $artist_by_hash = $schema->resultset('Artist')->find(artistid => 4);
128   is($artist_by_hash->name, 'Man With A Spoon', 'Retrieved correctly');
129   is($artist_by_hash->ID, 'DBICTest::Artist|artist|artistid=4', 'unique object id generated correctly');
130   like($warnings, qr/deprecated/, 'warned about deprecated find usage');
131 }
132
133 is($schema->resultset("Artist")->count, 4, 'count ok');
134
135 # test find_or_new
136 {
137   my $existing_obj = $schema->resultset('Artist')->find_or_new({
138     artistid => 4,
139   });
140
141   is($existing_obj->name, 'Man With A Spoon', 'find_or_new: found existing artist');
142   ok($existing_obj->in_storage, 'existing artist is in storage');
143
144   my $new_obj = $schema->resultset('Artist')->find_or_new({
145     artistid => 5,
146     name     => 'find_or_new',
147   });
148
149   is($new_obj->name, 'find_or_new', 'find_or_new: instantiated a new artist');
150   ok(! $new_obj->in_storage, 'new artist is not in storage');
151 }
152
153 my $cd = $schema->resultset("CD")->find(1);
154 my %cols = $cd->get_columns;
155
156 cmp_ok(keys %cols, '==', 5, 'get_columns number of columns ok');
157
158 is($cols{title}, 'Spoonful of bees', 'get_columns values ok');
159
160 %cols = ( title => 'Forkful of bees', year => 2005);
161 $cd->set_columns(\%cols);
162
163 is($cd->title, 'Forkful of bees', 'set_columns ok');
164
165 is($cd->year, 2005, 'set_columns ok');
166
167 $cd->discard_changes;
168
169 # check whether ResultSource->columns returns columns in order originally supplied
170 my @cd = $schema->source("CD")->columns;
171
172 is_deeply( \@cd, [qw/cdid artist title year genreid/], 'column order');
173
174 $cd = $schema->resultset("CD")->search({ title => 'Spoonful of bees' }, { columns => ['title'] })->next;
175 is($cd->title, 'Spoonful of bees', 'subset of columns returned correctly');
176
177 $cd = $schema->resultset("CD")->search(undef, { include_columns => [ 'artist.name' ], join => [ 'artist' ] })->find(1);
178
179 is($cd->title, 'Spoonful of bees', 'Correct CD returned with include');
180 is($cd->get_column('name'), 'Caterwauler McCrae', 'Additional column returned');
181
182 # check if new syntax +columns also works for this
183 $cd = $schema->resultset("CD")->search(undef, { '+columns' => [ 'artist.name' ], join => [ 'artist' ] })->find(1);
184
185 is($cd->title, 'Spoonful of bees', 'Correct CD returned with include');
186 is($cd->get_column('name'), 'Caterwauler McCrae', 'Additional column returned');
187
188 # check if new syntax for +columns select specifiers works for this
189 $cd = $schema->resultset("CD")->search(undef, { '+columns' => [ {artist_name => 'artist.name'} ], join => [ 'artist' ] })->find(1);
190
191 is($cd->title, 'Spoonful of bees', 'Correct CD returned with include');
192 is($cd->get_column('artist_name'), 'Caterwauler McCrae', 'Additional column returned');
193
194 # update_or_insert
195 $new = $schema->resultset("Track")->new( {
196   trackid => 100,
197   cd => 1,
198   position => 4,
199   title => 'Insert or Update',
200   last_updated_on => '1973-07-19 12:01:02'
201 } );
202 $new->update_or_insert;
203 ok($new->in_storage, 'update_or_insert insert ok');
204
205 # test in update mode
206 $new->pos(5);
207 $new->update_or_insert;
208 is( $schema->resultset("Track")->find(100)->pos, 5, 'update_or_insert update ok');
209
210 # get_inflated_columns w/relation and accessor alias
211 SKIP: {
212     skip "This test requires DateTime::Format::MySQL", 8 if $NO_DTFM;
213
214     isa_ok($new->updated_date, 'DateTime', 'have inflated object via accessor');
215     my %tdata = $new->get_inflated_columns;
216     is($tdata{'trackid'}, 100, 'got id');
217     isa_ok($tdata{'cd'}, 'DBICTest::CD', 'cd is CD object');
218     is($tdata{'cd'}->id, 1, 'cd object is id 1');
219     is($tdata{'position'}, 5, 'got position from pos');
220     is($tdata{'title'}, 'Insert or Update');
221     is($tdata{'last_updated_on'}, '1973-07-19T12:01:02');
222     isa_ok($tdata{'last_updated_on'}, 'DateTime', 'inflated accessored column');
223 }
224
225 eval { $schema->class("Track")->load_components('DoesNotExist'); };
226
227 ok $@, $@;
228
229 is($schema->class("Artist")->field_name_for->{name}, 'artist name', 'mk_classdata usage ok');
230
231 my $search = [ { 'tags.tag' => 'Cheesy' }, { 'tags.tag' => 'Blue' } ];
232
233 my( $or_rs ) = $schema->resultset("CD")->search_rs($search, { join => 'tags',
234                                                   order_by => 'cdid' });
235
236 cmp_ok($or_rs->count, '==', 5, 'Search with OR ok');
237
238 my $distinct_rs = $schema->resultset("CD")->search($search, { join => 'tags', distinct => 1 });
239 cmp_ok($distinct_rs->all, '==', 4, 'DISTINCT search with OR ok');
240
241 #SKIP: {
242 #  skip "SQLite < 3.2.6 doesn't understand COUNT(DISTINCT())", 2
243 #    if $is_broken_sqlite;
244
245   my $tcount = $schema->resultset("Track")->search(
246     {},
247     {       
248        select => {count => {distinct => ['position', 'title']}},
249            as => ['count']
250     }
251   );
252   cmp_ok($tcount->next->get_column('count'), '==', 13, 'multiple column COUNT DISTINCT ok');
253
254   $tcount = $schema->resultset("Track")->search(
255     {},
256     {       
257        columns => {count => {count => {distinct => ['position', 'title']}}},
258     }
259   );
260   cmp_ok($tcount->next->get_column('count'), '==', 13, 'multiple column COUNT DISTINCT using column syntax ok');
261
262 #}
263 my $tag_rs = $schema->resultset('Tag')->search(
264                [ { 'me.tag' => 'Cheesy' }, { 'me.tag' => 'Blue' } ]);
265
266 my $rel_rs = $tag_rs->search_related('cd');
267
268 cmp_ok($rel_rs->count, '==', 5, 'Related search ok');
269
270 cmp_ok($or_rs->next->cdid, '==', $rel_rs->next->cdid, 'Related object ok');
271 $or_rs->reset;
272 $rel_rs->reset;
273
274 my $tag = $schema->resultset('Tag')->search(
275                [ { 'me.tag' => 'Blue' } ], { cols=>[qw/tagid/] } )->next;
276
277 cmp_ok($tag->has_column_loaded('tagid'), '==', 1, 'Has tagid loaded');
278 cmp_ok($tag->has_column_loaded('tag'), '==', 0, 'Has not tag  loaded');
279
280 ok($schema->storage(), 'Storage available');
281
282 {
283   my $rs = $schema->resultset("Artist")->search({
284     -and => [
285       artistid => { '>=', 1 },
286       artistid => { '<', 3 }
287     ]
288   });
289
290   $rs->update({ name => 'Test _cond_for_update_delete' });
291
292   my $art;
293
294   $art = $schema->resultset("Artist")->find(1);
295   is($art->name, 'Test _cond_for_update_delete', 'updated first artist name');
296
297   $art = $schema->resultset("Artist")->find(2);
298   is($art->name, 'Test _cond_for_update_delete', 'updated second artist name');
299 }
300
301 # test source_name
302 {
303   # source_name should be set for normal modules
304   is($schema->source('CD')->source_name, 'CD', 'source_name is set to moniker');
305
306   # test the result source that sets source_name explictly
307   ok($schema->source('SourceNameArtists'), 'SourceNameArtists result source exists');
308
309   my @artsn = $schema->resultset('SourceNameArtists')->search({}, { order_by => 'name DESC' });
310   cmp_ok(@artsn, '==', 4, "Four artists returned");
311   
312   # make sure subclasses that don't set source_name are ok
313   ok($schema->source('ArtistSubclass'), 'ArtistSubclass exists');
314 }
315
316 my $newbook = $schema->resultset( 'Bookmark' )->find(1);
317
318 $@ = '';
319 eval {
320 my $newlink = $newbook->link;
321 };
322 ok(!$@, "stringify to false value doesn't cause error");
323
324 # test cascade_delete through many_to_many relations
325 {
326   my $art_del = $schema->resultset("Artist")->find({ artistid => 1 });
327   $art_del->delete;
328   cmp_ok( $schema->resultset("CD")->search({artist => 1}), '==', 0, 'Cascading through has_many top level.');
329   cmp_ok( $schema->resultset("CD_to_Producer")->search({cd => 1}), '==', 0, 'Cascading through has_many children.');
330 }
331
332 # test column_info
333 {
334   $schema->source("Artist")->{_columns}{'artistid'} = {};
335   $schema->source("Artist")->column_info_from_storage(1);
336
337   my $typeinfo = $schema->source("Artist")->column_info('artistid');
338   is($typeinfo->{data_type}, 'INTEGER', 'column_info ok');
339   $schema->source("Artist")->column_info('artistid');
340   ok($schema->source("Artist")->{_columns_info_loaded} == 1, 'Columns info flag set');
341 }
342
343 # test source_info
344 {
345   my $expected = {
346     "source_info_key_A" => "source_info_value_A",
347     "source_info_key_B" => "source_info_value_B",
348     "source_info_key_C" => "source_info_value_C",
349   };
350
351   my $sinfo = $schema->source("Artist")->source_info;
352
353   is_deeply($sinfo, $expected, 'source_info data works');
354 }
355
356 # test remove_columns
357 {
358   is_deeply([$schema->source('CD')->columns], [qw/cdid artist title year genreid/]);
359   $schema->source('CD')->remove_columns('year');
360   is_deeply([$schema->source('CD')->columns], [qw/cdid artist title genreid/]);
361   ok(! exists $schema->source('CD')->_columns->{'year'}, 'year still exists in _columns');
362 }
363
364 # test get_inflated_columns with objects
365 SKIP: {
366     skip "This test requires DateTime::Format::MySQL", 5 if $NO_DTFM;
367     my $event = $schema->resultset('Event')->search->first;
368     my %edata = $event->get_inflated_columns;
369     is($edata{'id'}, $event->id, 'got id');
370     isa_ok($edata{'starts_at'}, 'DateTime', 'start_at is DateTime object');
371     isa_ok($edata{'created_on'}, 'DateTime', 'create_on DateTime object');
372     is($edata{'starts_at'}, $event->starts_at, 'got start date');
373     is($edata{'created_on'}, $event->created_on, 'got created date');
374 }
375
376 # test resultsource->table return value when setting
377 {
378     my $class = $schema->class('Event');
379     diag $class;
380     my $table = $class->table($class->table);
381     is($table, $class->table, '->table($table) returns $table');
382 }