empty update OK even if row is not in database
[dbsrgits/DBIx-Class.git] / t / 60core.t
1 use strict;
2 use warnings;
3
4 use Test::More;
5 use Test::Exception;
6 use Test::Warn;
7 use lib qw(t/lib);
8 use DBICTest;
9 use DBIC::SqlMakerTest;
10
11 my $schema = DBICTest->init_schema();
12
13 eval { require DateTime::Format::SQLite };
14 my $NO_DTFM = $@ ? 1 : 0;
15
16 my @art = $schema->resultset("Artist")->search({ }, { order_by => 'name DESC'});
17
18 is(@art, 3, "Three artists returned");
19
20 my $art = $art[0];
21
22 is($art->name, 'We Are Goth', "Correct order too");
23
24 $art->name('We Are In Rehab');
25
26 is($art->name, 'We Are In Rehab', "Accessor update ok");
27
28 my %dirty = $art->get_dirty_columns();
29 is(scalar(keys(%dirty)), 1, '1 dirty column');
30 ok(grep($_ eq 'name', keys(%dirty)), 'name is dirty');
31
32 is($art->get_column("name"), 'We Are In Rehab', 'And via get_column');
33
34 ok($art->update, 'Update run');
35
36 my %not_dirty = $art->get_dirty_columns();
37 is(scalar(keys(%not_dirty)), 0, 'Nothing is dirty');
38
39 throws_ok ( sub {
40   my $ret = $art->make_column_dirty('name2');
41 }, qr/No such column 'name2'/, 'Failed to make non-existent column dirty');
42
43 $art->make_column_dirty('name');
44 my %fake_dirty = $art->get_dirty_columns();
45 is(scalar(keys(%fake_dirty)), 1, '1 fake dirty column');
46 ok(grep($_ eq 'name', keys(%fake_dirty)), 'name is fake dirty');
47
48 ok($art->update, 'Update run');
49
50 my $record_jp = $schema->resultset("Artist")->search(undef, { join => 'cds' })->search(undef, { prefetch => 'cds' })->next;
51
52 ok($record_jp, "prefetch on same rel okay");
53
54 my $record_fn = $schema->resultset("Artist")->search(undef, { join => 'cds' })->search({'cds.cdid' => '1'}, {join => 'artist_undirected_maps'})->next;
55
56 ok($record_fn, "funny join is okay");
57
58 @art = $schema->resultset("Artist")->search({ name => 'We Are In Rehab' });
59
60 is(@art, 1, "Changed artist returned by search");
61
62 is($art[0]->artistid, 3,'Correct artist too');
63
64 lives_ok (sub { $art->delete }, 'Cascading delete on Ordered has_many works' );  # real test in ordered.t
65
66 @art = $schema->resultset("Artist")->search({ });
67
68 is(@art, 2, 'And then there were two');
69
70 is($art->in_storage, 0, "It knows it's dead");
71
72 lives_ok { $art->update } 'No changes so update should be OK';
73
74 dies_ok ( sub { $art->delete }, "Can't delete twice");
75
76 is($art->name, 'We Are In Rehab', 'But the object is still live');
77
78 $art->insert;
79
80 ok($art->in_storage, "Re-created");
81
82 @art = $schema->resultset("Artist")->search({ });
83
84 is(@art, 3, 'And now there are three again');
85
86 my $new = $schema->resultset("Artist")->create({ artistid => 4 });
87
88 is($new->artistid, 4, 'Create produced record ok');
89
90 @art = $schema->resultset("Artist")->search({ });
91
92 is(@art, 4, "Oh my god! There's four of them!");
93
94 $new->set_column('name' => 'Man With A Fork');
95
96 is($new->name, 'Man With A Fork', 'set_column ok');
97
98 $new->discard_changes;
99
100 ok(!defined $new->name, 'Discard ok');
101
102 $new->name('Man With A Spoon');
103
104 $new->update;
105
106 my $new_again = $schema->resultset("Artist")->find(4);
107
108 is($new_again->name, 'Man With A Spoon', 'Retrieved correctly');
109
110 is($new_again->ID, 'DBICTest::Artist|artist|artistid=4', 'unique object id generated correctly');
111
112 # test that store_column is called once for create() for non sequence columns 
113 {
114   ok(my $artist = $schema->resultset('Artist')->create({name => 'store_column test'}));
115   is($artist->name, 'X store_column test'); # used to be 'X X store...'
116
117   # call store_column even though the column doesn't seem to be dirty
118   $artist->name($artist->name);
119   is($artist->name, 'X X store_column test');
120   ok($artist->is_column_changed('name'), 'changed column marked as dirty');
121
122   $artist->delete;
123 }
124
125 # Test backwards compatibility
126 {
127   my $warnings = '';
128   local $SIG{__WARN__} = sub { $warnings .= $_[0] };
129
130   my $artist_by_hash = $schema->resultset('Artist')->find(artistid => 4);
131   is($artist_by_hash->name, 'Man With A Spoon', 'Retrieved correctly');
132   is($artist_by_hash->ID, 'DBICTest::Artist|artist|artistid=4', 'unique object id generated correctly');
133   like($warnings, qr/deprecated/, 'warned about deprecated find usage');
134 }
135
136 is($schema->resultset("Artist")->count, 4, 'count ok');
137
138 # test find_or_new
139 {
140   my $existing_obj = $schema->resultset('Artist')->find_or_new({
141     artistid => 4,
142   });
143
144   is($existing_obj->name, 'Man With A Spoon', 'find_or_new: found existing artist');
145   ok($existing_obj->in_storage, 'existing artist is in storage');
146
147   my $new_obj = $schema->resultset('Artist')->find_or_new({
148     artistid => 5,
149     name     => 'find_or_new',
150   });
151
152   is($new_obj->name, 'find_or_new', 'find_or_new: instantiated a new artist');
153   is($new_obj->in_storage, 0, 'new artist is not in storage');
154 }
155
156 my $cd = $schema->resultset("CD")->find(1);
157 my %cols = $cd->get_columns;
158
159 is(keys %cols, 6, 'get_columns number of columns ok');
160
161 is($cols{title}, 'Spoonful of bees', 'get_columns values ok');
162
163 %cols = ( title => 'Forkful of bees', year => 2005);
164 $cd->set_columns(\%cols);
165
166 is($cd->title, 'Forkful of bees', 'set_columns ok');
167
168 is($cd->year, 2005, 'set_columns ok');
169
170 $cd->discard_changes;
171
172 # check whether ResultSource->columns returns columns in order originally supplied
173 my @cd = $schema->source("CD")->columns;
174
175 is_deeply( \@cd, [qw/cdid artist title year genreid single_track/], 'column order');
176
177 $cd = $schema->resultset("CD")->search({ title => 'Spoonful of bees' }, { columns => ['title'] })->next;
178 is($cd->title, 'Spoonful of bees', 'subset of columns returned correctly');
179
180 $cd = $schema->resultset("CD")->search(undef, { include_columns => [ 'artist.name' ], join => [ 'artist' ] })->find(1);
181
182 is($cd->title, 'Spoonful of bees', 'Correct CD returned with include');
183 is($cd->get_column('name'), 'Caterwauler McCrae', 'Additional column returned');
184
185 # check if new syntax +columns also works for this
186 $cd = $schema->resultset("CD")->search(undef, { '+columns' => [ 'artist.name' ], join => [ 'artist' ] })->find(1);
187
188 is($cd->title, 'Spoonful of bees', 'Correct CD returned with include');
189 is($cd->get_column('name'), 'Caterwauler McCrae', 'Additional column returned');
190
191 # check if new syntax for +columns select specifiers works for this
192 $cd = $schema->resultset("CD")->search(undef, { '+columns' => [ {artist_name => 'artist.name'} ], join => [ 'artist' ] })->find(1);
193
194 is($cd->title, 'Spoonful of bees', 'Correct CD returned with include');
195 is($cd->get_column('artist_name'), 'Caterwauler McCrae', 'Additional column returned');
196
197 # update_or_insert
198 $new = $schema->resultset("Track")->new( {
199   trackid => 100,
200   cd => 1,
201   title => 'Insert or Update',
202   last_updated_on => '1973-07-19 12:01:02'
203 } );
204 $new->update_or_insert;
205 ok($new->in_storage, 'update_or_insert insert ok');
206
207 # test in update mode
208 $new->title('Insert or Update - updated');
209 $new->update_or_insert;
210 is( $schema->resultset("Track")->find(100)->title, 'Insert or Update - updated', 'update_or_insert update ok');
211
212 # get_inflated_columns w/relation and accessor alias
213 SKIP: {
214     skip "This test requires DateTime::Format::SQLite", 8 if $NO_DTFM;
215
216     isa_ok($new->updated_date, 'DateTime', 'have inflated object via accessor');
217     my %tdata = $new->get_inflated_columns;
218     is($tdata{'trackid'}, 100, 'got id');
219     isa_ok($tdata{'cd'}, 'DBICTest::CD', 'cd is CD object');
220     is($tdata{'cd'}->id, 1, 'cd object is id 1');
221     is(
222         $tdata{'position'},
223         $schema->resultset ('Track')->search ({cd => 1})->count,
224         'Ordered assigned proper position',
225     );
226     is($tdata{'title'}, 'Insert or Update - updated');
227     is($tdata{'last_updated_on'}, '1973-07-19T12:01:02');
228     isa_ok($tdata{'last_updated_on'}, 'DateTime', 'inflated accessored column');
229 }
230
231 throws_ok (sub {
232   $schema->class("Track")->load_components('DoesNotExist');
233 }, qr!Can't locate DBIx/Class/DoesNotExist.pm!, 'exception on nonexisting component');
234
235 is($schema->class("Artist")->field_name_for->{name}, 'artist name', 'mk_classdata usage ok');
236
237 my $search = [ { 'tags.tag' => 'Cheesy' }, { 'tags.tag' => 'Blue' } ];
238
239 my( $or_rs ) = $schema->resultset("CD")->search_rs($search, { join => 'tags',
240                                                   order_by => 'cdid' });
241 is($or_rs->all, 5, 'Joined search with OR returned correct number of rows');
242 is($or_rs->count, 5, 'Search count with OR ok');
243
244 my $collapsed_or_rs = $or_rs->search ({}, { distinct => 1 }); # induce collapse
245 is ($collapsed_or_rs->all, 4, 'Collapsed joined search with OR returned correct number of rows');
246 is ($collapsed_or_rs->count, 4, 'Collapsed search count with OR ok');
247
248 # make sure sure distinct on a grouped rs is warned about
249 my $cd_rs = $schema->resultset ('CD')
250               ->search ({}, { distinct => 1, group_by => 'title' });
251 warnings_exist (sub {
252   $cd_rs->next;
253 }, qr/Useless use of distinct/, 'UUoD warning');
254
255 {
256   my $tcount = $schema->resultset('Track')->search(
257     {},
258     {
259       select => [ qw/position title/ ],
260       distinct => 1,
261     }
262   );
263   is($tcount->count, 13, 'multiple column COUNT DISTINCT ok');
264
265   $tcount = $schema->resultset('Track')->search(
266     {},
267     {
268       columns => [ qw/position title/ ],
269       distinct => 1,
270     }
271   );
272   is($tcount->count, 13, 'multiple column COUNT DISTINCT ok');
273
274   $tcount = $schema->resultset('Track')->search(
275     {},
276     {
277        group_by => [ qw/position title/ ]
278     }
279   );
280   is($tcount->count, 13, 'multiple column COUNT DISTINCT using column syntax ok');  
281 }
282
283 my $tag_rs = $schema->resultset('Tag')->search(
284                [ { 'me.tag' => 'Cheesy' }, { 'me.tag' => 'Blue' } ]);
285
286 my $rel_rs = $tag_rs->search_related('cd');
287
288 is($rel_rs->count, 5, 'Related search ok');
289
290 is($or_rs->next->cdid, $rel_rs->next->cdid, 'Related object ok');
291 $or_rs->reset;
292 $rel_rs->reset;
293
294 my $tag = $schema->resultset('Tag')->search(
295                [ { 'me.tag' => 'Blue' } ], { cols=>[qw/tagid/] } )->next;
296
297 ok($tag->has_column_loaded('tagid'), 'Has tagid loaded');
298 ok(!$tag->has_column_loaded('tag'), 'Has not tag loaded');
299
300 ok($schema->storage(), 'Storage available');
301
302 {
303   my $rs = $schema->resultset("Artist")->search({
304     -and => [
305       artistid => { '>=', 1 },
306       artistid => { '<', 3 }
307     ]
308   });
309
310   $rs->update({ name => 'Test _cond_for_update_delete' });
311
312   my $art;
313
314   $art = $schema->resultset("Artist")->find(1);
315   is($art->name, 'Test _cond_for_update_delete', 'updated first artist name');
316
317   $art = $schema->resultset("Artist")->find(2);
318   is($art->name, 'Test _cond_for_update_delete', 'updated second artist name');
319 }
320
321 # test source_name
322 {
323   # source_name should be set for normal modules
324   is($schema->source('CD')->source_name, 'CD', 'source_name is set to moniker');
325
326   # test the result source that sets source_name explictly
327   ok($schema->source('SourceNameArtists'), 'SourceNameArtists result source exists');
328
329   my @artsn = $schema->resultset('SourceNameArtists')->search({}, { order_by => 'name DESC' });
330   is(@artsn, 4, "Four artists returned");
331   
332   # make sure subclasses that don't set source_name are ok
333   ok($schema->source('ArtistSubclass'), 'ArtistSubclass exists');
334 }
335
336 my $newbook = $schema->resultset( 'Bookmark' )->find(1);
337
338 lives_ok (sub { my $newlink = $newbook->link}, "stringify to false value doesn't cause error");
339
340 # test cascade_delete through many_to_many relations
341 {
342   my $art_del = $schema->resultset("Artist")->find({ artistid => 1 });
343   lives_ok (sub { $art_del->delete }, 'Cascading delete on Ordered has_many works' );  # real test in ordered.t
344   is( $schema->resultset("CD")->search({artist => 1}), 0, 'Cascading through has_many top level.');
345   is( $schema->resultset("CD_to_Producer")->search({cd => 1}), 0, 'Cascading through has_many children.');
346 }
347
348 # test column_info
349 {
350   $schema->source("Artist")->{_columns}{'artistid'} = {};
351   $schema->source("Artist")->column_info_from_storage(1);
352
353   my $typeinfo = $schema->source("Artist")->column_info('artistid');
354   is($typeinfo->{data_type}, 'INTEGER', 'column_info ok');
355   $schema->source("Artist")->column_info('artistid');
356   ok($schema->source("Artist")->{_columns_info_loaded} == 1, 'Columns info flag set');
357 }
358
359 # test source_info
360 {
361   my $expected = {
362     "source_info_key_A" => "source_info_value_A",
363     "source_info_key_B" => "source_info_value_B",
364     "source_info_key_C" => "source_info_value_C",
365   };
366
367   my $sinfo = $schema->source("Artist")->source_info;
368
369   is_deeply($sinfo, $expected, 'source_info data works');
370 }
371
372 # test remove_columns
373 {
374   is_deeply(
375     [$schema->source('CD')->columns],
376     [qw/cdid artist title year genreid single_track/],
377     'initial columns',
378   );
379
380   $schema->source('CD')->remove_columns('coolyear'); #should not delete year
381   is_deeply(
382     [$schema->source('CD')->columns],
383     [qw/cdid artist title year genreid single_track/],
384     'nothing removed when removing a non-existent column',
385   );
386
387   $schema->source('CD')->remove_columns('genreid', 'year');
388   is_deeply(
389     [$schema->source('CD')->columns],
390     [qw/cdid artist title single_track/],
391     'removed two columns',
392   );
393
394   my $priv_columns = $schema->source('CD')->_columns;
395   ok(! exists $priv_columns->{'year'}, 'year purged from _columns');
396   ok(! exists $priv_columns->{'genreid'}, 'genreid purged from _columns');
397 }
398
399 # test get_inflated_columns with objects
400 SKIP: {
401     skip "This test requires DateTime::Format::SQLite", 5 if $NO_DTFM;
402     my $event = $schema->resultset('Event')->search->first;
403     my %edata = $event->get_inflated_columns;
404     is($edata{'id'}, $event->id, 'got id');
405     isa_ok($edata{'starts_at'}, 'DateTime', 'start_at is DateTime object');
406     isa_ok($edata{'created_on'}, 'DateTime', 'create_on DateTime object');
407     is($edata{'starts_at'}, $event->starts_at, 'got start date');
408     is($edata{'created_on'}, $event->created_on, 'got created date');
409 }
410
411 # test resultsource->table return value when setting
412 {
413     my $class = $schema->class('Event');
414     my $table = $class->table($class->table);
415     is($table, $class->table, '->table($table) returns $table');
416 }
417
418 #make sure insert doesn't use set_column
419 {
420   my $en_row = $schema->resultset('Encoded')->new_result({encoded => 'wilma'});
421   is($en_row->encoded, 'amliw', 'new encodes');
422   $en_row->insert;
423   is($en_row->encoded, 'amliw', 'insert does not encode again');
424 }
425
426 #make sure multicreate encoding still works
427 {
428   my $empl_rs = $schema->resultset('Employee');
429
430   my $empl = $empl_rs->create ({
431     name => 'Secret holder',
432     secretkey => {
433       encoded => 'CAN HAZ',
434     },
435   });
436   is($empl->secretkey->encoded, 'ZAH NAC', 'correctly encoding on multicreate');
437
438   my $empl2 = $empl_rs->create ({
439     name => 'Same secret holder',
440     secretkey => {
441       encoded => 'CAN HAZ',
442     },
443   });
444   is($empl2->secretkey->encoded, 'ZAH NAC', 'correctly encoding on preexisting multicreate');
445
446   $empl_rs->create ({
447     name => 'cat1',
448     secretkey => {
449       encoded => 'CHEEZBURGER',
450       keyholders => [
451         {
452           name => 'cat2',
453         },
454         {
455           name => 'cat3',
456         },
457       ],
458     },
459   });
460
461   is($empl_rs->find({name => 'cat1'})->secretkey->encoded, 'REGRUBZEEHC', 'correct secret in database for empl1');
462   is($empl_rs->find({name => 'cat2'})->secretkey->encoded, 'REGRUBZEEHC', 'correct secret in database for empl2');
463   is($empl_rs->find({name => 'cat3'})->secretkey->encoded, 'REGRUBZEEHC', 'correct secret in database for empl3');
464
465 }
466
467 # make sure we got rid of the compat shims
468 SKIP: {
469     skip "Remove in 0.082", 3 if $DBIx::Class::VERSION < 0.082;
470
471     for (qw/compare_relationship_keys pk_depends_on resolve_condition/) {
472       ok (! DBIx::Class::ResultSource->can ($_), "$_ no longer provided by DBIx::Class::ResultSource");
473     }
474 }
475
476 #------------------------------
477 # READ THIS BEFORE "FIXING"
478 #------------------------------
479 #
480 # make sure we got rid of discard_changes mess - this is a mess and a source
481 # of great confusion. Here I simply die if the methods are available, which
482 # is wrong on its own (we *have* to provide some sort of back-compat, even
483 # if with warnings). Here is how I envision things should actually be. Also
484 # note that a lot of the deprecation can be started today (i.e. the switch
485 # from get_from_storage to copy_from_storage). So:
486 #
487 # $row->discard_changes =>
488 #   warning, and delegation to reload_from_storage
489 #
490 # $row->reload_from_storage =>
491 #   does what discard changes did in 0.08 - issues a query to the db
492 #   and repopulates all column slots, regardless of dirty states etc.
493 #
494 # $row->revert_changes =>
495 #   does what discard_changes should have done initially (before it became
496 #   a dual-purpose call). In order to make this work we will have to
497 #   augment $row to carry its own initial-state, much like svn has a
498 #   copy of the current checkout in contrast to cvs.
499 #
500 # my $db_row = $row->get_from_storage =>
501 #   warns and delegates to an improved name copy_from_storage, with the
502 #   same semantics
503 #
504 # my $db_row = $row->copy_from_storage =>
505 #   a much better/descriptive name than get_from_storage
506 #
507 #------------------------------
508 # READ THIS BEFORE "FIXING"
509 #------------------------------
510 #
511 SKIP: {
512     skip "Something needs to be done before 0.09", 2 if $DBIx::Class::VERSION < 0.09;
513
514     my $row = $schema->resultset ('Artist')->next;
515
516     for (qw/discard_changes get_from_storage/) {
517       ok (! $row->can ($_), "$_ needs *some* sort of facelift before 0.09 ships - current state of affairs is unacceptable");
518     }
519 }
520
521 throws_ok { $schema->resultset} qr/resultset\(\) expects a source name/, 'resultset with no argument throws exception';
522
523 done_testing;