One more cdbi-compat author req
[dbsrgits/DBIx-Class.git] / t / 33storage_reconnect.t
CommitLineData
4ffbc1d6 1use strict;
2use warnings;
3
e7827df0 4use FindBin;
5use File::Copy;
4ffbc1d6 6use Test::More;
7use lib qw(t/lib);
8use DBICTest;
9
8d5add12 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}
e7827df0 18
19my $db_orig = "$FindBin::Bin/var/DBIxClass.db";
20my $db_tmp = "$db_orig.tmp";
4ffbc1d6 21
22# Set up the "usual" sqlite for DBICTest
fcf741b1 23my $schema = DBICTest->init_schema( sqlite_use_file => 1 );
4ffbc1d6 24
25# Make sure we're connected by doing something
26my @art = $schema->resultset("Artist")->search({ }, { order_by => 'name DESC'});
27cmp_ok(@art, '==', 3, "Three artists returned");
28
29# Disconnect the dbh, and be sneaky about it
b5bf138f 30# Also test if DBD::SQLite finaly knows how to ->disconnect properly
31TODO: {
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}
4ffbc1d6 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!
44my @art_two = $schema->resultset("Artist")->search({ }, { order_by => 'name DESC'});
45cmp_ok(@art_two, '==', 3, "Three artists returned");
e7827df0 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;
50move( $db_orig, $db_tmp );
51open DBFILE, '>', $db_orig;
52print DBFILE 'THIS IS NOT A REAL DATABASE';
53close DBFILE;
54chmod 0000, $db_orig;
55
56### Try the operation again... it should fail, since there's no db
b5bf138f 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}
e7827df0 65
66### Now, move the db file back to the correct name
67unlink($db_orig);
68move( $db_tmp, $db_orig );
69
413abe68 70SKIP: {
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}