56936f85674a21e1c0a7a3d76d76ef47cac22338
[dbsrgits/DBIx-Class.git] / t / relationship / update_or_create_multi.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 use DBIC::SqlMakerTest;
9
10 my $schema = DBICTest->init_schema();
11 my $sdebug = $schema->storage->debug;
12
13 plan tests => 6;
14
15 my $artist = $schema->resultset ('Artist')->first;
16
17 my $genre = $schema->resultset ('Genre')
18             ->create ({ name => 'par excellence' });
19
20 is ($genre->search_related( 'cds' )->count, 0, 'No cds yet');
21
22 # expect a create
23 $genre->update_or_create_related ('cds', {
24   artist => $artist,
25   year => 2009,
26   title => 'the best thing since sliced bread',
27 });
28
29 # verify cd was inserted ok
30 is ($genre->search_related( 'cds' )->count, 1, 'One cd');
31 my $cd = $genre->find_related ('cds', {});
32 is_deeply (
33   { map { $_, $cd->get_column ($_) } qw/artist year title/ },
34   {
35     artist => $artist->id,
36     year => 2009,
37     title => 'the best thing since sliced bread',
38   },
39   'CD created correctly',
40 );
41
42 # expect a year update on the only related row
43 # (non-qunique column + unique column as disambiguator)
44 $genre->update_or_create_related ('cds', {
45   year => 2010,
46   title => 'the best thing since sliced bread',
47 });
48
49 # re-fetch the cd, verify update
50 is ($genre->search_related( 'cds' )->count, 1, 'Still one cd');
51 $cd = $genre->find_related ('cds', {});
52 is_deeply (
53   { map { $_, $cd->get_column ($_) } qw/artist year title/ },
54   {
55     artist => $artist->id,
56     year => 2010,
57     title => 'the best thing since sliced bread',
58   },
59   'CD year column updated correctly',
60 );
61
62
63 # expect a create, after a failed search using *only* the
64 # *current* relationship and the unique column constraints
65 # (so no year)
66 my @sql;
67 $schema->storage->debugcb(sub { push @sql, $_[1] });
68 $schema->storage->debug (1);
69
70 $genre->update_or_create_related ('cds', {
71   title => 'the best thing since vertical toasters',
72   artist => $artist,
73   year => 2012,
74 });
75
76 $schema->storage->debugcb(undef);
77 $schema->storage->debug ($sdebug);
78
79 my ($search_sql) = $sql[0] =~ /^(SELECT .+?)\:/;
80 is_same_sql (
81   $search_sql,
82   'SELECT me.cdid, me.artist, me.title, me.year, me.genreid, me.single_track
83     FROM cd me 
84     WHERE ( me.artist = ? AND me.title = ? AND me.genreid = ? )
85   ',
86   'expected select issued',
87 );
88
89 # a has_many search without a unique constraint makes no sense
90 # but I am not sure what to test for - leaving open