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