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