Two failing multicreate tests (the root cause of castaway's problem)
[dbsrgits/DBIx-Class.git] / t / 96multi_create.t
1 use strict;
2 use warnings;
3
4 use Test::More;
5 use Test::Exception;
6 use lib qw(t/lib);
7 use DBICTest;
8
9 plan tests => 86;
10
11 my $schema = DBICTest->init_schema();
12
13 # simple create + parent (the stuff $rs belongs_to)
14 eval {
15   my $cd = $schema->resultset('CD')->create({
16     artist => { 
17       name => 'Fred Bloggs' 
18     },
19     title => 'Some CD',
20     year => 1996
21   });
22
23   isa_ok($cd, 'DBICTest::CD', 'Created CD object');
24   isa_ok($cd->artist, 'DBICTest::Artist', 'Created related Artist');
25   is($cd->artist->name, 'Fred Bloggs', 'Artist created correctly');
26 };
27 diag $@ if $@;
28
29 # same as above but the child and parent have no values,
30 # except for an explicit parent pk
31 eval {
32   my $bm_rs = $schema->resultset('Bookmark');
33   my $bookmark = $bm_rs->create({
34     link => {
35       id => 66,
36     },
37   });
38
39   isa_ok($bookmark, 'DBICTest::Bookmark', 'Created Bookrmark object');
40   isa_ok($bookmark->link, 'DBICTest::Link', 'Created related Link');
41   is (
42     $bm_rs->search (
43       { 'link.title' => $bookmark->link->title },
44       { join => 'link' },
45     )->count,
46     1,
47     'Bookmark and link made it to the DB',
48   );
49 };
50 diag $@ if $@;
51
52 # create over > 1 levels of has_many create (A => { has_many => { B => has_many => C } } )
53 eval {
54   my $artist = $schema->resultset('Artist')->first;
55   my $cd = $artist->create_related (cds => {
56     title => 'Music to code by',
57     year => 2007,
58     tags => [
59       { 'tag' => 'rock' },
60     ],
61   });
62
63   isa_ok($cd, 'DBICTest::CD', 'Created CD');
64   is($cd->title, 'Music to code by', 'CD created correctly');
65   is($cd->tags->count, 1, 'One tag created for CD');
66   is($cd->tags->first->tag, 'rock', 'Tag created correctly');
67
68 };
69 diag $@ if $@;
70
71 throws_ok (
72   sub {
73     # Create via update - add a new CD <--- THIS SHOULD HAVE NEVER WORKED!
74     $schema->resultset('Artist')->first->update({
75       cds => [
76         { title => 'Yet another CD',
77           year => 2006,
78         },
79       ],
80     });
81   },
82   qr/Recursive update is not supported over relationships of type multi/,
83   'create via update of multi relationships throws an exception'
84 );
85
86 # Create m2m while originating in the linker table
87 eval {
88   my $artist = $schema->resultset('Artist')->first;
89   my $c2p = $schema->resultset('CD_to_Producer')->create ({
90     cd => {
91       artist => $artist,
92       title => 'Bad investment',
93       year => 2008,
94       tracks => [
95         { position => 1, title => 'Just buy' },
96         { position => 2, title => 'Why did we do it' },
97         { position => 3, title => 'Burn baby burn' },
98       ],
99     },
100     producer => {
101       name => 'Lehman Bros.',
102     },
103   });
104
105   isa_ok ($c2p, 'DBICTest::CD_to_Producer', 'Linker object created');
106   my $prod = $schema->resultset ('Producer')->find ({ name => 'Lehman Bros.' });
107   isa_ok ($prod, 'DBICTest::Producer', 'Producer row found');
108   is ($prod->cds->count, 1, 'Producer has one production');
109   my $cd = $prod->cds->first;
110   is ($cd->title, 'Bad investment', 'CD created correctly');
111   is ($cd->tracks->count, 3, 'CD has 3 tracks');
112
113 };
114 diag $@ if $@;
115
116 # create over > 1 levels of might_have (A => { might_have => { B => has_many => C } } )
117 eval {
118   my $artist = $schema->resultset('Artist')->first;
119   my $cd = $schema->resultset('CD')->create ({
120     artist => $artist,
121     title => 'Music to code by at night',
122     year => 2008,
123     tracks => [
124       {
125         position => 1,
126         title => 'Off by one again',
127       },
128       {
129         position => 2,
130         title => 'The dereferencer',
131         cd_single => {
132           artist => $artist,
133           year => 2008,
134           title => 'Was that a null (Single)',
135           tracks => [
136             { title => 'The dereferencer', position => 1 },
137             { title => 'The dereferencer II', position => 2 },
138           ],
139           cd_to_producer => [
140             {
141               producer => {
142                 name => 'K&R',
143               }
144             }
145           ]
146         },
147       },
148     ],
149   });
150
151   isa_ok ($cd, 'DBICTest::CD', 'Main CD object created');
152   is ($cd->title, 'Music to code by at night', 'Correct CD title');
153   is ($cd->tracks->count, 2, 'Two tracks on main CD');
154
155   my ($t1, $t2) = $cd->tracks->all;
156   is ($t1->title, 'Off by one again', 'Correct 1st track name');
157   is ($t1->cd_single, undef, 'No single for 1st track');
158   is ($t2->title, 'The dereferencer', 'Correct 2nd track name');
159   isa_ok ($t2->cd_single, 'DBICTest::CD', 'Created a single for 2nd track');
160
161   my $single = $t2->cd_single;
162   is ($single->tracks->count, 2, 'Two tracks on single CD');
163   is ($single->tracks->find ({ position => 1})->title, 'The dereferencer', 'Correct 1st track title');
164   is ($single->tracks->find ({ position => 2})->title, 'The dereferencer II', 'Correct 2nd track title');
165
166   is ($single->cd_to_producer->count, 1, 'One producer created with the single cd');
167   is ($single->cd_to_producer->first->producer->name, 'K&R', 'Producer name correct');
168 };
169 diag $@ if $@;
170
171 # test might_have again but with a PK == FK in the middle (obviously not specified)
172 eval {
173   my $artist = $schema->resultset('Artist')->first;
174   my $cd = $schema->resultset('CD')->create ({
175     artist => $artist,
176     title => 'Music to code by at twilight',
177     year => 2008,
178     artwork => {
179       images => [
180         { name => 'recursive descent' },
181         { name => 'tail packing' },
182       ],
183     },
184   });
185
186   isa_ok ($cd, 'DBICTest::CD', 'Main CD object created');
187   is ($cd->title, 'Music to code by at twilight', 'Correct CD title');
188   isa_ok ($cd->artwork, 'DBICTest::Artwork', 'Artwork created');
189
190   # this test might look weird, but it failed at one point, keep it there
191   is ($cd->artwork->images->count, 2, 'Correct artwork image count via the new object');
192   is_deeply (
193     [ sort $cd->artwork->images->get_column ('name')->all ],
194     [ 'recursive descent', 'tail packing' ],
195     'Images named correctly in objects',
196   );
197
198
199   my $artwork = $schema->resultset('Artwork')->search (
200     { 'cd.title' => 'Music to code by at twilight' },
201     { join => 'cd' },
202   )->single;
203
204   is ($artwork->images->count, 2, 'Correct artwork image count via a new search');
205
206   is_deeply (
207     [ sort $artwork->images->get_column ('name')->all ],
208     [ 'recursive descent', 'tail packing' ],
209     'Images named correctly after search',
210   );
211 };
212 diag $@ if $@;
213
214 # test might_have again but with just a PK and FK (neither specified) in the mid-table
215 eval {
216   my $cd = $schema->resultset('CD')->first;
217   my $track = $schema->resultset ('Track')->create ({
218     cd => $cd,
219     position => 66,
220     title => 'Black',
221     lyrics => {
222       lyric_versions => [
223         { text => 'The color black' },
224         { text => 'The colour black' },
225       ],
226     },
227   });
228
229   isa_ok ($track, 'DBICTest::Track', 'Main track object created');
230   is ($track->title, 'Black', 'Correct track title');
231   isa_ok ($track->lyrics, 'DBICTest::Lyrics', 'Lyrics created');
232
233   # this test might look weird, but it was failing at one point, keep it there
234   is ($track->lyrics->lyric_versions->count, 2, 'Correct lyric versions count via the new object');
235
236   is_deeply (
237     [ sort $track->lyrics->lyric_versions->get_column ('text')->all ],
238     [ 'The color black', 'The colour black' ],
239     'Lyrics text in objects matches',
240   );
241
242
243   my $lyric = $schema->resultset('Lyrics')->search (
244     { 'track.title' => 'Black' },
245     { join => 'track' },
246   )->single;
247
248   is ($lyric->lyric_versions->count, 2, 'Correct lyric versions count via a new search');
249
250   is_deeply (
251     [ sort $lyric->lyric_versions->get_column ('text')->all ],
252     [ 'The color black', 'The colour black' ],
253     'Lyrics text via search matches',
254   );
255 };
256 diag $@ if $@;
257
258 # nested find_or_create
259 eval {
260   my $newartist2 = $schema->resultset('Artist')->find_or_create({ 
261     name => 'Fred 3',
262     cds => [
263       { 
264         title => 'Noah Act',
265         year => 2007,
266       },
267     ],
268   });
269   is($newartist2->name, 'Fred 3', 'Created new artist with cds via find_or_create');
270 };
271 diag $@ if $@;
272
273 # multiple same level has_many create
274 eval {
275   my $artist2 = $schema->resultset('Artist')->create({
276     name => 'Fred 4',
277     cds => [
278       {
279         title => 'Music to code by',
280         year => 2007,
281       },
282     ],
283     cds_unordered => [
284       {
285         title => 'Music to code by',
286         year => 2007,
287       },
288     ]
289   });
290
291   is($artist2->in_storage, 1, 'artist with duplicate rels inserted okay');
292 };
293 diag $@ if $@;
294
295 # first create_related pass
296 eval {
297         my $artist = $schema->resultset('Artist')->first;
298         
299         my $cd_result = $artist->create_related('cds', {
300         
301                 title => 'TestOneCD1',
302                 year => 2007,
303                 tracks => [
304                 
305                         { position=>111,
306                           title => 'TrackOne',
307                         },
308                         { position=>112,
309                           title => 'TrackTwo',
310                         }
311                 ],
312
313         });
314         
315         ok( $cd_result && ref $cd_result eq 'DBICTest::CD', "Got Good CD Class");
316         ok( $cd_result->title eq "TestOneCD1", "Got Expected Title");
317         
318         my $tracks = $cd_result->tracks;
319         
320         ok( ref $tracks eq "DBIx::Class::ResultSet", "Got Expected Tracks ResultSet");
321         
322         foreach my $track ($tracks->all)
323         {
324                 ok( $track && ref $track eq 'DBICTest::Track', 'Got Expected Track Class');
325         }
326 };
327 diag $@ if $@;
328
329 # second create_related with same arguments
330 eval {
331         my $artist = $schema->resultset('Artist')->first;
332         
333         my $cd_result = $artist->create_related('cds', {
334         
335                 title => 'TestOneCD2',
336                 year => 2007,
337                 tracks => [
338                 
339                         { position=>111,
340                           title => 'TrackOne',
341                         },
342                         { position=>112,
343                           title => 'TrackTwo',
344                         }
345                 ],
346
347     liner_notes => { notes => 'I can haz liner notes?' },
348
349         });
350         
351         ok( $cd_result && ref $cd_result eq 'DBICTest::CD', "Got Good CD Class");
352         ok( $cd_result->title eq "TestOneCD2", "Got Expected Title");
353   ok( $cd_result->notes eq 'I can haz liner notes?', 'Liner notes');
354         
355         my $tracks = $cd_result->tracks;
356         
357         ok( ref $tracks eq "DBIx::Class::ResultSet", "Got Expected Tracks ResultSet");
358         
359         foreach my $track ($tracks->all)
360         {
361                 ok( $track && ref $track eq 'DBICTest::Track', 'Got Expected Track Class');
362         }
363 };
364 diag $@ if $@;
365
366 # create of parents of a record linker table
367 eval {
368   my $cdp = $schema->resultset('CD_to_Producer')->create({
369     cd => { artist => 1, title => 'foo', year => 2000 },
370     producer => { name => 'jorge' }
371   });
372   ok($cdp, 'join table record created ok');
373 };
374 diag $@ if $@;
375
376 #SPECIAL_CASE
377 eval {
378   my $kurt_cobain = { name => 'Kurt Cobain' };
379
380   my $in_utero = $schema->resultset('CD')->new({
381       title => 'In Utero',
382       year  => 1993
383     });
384
385   $kurt_cobain->{cds} = [ $in_utero ];
386
387
388   $schema->resultset('Artist')->populate([ $kurt_cobain ]); # %)
389   $a = $schema->resultset('Artist')->find({name => 'Kurt Cobain'});
390
391   is($a->name, 'Kurt Cobain', 'Artist insertion ok');
392   is($a->cds && $a->cds->first && $a->cds->first->title, 
393                   'In Utero', 'CD insertion ok');
394 };
395 diag $@ if $@;
396
397 #SPECIAL_CASE2
398 eval {
399   my $pink_floyd = { name => 'Pink Floyd' };
400
401   my $the_wall = { title => 'The Wall', year  => 1979 };
402
403   $pink_floyd->{cds} = [ $the_wall ];
404
405
406   $schema->resultset('Artist')->populate([ $pink_floyd ]); # %)
407   $a = $schema->resultset('Artist')->find({name => 'Pink Floyd'});
408
409   is($a->name, 'Pink Floyd', 'Artist insertion ok');
410   is($a->cds && $a->cds->first->title, 'The Wall', 'CD insertion ok');
411 };
412 diag $@ if $@;
413
414 ## Create foreign key col obj including PK
415 ## See test 20 in 66relationships.t
416 eval {
417   my $new_cd_hashref = { 
418     cdid => 27, 
419     title => 'Boogie Woogie', 
420     year => '2007', 
421     artist => { artistid => 17, name => 'king luke' }
422   };
423
424   my $cd = $schema->resultset("CD")->find(1);
425
426   is($cd->artist->id, 1, 'rel okay');
427
428   my $new_cd = $schema->resultset("CD")->create($new_cd_hashref);
429   is($new_cd->artist->id, 17, 'new id retained okay');
430 };
431 diag $@ if $@;
432
433 eval {
434         $schema->resultset("CD")->create({ 
435               cdid => 28, 
436               title => 'Boogie Wiggle', 
437               year => '2007', 
438               artist => { artistid => 18, name => 'larry' }
439              });
440 };
441 is($@, '', 'new cd created without clash on related artist');
442
443 # Make sure exceptions from errors in created rels propogate
444 eval {
445     my $t = $schema->resultset("Track")->new({ cd => { artist => undef } });
446     #$t->cd($t->new_related('cd', { artist => undef } ) );
447     #$t->{_rel_in_storage} = 0;
448     $t->insert;
449 };
450 like($@, qr/cd.artist may not be NULL/, "Exception propogated properly");
451
452 # Test multi create over many_to_many
453 eval {
454   $schema->resultset('CD')->create ({
455     artist => {
456       name => 'larry', # should already exist
457     },
458     title => 'Warble Marble',
459     year => '2009',
460     cd_to_producer => [
461       { producer => { name => 'Cowboy Neal' } },
462     ],
463   });
464
465   my $m2m_cd = $schema->resultset('CD')->search ({ title => 'Warble Marble'});
466   is ($m2m_cd->count, 1, 'One CD row created via M2M create');
467   is ($m2m_cd->first->producers->count, 1, 'CD row created with one producer');
468   is ($m2m_cd->first->producers->first->name, 'Cowboy Neal', 'Correct producer row created');
469 };
470
471 # and some insane multicreate 
472 # (should work, despite the fact that no one will probably use it this way)
473
474 # first count how many rows do we initially have
475 my $counts;
476 $counts->{$_} = $schema->resultset($_)->count for qw/Artist CD Genre Producer Tag/;
477
478 # do the crazy create
479 eval {
480   $schema->resultset('CD')->create ({
481     artist => {
482       name => 'james',
483     },
484     title => 'Greatest hits 1',
485     year => '2012',
486     genre => {
487       name => '"Greatest" collections',
488     },
489     tags => [
490       { tag => 'A' },
491       { tag => 'B' },
492     ],
493     cd_to_producer => [
494       {
495         producer => {
496           name => 'bob',
497           producer_to_cd => [
498             {
499               cd => { 
500                 artist => {
501                   name => 'lars',
502                   cds => [
503                     {
504                       title => 'Greatest hits 2',
505                       year => 2012,
506                       genre => {
507                         name => '"Greatest" collections',
508                       },
509                       tags => [
510                         { tag => 'A' },
511                         { tag => 'B' },
512                       ],
513                       # This cd is created via artist so it doesn't know about producers
514                       cd_to_producer => [
515                         # if we specify 'bob' here things bomb
516                         # as the producer attached to Greatest Hits 1 is
517                         # already created, but not yet inserted.
518                         # Maybe this can be fixed, but things are hairy
519                         # enough already.
520                         #
521                         #{ producer => { name => 'bob' } },
522                         { producer => { name => 'paul' } },
523                         { producer => {
524                           name => 'flemming',
525                           producer_to_cd => [
526                             { cd => {
527                               artist => {
528                                 name => 'kirk',
529                                 cds => [
530                                   {
531                                     title => 'Greatest hits 3',
532                                     year => 2012,
533                                     genre => {
534                                       name => '"Greatest" collections',
535                                     },
536                                     tags => [
537                                       { tag => 'A' },
538                                       { tag => 'B' },
539                                     ],
540                                   },
541                                   {
542                                     title => 'Greatest hits 4',
543                                     year => 2012,
544                                     genre => {
545                                       name => '"Greatest" collections2',
546                                     },
547                                     tags => [
548                                       { tag => 'A' },
549                                       { tag => 'B' },
550                                     ],
551                                   },
552                                 ],
553                               },
554                               title => 'Greatest hits 5',
555                               year => 2013,
556                               genre => {
557                                 name => '"Greatest" collections2',
558                               },
559                             }},
560                           ],
561                         }},
562                       ],
563                     },
564                   ],
565                 },
566                 title => 'Greatest hits 6',
567                 year => 2012,
568                 genre => {
569                   name => '"Greatest" collections',
570                 },
571                 tags => [
572                   { tag => 'A' },
573                   { tag => 'B' },
574                 ],
575               },
576             },
577             {
578               cd => { 
579                 artist => {
580                   name => 'lars',    # should already exist
581                   # even though the artist 'name' is not uniquely constrained
582                   # find_or_create will arguably DWIM 
583                 },
584                 title => 'Greatest hits 7',
585                 year => 2013,
586               },
587             },
588           ],
589         },
590       },
591     ],
592   });
593
594   is ($schema->resultset ('Artist')->count, $counts->{Artist} + 3, '3 new artists created');
595   is ($schema->resultset ('Genre')->count, $counts->{Genre} + 2, '2 additional genres created');
596   is ($schema->resultset ('Producer')->count, $counts->{Producer} + 3, '3 new producer');
597   is ($schema->resultset ('CD')->count, $counts->{CD} + 7, '7 new CDs');
598   is ($schema->resultset ('Tag')->count, $counts->{Tag} + 10, '10 new Tags');
599
600   my $cd_rs = $schema->resultset ('CD')
601     ->search ({ title => { -like => 'Greatest hits %' }}, { order_by => 'title'} );
602   is ($cd_rs->count, 7, '7 greatest hits created');
603
604   my $cds_2012 = $cd_rs->search ({ year => 2012});
605   is ($cds_2012->count, 5, '5 CDs created in 2012');
606
607   is (
608     $cds_2012->search(
609       { 'tags.tag' => { -in => [qw/A B/] } },
610       { join => 'tags', group_by => 'me.cdid' }
611     ),
612     5,
613     'All 10 tags were pairwise distributed between 5 year-2012 CDs'
614   );
615
616   my $paul_prod = $cd_rs->search (
617     { 'producer.name' => 'paul'},
618     { join => { cd_to_producer => 'producer' } }
619   );
620   is ($paul_prod->count, 1, 'Paul had 1 production');
621   my $pauls_cd = $paul_prod->single;
622   is ($pauls_cd->cd_to_producer->count, 2, 'Paul had one co-producer');
623   is (
624     $pauls_cd->search_related ('cd_to_producer',
625       { 'producer.name' => 'flemming'},
626       { join => 'producer' }
627     )->count,
628     1,
629     'The second producer is flemming',
630   );
631
632   my $kirk_cds = $cd_rs->search ({ 'artist.name' => 'kirk' }, { join => 'artist' });
633   is ($kirk_cds, 3, 'Kirk had 3 CDs');
634   is (
635     $kirk_cds->search (
636       { 'cd_to_producer.cd' => { '!=', undef } },
637       { join => 'cd_to_producer' },
638     ),
639     1,
640     'Kirk had a producer only on one cd',
641   );
642
643   my $lars_cds = $cd_rs->search ({ 'artist.name' => 'lars' }, { join => 'artist' });
644   is ($lars_cds->count, 3, 'Lars had 3 CDs');
645   is (
646     $lars_cds->search (
647       { 'cd_to_producer.cd' => undef },
648       { join => 'cd_to_producer' },
649     ),
650     0,
651     'Lars always had a producer',
652   );
653   is (
654     $lars_cds->search_related ('cd_to_producer',
655       { 'producer.name' => 'flemming'},
656       { join => 'producer' }
657     )->count,
658     1,
659     'Lars produced 1 CD with flemming',
660   );
661   is (
662     $lars_cds->search_related ('cd_to_producer',
663       { 'producer.name' => 'bob'},
664       { join => 'producer' }
665     )->count,
666     2,
667     'Lars produced 2 CDs with bob',
668   );
669
670   my $bob_prod = $cd_rs->search (
671     { 'producer.name' => 'bob'},
672     { join => { cd_to_producer => 'producer' } }
673   );
674   is ($bob_prod->count, 3, 'Bob produced a total of 3 CDs');
675
676   is (
677     $bob_prod->search ({ 'artist.name' => 'james' }, { join => 'artist' })->count,
678     1,
679     "Bob produced james' only CD",
680   );
681 };
682 diag $@ if $@;
683
684 1;