d808eba087ad3d6b245bbeff5f5490a5bbce3901
[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 => 77;
10
11 my $schema = DBICTest->init_schema();
12
13 diag '* 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 diag '* same as above but the child and parent have no values, except for an explicit parent pk';
30 eval {
31   my $bm_rs = $schema->resultset('Bookmark');
32   my $bookmark = $bm_rs->create({
33     link => {
34       id => 66,
35     },
36   });
37
38   isa_ok($bookmark, 'DBICTest::Bookmark', 'Created Bookrmark object');
39   isa_ok($bookmark->link, 'DBICTest::Link', 'Created related Link');
40   is (
41     $bm_rs->search (
42       { 'link.title' => $bookmark->link->title },
43       { join => 'link' },
44     )->count,
45     1,
46     'Bookmark and link made it to the DB',
47   );
48 };
49 diag $@ if $@;
50
51 diag '* create over > 1 levels of has_many create (A => { has_many => { B => has_many => C } } )';
52 eval {
53   my $artist = $schema->resultset('Artist')->first;
54   my $cd = $artist->create_related (cds => {
55     title => 'Music to code by',
56     year => 2007,
57     tags => [
58       { 'tag' => 'rock' },
59     ],
60   });
61
62   isa_ok($cd, 'DBICTest::CD', 'Created CD');
63   is($cd->title, 'Music to code by', 'CD created correctly');
64   is($cd->tags->count, 1, 'One tag created for CD');
65   is($cd->tags->first->tag, 'rock', 'Tag created correctly');
66
67 };
68 diag $@ if $@;
69
70 throws_ok (
71   sub {
72     # Create via update - add a new CD <--- THIS SHOULD HAVE NEVER WORKED!
73     $schema->resultset('Artist')->first->update({
74       cds => [
75         { title => 'Yet another CD',
76           year => 2006,
77         },
78       ],
79     });
80   },
81   qr/Recursive update is not supported over relationships of type multi/,
82   'create via update of multi relationships throws an exception'
83 );
84
85 diag '* Create m2m while originating in the linker table';
86 eval {
87   my $artist = $schema->resultset('Artist')->first;
88   my $c2p = $schema->resultset('CD_to_Producer')->create ({
89     cd => {
90       artist => $artist,
91       title => 'Bad investment',
92       year => 2008,
93       tracks => [
94         { position => 1, title => 'Just buy' },
95         { position => 2, title => 'Why did we do it' },
96         { position => 3, title => 'Burn baby burn' },
97       ],
98     },
99     producer => {
100       name => 'Lehman Bros.',
101     },
102   });
103
104   isa_ok ($c2p, 'DBICTest::CD_to_Producer', 'Linker object created');
105   my $prod = $schema->resultset ('Producer')->find ({ name => 'Lehman Bros.' });
106   isa_ok ($prod, 'DBICTest::Producer', 'Producer row found');
107   is ($prod->cds->count, 1, 'Producer has one production');
108   my $cd = $prod->cds->first;
109   is ($cd->title, 'Bad investment', 'CD created correctly');
110   is ($cd->tracks->count, 3, 'CD has 3 tracks');
111
112 };
113 diag $@ if $@;
114
115 diag (<<'DG');
116 * Create over > 1 levels of might_have with multiple has_many and multiple m2m
117 but starting at a has_many level
118
119 CD -> has_many -> Tracks -> might have -> Single -> has_many -> Tracks
120                                                \
121                                                 \-> has_many \
122                                                               --> CD2Producer
123                                                 /-> has_many /
124                                                /
125                                           Producer
126 DG
127
128 eval {
129   my $artist = $schema->resultset('Artist')->first;
130   my $cd = $schema->resultset('CD')->create ({
131     artist => $artist,
132     title => 'Music to code by at night',
133     year => 2008,
134     tracks => [
135       {
136         position => 1, # some day me might test this with Ordered
137         title => 'Off by one again',
138       },
139       {
140         position => 2,
141         title => 'The dereferencer',
142         cd_single => {
143           artist => $artist,
144           year => 2008,
145           title => 'Was that a null (Single)',
146           tracks => [
147             { title => 'The dereferencer', position => 1 },
148             { title => 'The dereferencer II', position => 2 },
149           ],
150           cd_to_producer => [
151             {
152               producer => {
153                 name => 'K&R',
154               }
155             },
156             {
157               producer => {
158                 name => 'Don Knuth',
159               }
160             },
161           ]
162         },
163       },
164     ],
165   });
166
167   isa_ok ($cd, 'DBICTest::CD', 'Main CD object created');
168   is ($cd->title, 'Music to code by at night', 'Correct CD title');
169   is ($cd->tracks->count, 2, 'Two tracks on main CD');
170
171   my ($t1, $t2) = $cd->tracks->all;
172   is ($t1->title, 'Off by one again', 'Correct 1st track name');
173   is ($t1->cd_single, undef, 'No single for 1st track');
174   is ($t2->title, 'The dereferencer', 'Correct 2nd track name');
175   isa_ok ($t2->cd_single, 'DBICTest::CD', 'Created a single for 2nd track');
176
177   my $single = $t2->cd_single;
178   is ($single->tracks->count, 2, 'Two tracks on single CD');
179   is ($single->tracks->find ({ position => 1})->title, 'The dereferencer', 'Correct 1st track title');
180   is ($single->tracks->find ({ position => 2})->title, 'The dereferencer II', 'Correct 2nd track title');
181
182   is ($single->cd_to_producer->count, 2, 'Two producers created for the single cd');
183   is_deeply (
184     [ sort map { $_->producer->name } ($single->cd_to_producer->all) ],
185     ['Don Knuth', 'K&R'],
186     'Producers named correctly',
187   );
188 };
189 diag $@ if $@;
190
191 diag (<<'DG');
192 * Same as above but starting at the might_have directly
193
194 Track -> might have -> Single -> has_many -> Tracks
195                            \
196                             \-> has_many \
197                                           --> CD2Producer
198                             /-> has_many /
199                            /
200                        Producer
201 DG
202
203 eval {
204   my $cd = $schema->resultset('CD')->first;
205   my $track = $schema->resultset('Track')->create ({
206     cd => $cd,
207     position => 77,  # some day me might test this with Ordered
208     title => 'Multicreate rocks',
209     cd_single => {
210       artist => $cd->artist,
211       year => 2008,
212       title => 'Disemboweling MultiCreate',
213       tracks => [
214         { title => 'Why does mst write this way', position => 1 },
215         { title => 'Chainsaw celebration', position => 2 },
216         { title => 'Purl cleans up', position => 3 },
217       ],
218       cd_to_producer => [
219         {
220           producer => {
221             name => 'mst',
222           }
223         },
224         {
225           producer => {
226             name => 'castaway',
227           }
228         },
229         {
230           producer => {
231             name => 'theorbtwo',
232           }
233         },
234       ]
235     },
236   });
237
238   isa_ok ($track, 'DBICTest::Track', 'Main Track object created');
239   is ($track->title, 'Multicreate rocks', 'Correct Track title');
240
241   my $single = $track->cd_single;
242   isa_ok ($single, 'DBICTest::CD', 'Created a single with the track');
243   is ($single->tracks->count, 3, '3 tracks on single CD');
244   is ($single->tracks->find ({ position => 1})->title, 'Why does mst write this way', 'Correct 1st track title');
245   is ($single->tracks->find ({ position => 2})->title, 'Chainsaw celebration', 'Correct 2nd track title');
246   is ($single->tracks->find ({ position => 3})->title, 'Purl cleans up', 'Correct 3rd track title');
247
248   is ($single->cd_to_producer->count, 3, '3 producers created for the single cd');
249   is_deeply (
250     [ sort map { $_->producer->name } ($single->cd_to_producer->all) ],
251     ['castaway', 'mst', 'theorbtwo'],
252     'Producers named correctly',
253   );
254 };
255 diag $@ if $@;
256
257 diag '* Test might_have again but with a PK == FK in the middle (obviously not specified)';
258 eval {
259   my $artist = $schema->resultset('Artist')->first;
260   my $cd = $schema->resultset('CD')->create ({
261     artist => $artist,
262     title => 'Music to code by at twilight',
263     year => 2008,
264     artwork => {
265       images => [
266         { name => 'recursive descent' },
267         { name => 'tail packing' },
268       ],
269     },
270   });
271
272   isa_ok ($cd, 'DBICTest::CD', 'Main CD object created');
273   is ($cd->title, 'Music to code by at twilight', 'Correct CD title');
274   isa_ok ($cd->artwork, 'DBICTest::Artwork', 'Artwork created');
275
276   # this test might look weird, but it failed at one point, keep it there
277   my $art_obj = $cd->artwork;
278   ok ($art_obj->has_column_loaded ('cd_id'), 'PK/FK present on artwork object');
279   is ($art_obj->images->count, 2, 'Correct artwork image count via the new object');
280   is_deeply (
281     [ sort $art_obj->images->get_column ('name')->all ],
282     [ 'recursive descent', 'tail packing' ],
283     'Images named correctly in objects',
284   );
285
286   my $artwork = $schema->resultset('Artwork')->search (
287     { 'cd.title' => 'Music to code by at twilight' },
288     { join => 'cd' },
289   )->single;
290
291   is ($artwork->images->count, 2, 'Correct artwork image count via a new search');
292
293   is_deeply (
294     [ sort $artwork->images->get_column ('name')->all ],
295     [ 'recursive descent', 'tail packing' ],
296     'Images named correctly after search',
297   );
298 };
299 diag $@ if $@;
300
301 diag '* Test might_have again but with just a PK and FK (neither specified) in the mid-table';
302 eval {
303   my $cd = $schema->resultset('CD')->first;
304   my $track = $schema->resultset ('Track')->create ({
305     cd => $cd,
306     position => 66,
307     title => 'Black',
308     lyrics => {
309       lyric_versions => [
310         { text => 'The color black' },
311         { text => 'The colour black' },
312       ],
313     },
314   });
315
316   isa_ok ($track, 'DBICTest::Track', 'Main track object created');
317   is ($track->title, 'Black', 'Correct track title');
318   isa_ok ($track->lyrics, 'DBICTest::Lyrics', 'Lyrics created');
319
320   # this test might look weird, but it was failing at one point, keep it there
321   my $lyric_obj = $track->lyrics;
322   ok ($lyric_obj->has_column_loaded ('lyric_id'), 'PK present on lyric object');
323   ok ($lyric_obj->has_column_loaded ('track_id'), 'FK present on lyric object');
324   is ($lyric_obj->lyric_versions->count, 2, 'Correct lyric versions count via the new object');
325   is_deeply (
326     [ sort $lyric_obj->lyric_versions->get_column ('text')->all ],
327     [ 'The color black', 'The colour black' ],
328     'Lyrics text in objects matches',
329   );
330
331
332   my $lyric = $schema->resultset('Lyrics')->search (
333     { 'track.title' => 'Black' },
334     { join => 'track' },
335   )->single;
336
337   is ($lyric->lyric_versions->count, 2, 'Correct lyric versions count via a new search');
338
339   is_deeply (
340     [ sort $lyric->lyric_versions->get_column ('text')->all ],
341     [ 'The color black', 'The colour black' ],
342     'Lyrics text via search matches',
343   );
344 };
345 diag $@ if $@;
346
347 diag (<<'DG');
348 * Test a multilevel might-have with a PK == FK in the might_have/has_many table
349
350 CD -> might have -> Artwork
351                        \
352                         \-> has_many \
353                                       --> Artwork_to_Artist
354                         /-> has_many /
355                        /
356                      Artist
357 DG
358
359 eval {
360   my $someartist = $schema->resultset('Artist')->first;
361   my $cd = $schema->resultset('CD')->create ({
362     artist => $someartist,
363     title => 'Music to code by until the cows come home',
364     year => 2008,
365     artwork => {
366       artwork_to_artist => [
367         { artist => { name => 'cowboy joe' } },
368         { artist => { name => 'billy the kid' } },
369       ],
370     },
371   });
372
373   isa_ok ($cd, 'DBICTest::CD', 'Main CD object created');
374   is ($cd->title, 'Music to code by until the cows come home', 'Correct CD title');
375
376   my $art_obj = $cd->artwork;
377   ok ($art_obj->has_column_loaded ('cd_id'), 'PK/FK present on artwork object');
378   is ($art_obj->artists->count, 2, 'Correct artwork creator count via the new object');
379   is_deeply (
380     [ sort $art_obj->artists->get_column ('name')->all ],
381     [ 'billy the kid', 'cowboy joe' ],
382     'Artists named correctly when queried via object',
383   );
384
385   my $artwork = $schema->resultset('Artwork')->search (
386     { 'cd.title' => 'Music to code by until the cows come home' },
387     { join => 'cd' },
388   )->single;
389   is ($artwork->artists->count, 2, 'Correct artwork creator count via a new search');
390   is_deeply (
391     [ sort $artwork->artists->get_column ('name')->all ],
392     [ 'billy the kid', 'cowboy joe' ],
393     'Artists named correctly queried via a new search',
394   );
395 };
396 diag $@ if $@;
397
398 diag '* Nested find_or_create';
399 eval {
400   my $newartist2 = $schema->resultset('Artist')->find_or_create({ 
401     name => 'Fred 3',
402     cds => [
403       { 
404         title => 'Noah Act',
405         year => 2007,
406       },
407     ],
408   });
409   is($newartist2->name, 'Fred 3', 'Created new artist with cds via find_or_create');
410 };
411 diag $@ if $@;
412
413 diag '* Multiple same level has_many create';
414 eval {
415   my $artist2 = $schema->resultset('Artist')->create({
416     name => 'Fred 4',
417     cds => [
418       {
419         title => 'Music to code by',
420         year => 2007,
421       },
422     ],
423     cds_unordered => [
424       {
425         title => 'Music to code by',
426         year => 2007,
427       },
428     ]
429   });
430
431   is($artist2->in_storage, 1, 'artist with duplicate rels inserted okay');
432 };
433 diag $@ if $@;
434
435 diag '* First create_related pass';
436 eval {
437         my $artist = $schema->resultset('Artist')->first;
438         
439         my $cd_result = $artist->create_related('cds', {
440         
441                 title => 'TestOneCD1',
442                 year => 2007,
443                 tracks => [
444                 
445                         { position=>111,
446                           title => 'TrackOne',
447                         },
448                         { position=>112,
449                           title => 'TrackTwo',
450                         }
451                 ],
452
453         });
454         
455         ok( $cd_result && ref $cd_result eq 'DBICTest::CD', "Got Good CD Class");
456         ok( $cd_result->title eq "TestOneCD1", "Got Expected Title");
457         
458         my $tracks = $cd_result->tracks;
459         
460         ok( ref $tracks eq "DBIx::Class::ResultSet", "Got Expected Tracks ResultSet");
461         
462         foreach my $track ($tracks->all)
463         {
464                 ok( $track && ref $track eq 'DBICTest::Track', 'Got Expected Track Class');
465         }
466 };
467 diag $@ if $@;
468
469 diag '* second create_related with same arguments';
470 eval {
471         my $artist = $schema->resultset('Artist')->first;
472         
473         my $cd_result = $artist->create_related('cds', {
474         
475                 title => 'TestOneCD2',
476                 year => 2007,
477                 tracks => [
478                 
479                         { position=>111,
480                           title => 'TrackOne',
481                         },
482                         { position=>112,
483                           title => 'TrackTwo',
484                         }
485                 ],
486
487     liner_notes => { notes => 'I can haz liner notes?' },
488
489         });
490         
491         ok( $cd_result && ref $cd_result eq 'DBICTest::CD', "Got Good CD Class");
492         ok( $cd_result->title eq "TestOneCD2", "Got Expected Title");
493   ok( $cd_result->notes eq 'I can haz liner notes?', 'Liner notes');
494         
495         my $tracks = $cd_result->tracks;
496         
497         ok( ref $tracks eq "DBIx::Class::ResultSet", "Got Expected Tracks ResultSet");
498         
499         foreach my $track ($tracks->all)
500         {
501                 ok( $track && ref $track eq 'DBICTest::Track', 'Got Expected Track Class');
502         }
503 };
504 diag $@ if $@;
505
506 diag '* create of parents of a record linker table';
507 eval {
508   my $cdp = $schema->resultset('CD_to_Producer')->create({
509     cd => { artist => 1, title => 'foo', year => 2000 },
510     producer => { name => 'jorge' }
511   });
512   ok($cdp, 'join table record created ok');
513 };
514 diag $@ if $@;
515
516 eval {
517   my $kurt_cobain = { name => 'Kurt Cobain' };
518
519   my $in_utero = $schema->resultset('CD')->new({
520       title => 'In Utero',
521       year  => 1993
522     });
523
524   $kurt_cobain->{cds} = [ $in_utero ];
525
526
527   $schema->resultset('Artist')->populate([ $kurt_cobain ]); # %)
528   $a = $schema->resultset('Artist')->find({name => 'Kurt Cobain'});
529
530   is($a->name, 'Kurt Cobain', 'Artist insertion ok');
531   is($a->cds && $a->cds->first && $a->cds->first->title, 
532                   'In Utero', 'CD insertion ok');
533 };
534 diag $@ if $@;
535
536 =pod
537 # This test case has been moved to t/96multi_create/cd_single.t
538 eval {
539   my $pink_floyd = { name => 'Pink Floyd' };
540
541   my $the_wall = { title => 'The Wall', year  => 1979 };
542
543   $pink_floyd->{cds} = [ $the_wall ];
544
545
546   $schema->resultset('Artist')->populate([ $pink_floyd ]); # %)
547   $a = $schema->resultset('Artist')->find({name => 'Pink Floyd'});
548
549   is($a->name, 'Pink Floyd', 'Artist insertion ok');
550   is($a->cds && $a->cds->first->title, 'The Wall', 'CD insertion ok');
551 };
552 diag $@ if $@;
553 =cut
554
555 diag '* Create foreign key col obj including PK (See test 20 in 66relationships.t)';
556 ## Create foreign key col obj including PK
557 ## See test 20 in 66relationships.t
558 eval {
559   my $new_cd_hashref = { 
560     cdid => 27, 
561     title => 'Boogie Woogie', 
562     year => '2007', 
563     artist => { artistid => 17, name => 'king luke' }
564   };
565
566   my $cd = $schema->resultset("CD")->find(1);
567
568   is($cd->artist->id, 1, 'rel okay');
569
570   my $new_cd = $schema->resultset("CD")->create($new_cd_hashref);
571   is($new_cd->artist->id, 17, 'new id retained okay');
572 };
573 diag $@ if $@;
574
575 eval {
576         $schema->resultset("CD")->create({ 
577               cdid => 28, 
578               title => 'Boogie Wiggle', 
579               year => '2007', 
580               artist => { artistid => 18, name => 'larry' }
581              });
582 };
583 is($@, '', 'new cd created without clash on related artist');
584
585 diag '* Make sure exceptions from errors in created rels propogate';
586 eval {
587     my $t = $schema->resultset("Track")->new({ cd => { artist => undef } });
588     #$t->cd($t->new_related('cd', { artist => undef } ) );
589     #$t->{_rel_in_storage} = 0;
590     $t->insert;
591 };
592 like($@, qr/cd.artist may not be NULL/, "Exception propogated properly");
593
594 diag '* Test multi create over many_to_many';
595 eval {
596   $schema->resultset('CD')->create ({
597     artist => {
598       name => 'larry', # should already exist
599     },
600     title => 'Warble Marble',
601     year => '2009',
602     cd_to_producer => [
603       { producer => { name => 'Cowboy Neal' } },
604     ],
605   });
606
607   my $m2m_cd = $schema->resultset('CD')->search ({ title => 'Warble Marble'});
608   is ($m2m_cd->count, 1, 'One CD row created via M2M create');
609   is ($m2m_cd->first->producers->count, 1, 'CD row created with one producer');
610   is ($m2m_cd->first->producers->first->name, 'Cowboy Neal', 'Correct producer row created');
611 };
612
613 1;