Protect DBIC as best we can from the failure mode in 7cb35852
[dbsrgits/DBIx-Class.git] / t / storage / reconnect.t
1 use strict;
2 use warnings;
3
4 use FindBin;
5 use B::Deparse;
6 use File::Copy 'move';
7 use Scalar::Util 'weaken';
8 use Test::More;
9 use Test::Exception;
10 use lib qw(t/lib);
11 use DBICTest;
12
13 my $db_orig = DBICTest->_sqlite_dbfilename;
14 my $db_tmp  = "$db_orig.tmp";
15
16 # Set up the "usual" sqlite for DBICTest
17 my $schema = DBICTest->init_schema( sqlite_use_file => 1 );
18
19 my $exception_action_count;
20 $schema->exception_action(sub {
21   $exception_action_count++;
22   die @_;
23 });
24
25 # Make sure we're connected by doing something
26 my @art = $schema->resultset("Artist")->search({ }, { order_by => { -desc => 'name' }});
27 cmp_ok(@art, '==', 3, "Three artists returned");
28
29 # Disconnect the dbh, and be sneaky about it
30 # Also test if DBD::SQLite finaly knows how to ->disconnect properly
31 {
32   my $w;
33   local $SIG{__WARN__} = sub { $w = shift };
34   $schema->storage->_dbh->disconnect;
35   ok ($w !~ /active statement handles/, 'SQLite can disconnect properly');
36 }
37
38 # Try the operation again - What should happen here is:
39 #   1. S::DBI blindly attempts the SELECT, which throws an exception
40 #   2. It catches the exception, checks ->{Active}/->ping, sees the disconnected state...
41 #   3. Reconnects, and retries the operation
42 #   4. Success!
43 my @art_two = $schema->resultset("Artist")->search({ }, { order_by => { -desc => 'name' }});
44 cmp_ok(@art_two, '==', 3, "Three artists returned");
45
46 ### Now, disconnect the dbh, and move the db file;
47 # create a new one full of garbage, prevent SQLite from connecting.
48 $schema->storage->_dbh->disconnect;
49 move( $db_orig, $db_tmp )
50   or die "failed to move $db_orig to $db_tmp: $!";
51 open my $db_file, '>', $db_orig;
52 print $db_file 'THIS IS NOT A REAL DATABASE';
53 close $db_file;
54
55 ### Try the operation again... it should fail, since there's no valid db
56 {
57   # Catch the DBI connection error
58   local $SIG{__WARN__} = sub {};
59   throws_ok {
60     $schema->resultset("Artist")->create({ name => 'not gonna happen' });
61   }  qr/not a database/, 'The operation failed';
62 }
63
64 ok (! $schema->storage->connected, 'We are not connected' );
65
66 ### Now, move the db file back to the correct name
67 unlink($db_orig) or die "could not delete $db_orig: $!";
68 move( $db_tmp, $db_orig )
69   or die "could not move $db_tmp to $db_orig: $!";
70
71 ### Try the operation again... this time, it should succeed
72 my @art_four;
73 lives_ok {
74     @art_four = $schema->resultset("Artist")->search( {}, { order_by => { -desc => 'name' } } );
75 } 'The operation succeeded';
76 cmp_ok( @art_four, '==', 3, "Three artists returned" );
77
78 # check that reconnection contexts are preserved in txn_do / dbh_do
79
80 my $args = [1, 2, 3];
81
82 my $ctx_map = {
83   VOID => {
84     invoke => sub { shift->(); 1 },
85     wa => undef,
86   },
87   SCALAR => {
88     invoke => sub { my $foo = shift->() },
89     wa => '',
90   },
91   LIST => {
92     invoke => sub { my @foo = shift->() },
93     wa => 1,
94   },
95 };
96
97 for my $ctx (keys %$ctx_map) {
98
99   # start disconnected and then connected
100   $schema->storage->disconnect;
101   $exception_action_count = 0;
102
103   for (1, 2) {
104     my $disarmed;
105
106     $ctx_map->{$ctx}{invoke}->(sub { $schema->txn_do(sub {
107       is_deeply (\@_, $args, 'Args propagated correctly' );
108
109       is (wantarray(), $ctx_map->{$ctx}{wa}, "Correct $ctx context");
110
111       # this will cause a retry
112       $schema->storage->_dbh->disconnect unless $disarmed++;
113
114       isa_ok ($schema->resultset('Artist')->next, 'DBICTest::Artist');
115     }, @$args) });
116   }
117
118   is( $exception_action_count, 0, 'exception_action never called' );
119 };
120
121 # make sure RT#110429 does not recur on manual DBI-side disconnect
122 for my $cref (
123   sub {
124     my $schema = shift;
125
126     my $g = $schema->txn_scope_guard;
127
128     is( $schema->storage->transaction_depth, 1, "Expected txn depth" );
129
130     $schema->storage->_dbh->disconnect;
131
132     $schema->storage->dbh_do(sub { $_[1]->do('SELECT 1') } );
133   },
134   sub {
135     my $schema = shift;
136     $schema->txn_do(sub {
137       $schema->storage->_dbh->disconnect
138     } );
139   },
140   sub {
141     my $schema = shift;
142     $schema->txn_do(sub {
143       $schema->storage->disconnect;
144       die "VIOLENCE";
145     } );
146   },
147 ) {
148
149   note( "Testing with " . B::Deparse->new->coderef2text($cref) );
150
151   $schema->storage->disconnect;
152   $exception_action_count = 0;
153
154   ok( !$schema->storage->connected, 'Not connected' );
155
156   is( $schema->storage->transaction_depth, undef, "Start with unknown txn depth" );
157
158   # messages vary depending on version and whether txn or do, whatever
159   dies_ok {
160     $cref->($schema)
161   } 'Threw *something*';
162
163   ok( !$schema->storage->connected, 'Not connected as a result of failed rollback' );
164
165   is( $schema->storage->transaction_depth, undef, "Depth expectedly unknown after failed rollbacks" );
166
167   is( $exception_action_count, 1, "exception_action called only once" );
168 }
169
170 # check exception_action under tenacious disconnect
171 {
172   $schema->storage->disconnect;
173   $exception_action_count = 0;
174
175   throws_ok { $schema->txn_do(sub {
176     $schema->storage->_dbh->disconnect;
177
178     $schema->resultset('Artist')->next;
179   })} qr/prepare on inactive database handle/;
180
181   is( $exception_action_count, 1, "exception_action called only once" );
182 }
183
184 # check that things aren't crazy with a non-violent disconnect
185 {
186   my $schema = DBICTest->init_schema( sqlite_use_file => 0, no_deploy => 1 );
187   weaken( my $ws = $schema );
188
189   $schema->is_executed_sql_bind( sub {
190     $ws->txn_do(sub { $ws->storage->disconnect } );
191   }, [ [ 'BEGIN' ] ], 'Only one BEGIN statement' );
192
193   $schema->is_executed_sql_bind( sub {
194     my $g = $ws->txn_scope_guard;
195     $ws->storage->disconnect;
196   }, [ [ 'BEGIN' ] ], 'Only one BEGIN statement' );
197 }
198
199 done_testing;