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