568413426fb3c15d35e50202b46c027ca8f94918
[dbsrgits/DBIx-Class.git] / t / 33storage_reconnect.t
1 use strict;
2 use warnings;  
3
4 use FindBin;
5 use File::Copy;
6 use Test::More;
7 use lib qw(t/lib);
8 use DBICTest;
9
10 {
11   no warnings qw/once/;
12   require inc::Module::Install;
13   plan $Module::Install::AUTHOR 
14     ? (tests => 6) 
15     : (skip_all => 'Test temporarily disabled due to a widespread buggy SQLite version')
16   ;
17 }
18
19 my $db_orig = "$FindBin::Bin/var/DBIxClass.db";
20 my $db_tmp  = "$db_orig.tmp";
21
22 # Set up the "usual" sqlite for DBICTest
23 my $schema = DBICTest->init_schema( sqlite_use_file => 1 );
24
25 # Make sure we're connected by doing something
26 my @art = $schema->resultset("Artist")->search({ }, { order_by => 'name DESC'});
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 TODO: {
32     local $TODO = 'SQLite is evil/braindead. Once this test starts passing, remove the related atrocity from DBIx::Class::Storage::DBI::SQLite';
33     my $w;
34     local $SIG{__WARN__} = sub { $w = shift };
35     $schema->storage->_dbh->disconnect;
36     ok ($w !~ /active statement handles/, 'SQLite can disconnect properly \o/');
37 }
38
39 # Try the operation again - What should happen here is:
40 #   1. S::DBI blindly attempts the SELECT, which throws an exception
41 #   2. It catches the exception, checks ->{Active}/->ping, sees the disconnected state...
42 #   3. Reconnects, and retries the operation
43 #   4. Success!
44 my @art_two = $schema->resultset("Artist")->search({ }, { order_by => 'name DESC'});
45 cmp_ok(@art_two, '==', 3, "Three artists returned");
46
47 ### Now, disconnect the dbh, and move the db file;
48 # create a new one and chmod 000 to prevent SQLite from connecting.
49 $schema->storage->_dbh->disconnect;
50 move( $db_orig, $db_tmp );
51 open DBFILE, '>', $db_orig;
52 print DBFILE 'THIS IS NOT A REAL DATABASE';
53 close DBFILE;
54 chmod 0000, $db_orig;
55
56 ### Try the operation again... it should fail, since there's no db
57 {
58     # Catch the DBI connection error
59     local $SIG{__WARN__} = sub {};
60     eval {
61         my @art_three = $schema->resultset("Artist")->search( {}, { order_by => 'name DESC' } );
62     };
63     ok( $@, 'The operation failed' );
64 }
65
66 ### Now, move the db file back to the correct name
67 unlink($db_orig);
68 move( $db_tmp, $db_orig );
69
70 SKIP: {
71     skip "Cannot reconnect if original connection didn't fail", 2
72         if ( $@ =~ /encrypted or is not a database/ );
73
74     ### Try the operation again... this time, it should succeed
75     my @art_four;
76     eval {
77         @art_four = $schema->resultset("Artist")->search( {}, { order_by => 'name DESC' } );
78     };
79     ok( !$@, 'The operation succeeded' );
80     cmp_ok( @art_four, '==', 3, "Three artists returned" );
81 }