Merge 'warnfree' into 'trunk'
[dbsrgits/DBIx-Class.git] / t / 93storage_replication.t
1 use strict;
2 use warnings;
3 use lib qw(t/lib);
4 use Test::More;
5 use Test::Exception;
6 use DBICTest;
7
8 BEGIN {
9     eval "use DBIx::Class::Storage::DBI::Replicated; use Test::Moose";
10     plan $@
11         ? ( skip_all => "Deps not installed: $@" )
12         : ( tests => 79 );
13 }
14
15 use_ok 'DBIx::Class::Storage::DBI::Replicated::Pool';
16 use_ok 'DBIx::Class::Storage::DBI::Replicated::Balancer';
17 use_ok 'DBIx::Class::Storage::DBI::Replicated::Replicant';
18 use_ok 'DBIx::Class::Storage::DBI::Replicated';
19
20 =head1 HOW TO USE
21
22     This is a test of the replicated storage system.  This will work in one of
23     two ways, either it was try to fake replication with a couple of SQLite DBs
24     and creative use of copy, or if you define a couple of %ENV vars correctly
25     will try to test those.  If you do that, it will assume the setup is properly
26     replicating.  Your results may vary, but I have demonstrated this to work with
27     mysql native replication.
28     
29 =cut
30
31
32 ## ----------------------------------------------------------------------------
33 ## Build a class to hold all our required testing data and methods.
34 ## ----------------------------------------------------------------------------
35
36 TESTSCHEMACLASSES: {
37
38     ## --------------------------------------------------------------------- ##
39     ## Create an object to contain your replicated stuff.
40     ## --------------------------------------------------------------------- ##
41     
42     package DBIx::Class::DBI::Replicated::TestReplication;
43    
44     use DBICTest;
45     use base qw/Class::Accessor::Fast/;
46     
47     __PACKAGE__->mk_accessors( qw/schema/ );
48
49     ## Initialize the object
50     
51         sub new {
52             my $class = shift @_;
53             my $self = $class->SUPER::new(@_);
54         
55             $self->schema( $self->init_schema );
56             return $self;
57         }
58     
59     ## Get the Schema and set the replication storage type
60     
61     sub init_schema {
62         # current SQLT SQLite producer does not handle DROP TABLE IF EXISTS, trap warnings here
63         local $SIG{__WARN__} = sub { warn @_ unless $_[0] =~ /no such table.+DROP TABLE/ };
64
65         my $class = shift @_;
66
67         my $schema = DBICTest->init_schema(
68             sqlite_use_file => 1,
69             storage_type=>{
70                 '::DBI::Replicated' => {
71                         balancer_type=>'::Random',
72                     balancer_args=>{
73                         auto_validate_every=>100,
74                     },
75                 }
76             },
77             deploy_args=>{
78                    add_drop_table => 1,
79             },
80         );
81
82         return $schema;
83     }
84     
85     sub generate_replicant_connect_info {}
86     sub replicate {}
87     sub cleanup {}
88
89   
90     ## --------------------------------------------------------------------- ##
91     ## Subclass for when you are using SQLite for testing, this provides a fake
92     ## replication support.
93     ## --------------------------------------------------------------------- ##
94         
95     package DBIx::Class::DBI::Replicated::TestReplication::SQLite;
96
97     use DBICTest;
98     use File::Copy;    
99     use base 'DBIx::Class::DBI::Replicated::TestReplication';
100     
101     __PACKAGE__->mk_accessors( qw/master_path slave_paths/ );
102     
103     ## Set the mastep path from DBICTest
104     
105         sub new {
106             my $class = shift @_;
107             my $self = $class->SUPER::new(@_);
108         
109             $self->master_path( DBICTest->_sqlite_dbfilename );
110             $self->slave_paths([
111             "t/var/DBIxClass_slave1.db",
112             "t/var/DBIxClass_slave2.db",    
113         ]);
114         
115             return $self;
116         }    
117         
118     ## Return an Array of ArrayRefs where each ArrayRef is suitable to use for
119     ## $storage->connect_info to be used for connecting replicants.
120     
121     sub generate_replicant_connect_info {
122         my $self = shift @_;
123         my @dsn = map {
124             "dbi:SQLite:${_}";
125         } @{$self->slave_paths};
126         
127         return map { [$_,'','',{AutoCommit=>1}] } @dsn;
128     }
129     
130     ## Do a 'good enough' replication by copying the master dbfile over each of
131     ## the slave dbfiles.  If the master is SQLite we do this, otherwise we
132     ## just do a one second pause to let the slaves catch up.
133     
134     sub replicate {
135         my $self = shift @_;
136         foreach my $slave (@{$self->slave_paths}) {
137             copy($self->master_path, $slave);
138         }
139     }
140     
141     ## Cleanup after ourselves.  Unlink all gthe slave paths.
142     
143     sub cleanup {
144         my $self = shift @_;
145         foreach my $slave (@{$self->slave_paths}) {
146             unlink $slave;
147         }     
148     }
149     
150     ## --------------------------------------------------------------------- ##
151     ## Subclass for when you are setting the databases via custom export vars
152     ## This is for when you have a replicating database setup that you are
153     ## going to test against.  You'll need to define the correct $ENV and have
154     ## two slave databases to test against, as well as a replication system
155     ## that will replicate in less than 1 second.
156     ## --------------------------------------------------------------------- ##
157         
158     package DBIx::Class::DBI::Replicated::TestReplication::Custom; 
159     use base 'DBIx::Class::DBI::Replicated::TestReplication';
160     
161     ## Return an Array of ArrayRefs where each ArrayRef is suitable to use for
162     ## $storage->connect_info to be used for connecting replicants.
163     
164     sub generate_replicant_connect_info { 
165         return (
166             [$ENV{"DBICTEST_SLAVE0_DSN"}, $ENV{"DBICTEST_SLAVE0_DBUSER"}, $ENV{"DBICTEST_SLAVE0_DBPASS"}, {AutoCommit => 1}],
167             [$ENV{"DBICTEST_SLAVE1_DSN"}, $ENV{"DBICTEST_SLAVE1_DBUSER"}, $ENV{"DBICTEST_SLAVE1_DBPASS"}, {AutoCommit => 1}],           
168         );
169     }
170     
171     ## pause a bit to let the replication catch up 
172     
173     sub replicate {
174         sleep 1;
175     } 
176 }
177
178 ## ----------------------------------------------------------------------------
179 ## Create an object and run some tests
180 ## ----------------------------------------------------------------------------
181
182 ## Thi first bunch of tests are basic, just make sure all the bits are behaving
183
184 my $replicated_class = DBICTest->has_custom_dsn ?
185     'DBIx::Class::DBI::Replicated::TestReplication::Custom' :
186     'DBIx::Class::DBI::Replicated::TestReplication::SQLite';
187
188 ok my $replicated = $replicated_class->new
189     => 'Created a replication object';
190     
191 isa_ok $replicated->schema
192     => 'DBIx::Class::Schema';
193     
194 isa_ok $replicated->schema->storage
195     => 'DBIx::Class::Storage::DBI::Replicated';
196
197 ok $replicated->schema->storage->meta
198     => 'has a meta object';
199     
200 isa_ok $replicated->schema->storage->master
201     => 'DBIx::Class::Storage::DBI';
202     
203 isa_ok $replicated->schema->storage->pool
204     => 'DBIx::Class::Storage::DBI::Replicated::Pool';
205     
206 does_ok $replicated->schema->storage->balancer
207     => 'DBIx::Class::Storage::DBI::Replicated::Balancer'; 
208
209 ok my @replicant_connects = $replicated->generate_replicant_connect_info
210     => 'got replication connect information';
211
212 ok my @replicated_storages = $replicated->schema->storage->connect_replicants(@replicant_connects)
213     => 'Created some storages suitable for replicants';
214     
215 isa_ok $replicated->schema->storage->balancer->current_replicant
216     => 'DBIx::Class::Storage::DBI';
217     
218 ok $replicated->schema->storage->pool->has_replicants
219     => 'does have replicants';     
220
221 is $replicated->schema->storage->pool->num_replicants => 2
222     => 'has two replicants';
223        
224 does_ok $replicated_storages[0]
225     => 'DBIx::Class::Storage::DBI::Replicated::Replicant';
226
227 does_ok $replicated_storages[1]
228     => 'DBIx::Class::Storage::DBI::Replicated::Replicant';
229     
230 my @replicant_names = keys %{$replicated->schema->storage->replicants};
231
232 does_ok $replicated->schema->storage->replicants->{$replicant_names[0]}
233     => 'DBIx::Class::Storage::DBI::Replicated::Replicant';
234
235 does_ok $replicated->schema->storage->replicants->{$replicant_names[1]}
236     => 'DBIx::Class::Storage::DBI::Replicated::Replicant';  
237
238 ## Add some info to the database
239
240 $replicated
241     ->schema
242     ->populate('Artist', [
243         [ qw/artistid name/ ],
244         [ 4, "Ozric Tentacles"],
245     ]);
246                 
247 ## Make sure all the slaves have the table definitions
248
249 $replicated->replicate;
250 $replicated->schema->storage->replicants->{$replicant_names[0]}->active(1);
251 $replicated->schema->storage->replicants->{$replicant_names[1]}->active(1);
252
253 ## Make sure we can read the data.
254
255 ok my $artist1 = $replicated->schema->resultset('Artist')->find(4)
256     => 'Created Result';
257
258 isa_ok $artist1
259     => 'DBICTest::Artist';
260     
261 is $artist1->name, 'Ozric Tentacles'
262     => 'Found expected name for first result';
263
264 ## Add some new rows that only the master will have  This is because
265 ## we overload any type of write operation so that is must hit the master
266 ## database.
267
268 $replicated
269     ->schema
270     ->populate('Artist', [
271         [ qw/artistid name/ ],
272         [ 5, "Doom's Children"],
273         [ 6, "Dead On Arrival"],
274         [ 7, "Watergate"],
275     ]);
276
277 ## Make sure all the slaves have the table definitions
278 $replicated->replicate;
279
280 ## Should find some data now
281
282 ok my $artist2 = $replicated->schema->resultset('Artist')->find(5)
283     => 'Sync succeed';
284     
285 isa_ok $artist2
286     => 'DBICTest::Artist';
287     
288 is $artist2->name, "Doom's Children"
289     => 'Found expected name for first result';
290
291 ## What happens when we disconnect all the replicants?
292
293 is $replicated->schema->storage->pool->connected_replicants => 2
294     => "both replicants are connected";
295     
296 $replicated->schema->storage->replicants->{$replicant_names[0]}->disconnect;
297 $replicated->schema->storage->replicants->{$replicant_names[1]}->disconnect;
298
299 is $replicated->schema->storage->pool->connected_replicants => 0
300     => "both replicants are now disconnected";
301
302 ## All these should pass, since the database should automatically reconnect
303
304 ok my $artist3 = $replicated->schema->resultset('Artist')->find(6)
305     => 'Still finding stuff.';
306     
307 isa_ok $artist3
308     => 'DBICTest::Artist';
309     
310 is $artist3->name, "Dead On Arrival"
311     => 'Found expected name for first result';
312
313 is $replicated->schema->storage->pool->connected_replicants => 1
314     => "One replicant reconnected to handle the job";
315     
316 ## What happens when we try to select something that doesn't exist?
317
318 ok ! $replicated->schema->resultset('Artist')->find(666)
319     => 'Correctly failed to find something.';
320     
321 ## test the reliable option
322
323 TESTRELIABLE: {
324         
325         $replicated->schema->storage->set_reliable_storage;
326         
327         ok $replicated->schema->resultset('Artist')->find(2)
328             => 'Read from master 1';
329         
330         ok $replicated->schema->resultset('Artist')->find(5)
331             => 'Read from master 2';
332             
333     $replicated->schema->storage->set_balanced_storage;     
334             
335         ok $replicated->schema->resultset('Artist')->find(3)
336         => 'Read from replicant';
337 }
338
339 ## Make sure when reliable goes out of scope, we are using replicants again
340
341 ok $replicated->schema->resultset('Artist')->find(1)
342     => 'back to replicant 1.';
343     
344 ok $replicated->schema->resultset('Artist')->find(2)
345     => 'back to replicant 2.';
346
347 ## set all the replicants to inactive, and make sure the balancer falls back to
348 ## the master.
349
350 $replicated->schema->storage->replicants->{$replicant_names[0]}->active(0);
351 $replicated->schema->storage->replicants->{$replicant_names[1]}->active(0);
352     
353 ok $replicated->schema->resultset('Artist')->find(2)
354     => 'Fallback to master';
355
356 $replicated->schema->storage->replicants->{$replicant_names[0]}->active(1);
357 $replicated->schema->storage->replicants->{$replicant_names[1]}->active(1);
358
359 ok $replicated->schema->resultset('Artist')->find(2)
360     => 'Returned to replicates';
361     
362 ## Getting slave status tests
363
364 SKIP: {
365     ## We skip this tests unless you have a custom replicants, since the default
366     ## sqlite based replication tests don't support these functions.
367     
368     skip 'Cannot Test Replicant Status on Non Replicating Database', 9
369      unless DBICTest->has_custom_dsn && $ENV{"DBICTEST_SLAVE0_DSN"};
370
371     $replicated->replicate; ## Give the slaves a chance to catchup.
372
373         ok $replicated->schema->storage->replicants->{$replicant_names[0]}->is_replicating
374             => 'Replicants are replicating';
375             
376         is $replicated->schema->storage->replicants->{$replicant_names[0]}->lag_behind_master, 0
377             => 'Replicant is zero seconds behind master';
378             
379         ## Test the validate replicants
380         
381         $replicated->schema->storage->pool->validate_replicants;
382         
383         is $replicated->schema->storage->pool->active_replicants, 2
384             => 'Still have 2 replicants after validation';
385             
386         ## Force the replicants to fail the validate test by required their lag to
387         ## be negative (ie ahead of the master!)
388         
389     $replicated->schema->storage->pool->maximum_lag(-10);
390     $replicated->schema->storage->pool->validate_replicants;
391     
392     is $replicated->schema->storage->pool->active_replicants, 0
393         => 'No way a replicant be be ahead of the master';
394         
395     ## Let's be fair to the replicants again.  Let them lag up to 5
396         
397     $replicated->schema->storage->pool->maximum_lag(5);
398     $replicated->schema->storage->pool->validate_replicants;
399     
400     is $replicated->schema->storage->pool->active_replicants, 2
401         => 'Both replicants in good standing again';    
402         
403         ## Check auto validate
404         
405         is $replicated->schema->storage->balancer->auto_validate_every, 100
406             => "Got the expected value for auto validate";
407             
408                 ## This will make sure we auto validatge everytime
409                 $replicated->schema->storage->balancer->auto_validate_every(0);
410                 
411                 ## set all the replicants to inactive, and make sure the balancer falls back to
412                 ## the master.
413                 
414                 $replicated->schema->storage->replicants->{$replicant_names[0]}->active(0);
415                 $replicated->schema->storage->replicants->{$replicant_names[1]}->active(0);
416                 
417                 ## Ok, now when we go to run a query, autovalidate SHOULD reconnect
418         
419         is $replicated->schema->storage->pool->active_replicants => 0
420             => "both replicants turned off";
421                 
422         ok $replicated->schema->resultset('Artist')->find(5)
423             => 'replicant reactivated';
424             
425         is $replicated->schema->storage->pool->active_replicants => 2
426             => "both replicants reactivated";        
427 }
428
429 ## Test the reliably callback
430
431 ok my $reliably = sub {
432         
433     ok $replicated->schema->resultset('Artist')->find(5)
434         => 'replicant reactivated';     
435         
436 } => 'created coderef properly';
437
438 $replicated->schema->storage->execute_reliably($reliably);
439
440 ## Try something with an error
441
442 ok my $unreliably = sub {
443     
444     ok $replicated->schema->resultset('ArtistXX')->find(5)
445         => 'replicant reactivated'; 
446     
447 } => 'created coderef properly';
448
449 throws_ok {$replicated->schema->storage->execute_reliably($unreliably)} 
450     qr/Can't find source for ArtistXX/
451     => 'Bad coderef throws proper error';
452     
453 ## Make sure replication came back
454
455 ok $replicated->schema->resultset('Artist')->find(3)
456     => 'replicant reactivated';
457     
458 ## make sure transactions are set to execute_reliably
459
460 ok my $transaction = sub {
461         
462         my $id = shift @_;
463         
464         $replicated
465             ->schema
466             ->populate('Artist', [
467                 [ qw/artistid name/ ],
468                 [ $id, "Children of the Grave"],
469             ]);
470             
471     ok my $result = $replicated->schema->resultset('Artist')->find($id)
472         => 'Found expected artist';
473         
474     ok my $more = $replicated->schema->resultset('Artist')->find(1)
475         => 'Found expected artist again';
476         
477    return ($result, $more);
478    
479 } => 'Created a coderef properly';
480
481 ## Test the transaction with multi return
482 {
483         ok my @return = $replicated->schema->txn_do($transaction, 666)
484             => 'did transaction';
485             
486             is $return[0]->id, 666
487                 => 'first returned value is correct';
488                 
489             is $return[1]->id, 1
490                 => 'second returned value is correct';
491 }
492
493 ## Test that asking for single return works
494 {
495         ok my $return = $replicated->schema->txn_do($transaction, 777)
496             => 'did transaction';
497             
498             is $return->id, 777
499                 => 'first returned value is correct';
500 }
501
502 ## Test transaction returning a single value
503
504 {
505         ok my $result = $replicated->schema->txn_do(sub {
506                 ok my $more = $replicated->schema->resultset('Artist')->find(1)
507                 => 'found inside a transaction';
508                 return $more;
509         }) => 'successfully processed transaction';
510         
511         is $result->id, 1
512            => 'Got expected single result from transaction';
513 }
514
515 ## Make sure replication came back
516
517 ok $replicated->schema->resultset('Artist')->find(1)
518     => 'replicant reactivated';
519     
520 ## Test Discard changes
521
522 {
523         ok my $artist = $replicated->schema->resultset('Artist')->find(2)
524             => 'got an artist to test discard changes';
525             
526         ok $artist->discard_changes
527            => 'properly discard changes';
528 }
529
530 ## Test some edge cases, like trying to do a transaction inside a transaction, etc
531
532 {
533     ok my $result = $replicated->schema->txn_do(sub {
534         return $replicated->schema->txn_do(sub {
535                 ok my $more = $replicated->schema->resultset('Artist')->find(1)
536                 => 'found inside a transaction inside a transaction';
537                 return $more;                   
538         });
539     }) => 'successfully processed transaction';
540     
541     is $result->id, 1
542        => 'Got expected single result from transaction';          
543 }
544
545 {
546     ok my $result = $replicated->schema->txn_do(sub {
547         return $replicated->schema->storage->execute_reliably(sub {
548                 return $replicated->schema->txn_do(sub {
549                         return $replicated->schema->storage->execute_reliably(sub {
550                                 ok my $more = $replicated->schema->resultset('Artist')->find(1)
551                                 => 'found inside crazy deep transactions and execute_reliably';
552                                 return $more;                           
553                         });
554                 });     
555         });
556     }) => 'successfully processed transaction';
557     
558     is $result->id, 1
559        => 'Got expected single result from transaction';          
560 }     
561
562 ## Test the force_pool resultset attribute.
563
564 {
565         ok my $artist_rs = $replicated->schema->resultset('Artist')
566         => 'got artist resultset';
567            
568         ## Turn on Forced Pool Storage
569         ok my $reliable_artist_rs = $artist_rs->search(undef, {force_pool=>'master'})
570         => 'Created a resultset using force_pool storage';
571            
572     ok my $artist = $reliable_artist_rs->find(2) 
573         => 'got an artist result via force_pool storage';
574 }
575
576 ## Delete the old database files
577 $replicated->cleanup;
578
579
580
581
582
583