Extend might_have test with ideas from zby
[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 => 89;
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   my $art_obj = $cd->artwork;
192   ok ($art_obj->has_column_loaded ('cd_id'), 'PK/FK present on artwork object');
193   is ($art_obj->images->count, 2, 'Correct artwork image count via the new object');
194   is_deeply (
195     [ sort $art_obj->images->get_column ('name')->all ],
196     [ 'recursive descent', 'tail packing' ],
197     'Images named correctly in objects',
198   );
199
200
201   my $artwork = $schema->resultset('Artwork')->search (
202     { 'cd.title' => 'Music to code by at twilight' },
203     { join => 'cd' },
204   )->single;
205
206   is ($artwork->images->count, 2, 'Correct artwork image count via a new search');
207
208   is_deeply (
209     [ sort $artwork->images->get_column ('name')->all ],
210     [ 'recursive descent', 'tail packing' ],
211     'Images named correctly after search',
212   );
213 };
214 diag $@ if $@;
215
216 # test might_have again but with just a PK and FK (neither specified) in the mid-table
217 eval {
218   my $cd = $schema->resultset('CD')->first;
219   my $track = $schema->resultset ('Track')->create ({
220     cd => $cd,
221     position => 66,
222     title => 'Black',
223     lyrics => {
224       lyric_versions => [
225         { text => 'The color black' },
226         { text => 'The colour black' },
227       ],
228     },
229   });
230
231   isa_ok ($track, 'DBICTest::Track', 'Main track object created');
232   is ($track->title, 'Black', 'Correct track title');
233   isa_ok ($track->lyrics, 'DBICTest::Lyrics', 'Lyrics created');
234
235   # this test might look weird, but it was failing at one point, keep it there
236   my $lyric_obj = $track->lyrics;
237   ok ($lyric_obj->has_column_loaded ('lyric_id'), 'PK present on lyric object');
238   ok ($lyric_obj->has_column_loaded ('track_id'), 'FK present on lyric object');
239   is ($lyric_obj->lyric_versions->count, 2, 'Correct lyric versions count via the new object');
240   is_deeply (
241     [ sort $lyric_obj->lyric_versions->get_column ('text')->all ],
242     [ 'The color black', 'The colour black' ],
243     'Lyrics text in objects matches',
244   );
245
246
247   my $lyric = $schema->resultset('Lyrics')->search (
248     { 'track.title' => 'Black' },
249     { join => 'track' },
250   )->single;
251
252   is ($lyric->lyric_versions->count, 2, 'Correct lyric versions count via a new search');
253
254   is_deeply (
255     [ sort $lyric->lyric_versions->get_column ('text')->all ],
256     [ 'The color black', 'The colour black' ],
257     'Lyrics text via search matches',
258   );
259 };
260 diag $@ if $@;
261
262 # nested find_or_create
263 eval {
264   my $newartist2 = $schema->resultset('Artist')->find_or_create({ 
265     name => 'Fred 3',
266     cds => [
267       { 
268         title => 'Noah Act',
269         year => 2007,
270       },
271     ],
272   });
273   is($newartist2->name, 'Fred 3', 'Created new artist with cds via find_or_create');
274 };
275 diag $@ if $@;
276
277 # multiple same level has_many create
278 eval {
279   my $artist2 = $schema->resultset('Artist')->create({
280     name => 'Fred 4',
281     cds => [
282       {
283         title => 'Music to code by',
284         year => 2007,
285       },
286     ],
287     cds_unordered => [
288       {
289         title => 'Music to code by',
290         year => 2007,
291       },
292     ]
293   });
294
295   is($artist2->in_storage, 1, 'artist with duplicate rels inserted okay');
296 };
297 diag $@ if $@;
298
299 # first create_related pass
300 eval {
301         my $artist = $schema->resultset('Artist')->first;
302         
303         my $cd_result = $artist->create_related('cds', {
304         
305                 title => 'TestOneCD1',
306                 year => 2007,
307                 tracks => [
308                 
309                         { position=>111,
310                           title => 'TrackOne',
311                         },
312                         { position=>112,
313                           title => 'TrackTwo',
314                         }
315                 ],
316
317         });
318         
319         ok( $cd_result && ref $cd_result eq 'DBICTest::CD', "Got Good CD Class");
320         ok( $cd_result->title eq "TestOneCD1", "Got Expected Title");
321         
322         my $tracks = $cd_result->tracks;
323         
324         ok( ref $tracks eq "DBIx::Class::ResultSet", "Got Expected Tracks ResultSet");
325         
326         foreach my $track ($tracks->all)
327         {
328                 ok( $track && ref $track eq 'DBICTest::Track', 'Got Expected Track Class');
329         }
330 };
331 diag $@ if $@;
332
333 # second create_related with same arguments
334 eval {
335         my $artist = $schema->resultset('Artist')->first;
336         
337         my $cd_result = $artist->create_related('cds', {
338         
339                 title => 'TestOneCD2',
340                 year => 2007,
341                 tracks => [
342                 
343                         { position=>111,
344                           title => 'TrackOne',
345                         },
346                         { position=>112,
347                           title => 'TrackTwo',
348                         }
349                 ],
350
351     liner_notes => { notes => 'I can haz liner notes?' },
352
353         });
354         
355         ok( $cd_result && ref $cd_result eq 'DBICTest::CD', "Got Good CD Class");
356         ok( $cd_result->title eq "TestOneCD2", "Got Expected Title");
357   ok( $cd_result->notes eq 'I can haz liner notes?', 'Liner notes');
358         
359         my $tracks = $cd_result->tracks;
360         
361         ok( ref $tracks eq "DBIx::Class::ResultSet", "Got Expected Tracks ResultSet");
362         
363         foreach my $track ($tracks->all)
364         {
365                 ok( $track && ref $track eq 'DBICTest::Track', 'Got Expected Track Class');
366         }
367 };
368 diag $@ if $@;
369
370 # create of parents of a record linker table
371 eval {
372   my $cdp = $schema->resultset('CD_to_Producer')->create({
373     cd => { artist => 1, title => 'foo', year => 2000 },
374     producer => { name => 'jorge' }
375   });
376   ok($cdp, 'join table record created ok');
377 };
378 diag $@ if $@;
379
380 #SPECIAL_CASE
381 eval {
382   my $kurt_cobain = { name => 'Kurt Cobain' };
383
384   my $in_utero = $schema->resultset('CD')->new({
385       title => 'In Utero',
386       year  => 1993
387     });
388
389   $kurt_cobain->{cds} = [ $in_utero ];
390
391
392   $schema->resultset('Artist')->populate([ $kurt_cobain ]); # %)
393   $a = $schema->resultset('Artist')->find({name => 'Kurt Cobain'});
394
395   is($a->name, 'Kurt Cobain', 'Artist insertion ok');
396   is($a->cds && $a->cds->first && $a->cds->first->title, 
397                   'In Utero', 'CD insertion ok');
398 };
399 diag $@ if $@;
400
401 #SPECIAL_CASE2
402 eval {
403   my $pink_floyd = { name => 'Pink Floyd' };
404
405   my $the_wall = { title => 'The Wall', year  => 1979 };
406
407   $pink_floyd->{cds} = [ $the_wall ];
408
409
410   $schema->resultset('Artist')->populate([ $pink_floyd ]); # %)
411   $a = $schema->resultset('Artist')->find({name => 'Pink Floyd'});
412
413   is($a->name, 'Pink Floyd', 'Artist insertion ok');
414   is($a->cds && $a->cds->first->title, 'The Wall', 'CD insertion ok');
415 };
416 diag $@ if $@;
417
418 ## Create foreign key col obj including PK
419 ## See test 20 in 66relationships.t
420 eval {
421   my $new_cd_hashref = { 
422     cdid => 27, 
423     title => 'Boogie Woogie', 
424     year => '2007', 
425     artist => { artistid => 17, name => 'king luke' }
426   };
427
428   my $cd = $schema->resultset("CD")->find(1);
429
430   is($cd->artist->id, 1, 'rel okay');
431
432   my $new_cd = $schema->resultset("CD")->create($new_cd_hashref);
433   is($new_cd->artist->id, 17, 'new id retained okay');
434 };
435 diag $@ if $@;
436
437 eval {
438         $schema->resultset("CD")->create({ 
439               cdid => 28, 
440               title => 'Boogie Wiggle', 
441               year => '2007', 
442               artist => { artistid => 18, name => 'larry' }
443              });
444 };
445 is($@, '', 'new cd created without clash on related artist');
446
447 # Make sure exceptions from errors in created rels propogate
448 eval {
449     my $t = $schema->resultset("Track")->new({ cd => { artist => undef } });
450     #$t->cd($t->new_related('cd', { artist => undef } ) );
451     #$t->{_rel_in_storage} = 0;
452     $t->insert;
453 };
454 like($@, qr/cd.artist may not be NULL/, "Exception propogated properly");
455
456 # Test multi create over many_to_many
457 eval {
458   $schema->resultset('CD')->create ({
459     artist => {
460       name => 'larry', # should already exist
461     },
462     title => 'Warble Marble',
463     year => '2009',
464     cd_to_producer => [
465       { producer => { name => 'Cowboy Neal' } },
466     ],
467   });
468
469   my $m2m_cd = $schema->resultset('CD')->search ({ title => 'Warble Marble'});
470   is ($m2m_cd->count, 1, 'One CD row created via M2M create');
471   is ($m2m_cd->first->producers->count, 1, 'CD row created with one producer');
472   is ($m2m_cd->first->producers->first->name, 'Cowboy Neal', 'Correct producer row created');
473 };
474
475 # and some insane multicreate 
476 # (should work, despite the fact that no one will probably use it this way)
477
478 # first count how many rows do we initially have
479 my $counts;
480 $counts->{$_} = $schema->resultset($_)->count for qw/Artist CD Genre Producer Tag/;
481
482 # do the crazy create
483 eval {
484   $schema->resultset('CD')->create ({
485     artist => {
486       name => 'james',
487     },
488     title => 'Greatest hits 1',
489     year => '2012',
490     genre => {
491       name => '"Greatest" collections',
492     },
493     tags => [
494       { tag => 'A' },
495       { tag => 'B' },
496     ],
497     cd_to_producer => [
498       {
499         producer => {
500           name => 'bob',
501           producer_to_cd => [
502             {
503               cd => { 
504                 artist => {
505                   name => 'lars',
506                   cds => [
507                     {
508                       title => 'Greatest hits 2',
509                       year => 2012,
510                       genre => {
511                         name => '"Greatest" collections',
512                       },
513                       tags => [
514                         { tag => 'A' },
515                         { tag => 'B' },
516                       ],
517                       # This cd is created via artist so it doesn't know about producers
518                       cd_to_producer => [
519                         # if we specify 'bob' here things bomb
520                         # as the producer attached to Greatest Hits 1 is
521                         # already created, but not yet inserted.
522                         # Maybe this can be fixed, but things are hairy
523                         # enough already.
524                         #
525                         #{ producer => { name => 'bob' } },
526                         { producer => { name => 'paul' } },
527                         { producer => {
528                           name => 'flemming',
529                           producer_to_cd => [
530                             { cd => {
531                               artist => {
532                                 name => 'kirk',
533                                 cds => [
534                                   {
535                                     title => 'Greatest hits 3',
536                                     year => 2012,
537                                     genre => {
538                                       name => '"Greatest" collections',
539                                     },
540                                     tags => [
541                                       { tag => 'A' },
542                                       { tag => 'B' },
543                                     ],
544                                   },
545                                   {
546                                     title => 'Greatest hits 4',
547                                     year => 2012,
548                                     genre => {
549                                       name => '"Greatest" collections2',
550                                     },
551                                     tags => [
552                                       { tag => 'A' },
553                                       { tag => 'B' },
554                                     ],
555                                   },
556                                 ],
557                               },
558                               title => 'Greatest hits 5',
559                               year => 2013,
560                               genre => {
561                                 name => '"Greatest" collections2',
562                               },
563                             }},
564                           ],
565                         }},
566                       ],
567                     },
568                   ],
569                 },
570                 title => 'Greatest hits 6',
571                 year => 2012,
572                 genre => {
573                   name => '"Greatest" collections',
574                 },
575                 tags => [
576                   { tag => 'A' },
577                   { tag => 'B' },
578                 ],
579               },
580             },
581             {
582               cd => { 
583                 artist => {
584                   name => 'lars',    # should already exist
585                   # even though the artist 'name' is not uniquely constrained
586                   # find_or_create will arguably DWIM 
587                 },
588                 title => 'Greatest hits 7',
589                 year => 2013,
590               },
591             },
592           ],
593         },
594       },
595     ],
596   });
597
598   is ($schema->resultset ('Artist')->count, $counts->{Artist} + 3, '3 new artists created');
599   is ($schema->resultset ('Genre')->count, $counts->{Genre} + 2, '2 additional genres created');
600   is ($schema->resultset ('Producer')->count, $counts->{Producer} + 3, '3 new producer');
601   is ($schema->resultset ('CD')->count, $counts->{CD} + 7, '7 new CDs');
602   is ($schema->resultset ('Tag')->count, $counts->{Tag} + 10, '10 new Tags');
603
604   my $cd_rs = $schema->resultset ('CD')
605     ->search ({ title => { -like => 'Greatest hits %' }}, { order_by => 'title'} );
606   is ($cd_rs->count, 7, '7 greatest hits created');
607
608   my $cds_2012 = $cd_rs->search ({ year => 2012});
609   is ($cds_2012->count, 5, '5 CDs created in 2012');
610
611   is (
612     $cds_2012->search(
613       { 'tags.tag' => { -in => [qw/A B/] } },
614       { join => 'tags', group_by => 'me.cdid' }
615     ),
616     5,
617     'All 10 tags were pairwise distributed between 5 year-2012 CDs'
618   );
619
620   my $paul_prod = $cd_rs->search (
621     { 'producer.name' => 'paul'},
622     { join => { cd_to_producer => 'producer' } }
623   );
624   is ($paul_prod->count, 1, 'Paul had 1 production');
625   my $pauls_cd = $paul_prod->single;
626   is ($pauls_cd->cd_to_producer->count, 2, 'Paul had one co-producer');
627   is (
628     $pauls_cd->search_related ('cd_to_producer',
629       { 'producer.name' => 'flemming'},
630       { join => 'producer' }
631     )->count,
632     1,
633     'The second producer is flemming',
634   );
635
636   my $kirk_cds = $cd_rs->search ({ 'artist.name' => 'kirk' }, { join => 'artist' });
637   is ($kirk_cds, 3, 'Kirk had 3 CDs');
638   is (
639     $kirk_cds->search (
640       { 'cd_to_producer.cd' => { '!=', undef } },
641       { join => 'cd_to_producer' },
642     ),
643     1,
644     'Kirk had a producer only on one cd',
645   );
646
647   my $lars_cds = $cd_rs->search ({ 'artist.name' => 'lars' }, { join => 'artist' });
648   is ($lars_cds->count, 3, 'Lars had 3 CDs');
649   is (
650     $lars_cds->search (
651       { 'cd_to_producer.cd' => undef },
652       { join => 'cd_to_producer' },
653     ),
654     0,
655     'Lars always had a producer',
656   );
657   is (
658     $lars_cds->search_related ('cd_to_producer',
659       { 'producer.name' => 'flemming'},
660       { join => 'producer' }
661     )->count,
662     1,
663     'Lars produced 1 CD with flemming',
664   );
665   is (
666     $lars_cds->search_related ('cd_to_producer',
667       { 'producer.name' => 'bob'},
668       { join => 'producer' }
669     )->count,
670     2,
671     'Lars produced 2 CDs with bob',
672   );
673
674   my $bob_prod = $cd_rs->search (
675     { 'producer.name' => 'bob'},
676     { join => { cd_to_producer => 'producer' } }
677   );
678   is ($bob_prod->count, 3, 'Bob produced a total of 3 CDs');
679
680   is (
681     $bob_prod->search ({ 'artist.name' => 'james' }, { join => 'artist' })->count,
682     1,
683     "Bob produced james' only CD",
684   );
685 };
686 diag $@ if $@;
687
688 1;