1use strict;
2use warnings;
3
4use Test::More;
5use Test::Exception;
6use lib qw(t/lib);
7use DBICTest;
8
9sub mc_diag { diag (@_) if $ENV{DBIC_MULTICREATE_DEBUG} };
10
11my $schema = DBICTest->init_schema();
12
13mc_diag (<<'DG');
14* Test a multilevel might-have/has_one with a PK == FK in the mid-table
15
16CD -> might have -> Artwork
17    \- has_one -/     \
18                       \
19                        \-> has_many \
20                                      --> Artwork_to_Artist
21                        /-> has_many /
22                       /
23                     Artist
24DG
25
26my $rels = {
27  has_one => 'mandatory_artwork',
28  might_have => 'artwork',
29};
30
31for my $type (qw/has_one might_have/) {
32
33  lives_ok (sub {
34
35    my $rel = $rels->{$type};
36    my $cd_title = "Simple test $type cd";
37
38    my $cd = $schema->resultset('CD')->create ({
39      artist => 1,
40      title => $cd_title,
41      year => 2008,
42      $rel => {},
43    });
44
45    isa_ok ($cd, 'DBICTest::CD', 'Main CD object created');
46    is ($cd->title, $cd_title, 'Correct CD title');
47
48    isa_ok ($cd->$rel, 'DBICTest::Artwork', 'Related artwork present');
49    ok ($cd->$rel->in_storage, 'And in storage');
50
51  }, "Simple $type creation");
52}
53
54my $artist_rs = $schema->resultset('Artist');
55for my $type (qw/has_one might_have/) {
56
57  my $rel = $rels->{$type};
58
59  my $cd_title = "Test $type cd";
60  my $artist_names = [ map { "Artist via $type $_" } (1, 2) ];
61
62  my $someartist = $artist_rs->next;
63
64  lives_ok (sub {
65    my $cd = $schema->resultset('CD')->create ({
66      artist => $someartist,
67      title => $cd_title,
68      year => 2008,
69      $rel => {
70      artwork_to_artist => [ map {
71            { artist => { name => $_ } }
72          } (@$artist_names)
73        ]
74      },
75    });
76
77
78    isa_ok ($cd, 'DBICTest::CD', 'Main CD object created');
79    is ($cd->title, $cd_title, 'Correct CD title');
80
81    my $art_obj = $cd->$rel;
82    ok ($art_obj->has_column_loaded ('cd_id'), 'PK/FK present on artwork object');
83    is ($art_obj->artists->count, 2, 'Correct artwork creator count via the new object');
84    is_deeply (
85      [ sort $art_obj->artists->get_column ('name')->all ],
86      $artist_names,
87      'Artists named correctly when queried via object',
88    );
89
90    my $artwork = $schema->resultset('Artwork')->search (
91      { 'cd.title' => $cd_title },
92      { join => 'cd' },
93    )->single;
94    is ($artwork->artists->count, 2, 'Correct artwork creator count via a new search');
95    is_deeply (
96        [ sort $artwork->artists->get_column ('name')->all ],
97      $artist_names,
98      'Artists named correctly queried via a new search',
99    );
100  }, "multilevel $type with a PK == FK in the $type/has_many table ok");
101}
102
103done_testing;
104