7 use List::Util 'first';
8 use Scalar::Util 'reftype';
12 eval "use DBIx::Class::Storage::DBI::Replicated; use Test::Moose";
14 ? ( skip_all => "Deps not installed: $@" )
18 use_ok 'DBIx::Class::Storage::DBI::Replicated::Pool';
19 use_ok 'DBIx::Class::Storage::DBI::Replicated::Balancer';
20 use_ok 'DBIx::Class::Storage::DBI::Replicated::Replicant';
21 use_ok 'DBIx::Class::Storage::DBI::Replicated';
25 This is a test of the replicated storage system. This will work in one of
26 two ways, either it was try to fake replication with a couple of SQLite DBs
27 and creative use of copy, or if you define a couple of %ENV vars correctly
28 will try to test those. If you do that, it will assume the setup is properly
29 replicating. Your results may vary, but I have demonstrated this to work with
30 mysql native replication.
35 ## ----------------------------------------------------------------------------
36 ## Build a class to hold all our required testing data and methods.
37 ## ----------------------------------------------------------------------------
41 ## --------------------------------------------------------------------- ##
42 ## Create an object to contain your replicated stuff.
43 ## --------------------------------------------------------------------- ##
45 package DBIx::Class::DBI::Replicated::TestReplication;
48 use base qw/Class::Accessor::Fast/;
50 __PACKAGE__->mk_accessors( qw/schema/ );
52 ## Initialize the object
55 my ($class, $schema_method) = (shift, shift);
56 my $self = $class->SUPER::new(@_);
58 $self->schema( $self->init_schema($schema_method) );
62 ## Get the Schema and set the replication storage type
65 # current SQLT SQLite producer does not handle DROP TABLE IF EXISTS, trap warnings here
66 local $SIG{__WARN__} = sub { warn @_ unless $_[0] =~ /no such table.+DROP TABLE/ };
68 my ($class, $schema_method) = @_;
70 my $method = "get_schema_$schema_method";
71 my $schema = $class->$method;
76 sub get_schema_by_storage_type {
77 DBICTest->init_schema(
80 '::DBI::Replicated' => {
81 balancer_type=>'::Random',
83 auto_validate_every=>100,
84 master_read_weight => 1
94 sub get_schema_by_connect_info {
95 DBICTest->init_schema(
97 storage_type=> '::DBI::Replicated',
98 balancer_type=>'::Random',
100 auto_validate_every=>100,
101 master_read_weight => 1
109 sub generate_replicant_connect_info {}
113 ## --------------------------------------------------------------------- ##
114 ## Add a connect_info option to test option merging.
115 ## --------------------------------------------------------------------- ##
117 package DBIx::Class::Storage::DBI::Replicated;
121 __PACKAGE__->meta->make_mutable;
123 around connect_info => sub {
124 my ($next, $self, $info) = @_;
125 $info->[3]{master_option} = 1;
129 __PACKAGE__->meta->make_immutable;
134 ## --------------------------------------------------------------------- ##
135 ## Subclass for when you are using SQLite for testing, this provides a fake
136 ## replication support.
137 ## --------------------------------------------------------------------- ##
139 package DBIx::Class::DBI::Replicated::TestReplication::SQLite;
143 use base 'DBIx::Class::DBI::Replicated::TestReplication';
145 __PACKAGE__->mk_accessors( qw/master_path slave_paths/ );
147 ## Set the mastep path from DBICTest
150 my $class = shift @_;
151 my $self = $class->SUPER::new(@_);
153 $self->master_path( DBICTest->_sqlite_dbfilename );
155 "t/var/DBIxClass_slave1.db",
156 "t/var/DBIxClass_slave2.db",
162 ## Return an Array of ArrayRefs where each ArrayRef is suitable to use for
163 ## $storage->connect_info to be used for connecting replicants.
165 sub generate_replicant_connect_info {
169 } @{$self->slave_paths};
171 my @connect_infos = map { [$_,'','',{AutoCommit=>1}] } @dsn;
174 my $c = $connect_infos[0];
175 $connect_infos[0] = {
185 ## Do a 'good enough' replication by copying the master dbfile over each of
186 ## the slave dbfiles. If the master is SQLite we do this, otherwise we
187 ## just do a one second pause to let the slaves catch up.
191 foreach my $slave (@{$self->slave_paths}) {
192 copy($self->master_path, $slave);
196 ## Cleanup after ourselves. Unlink all gthe slave paths.
200 foreach my $slave (@{$self->slave_paths}) {
205 ## --------------------------------------------------------------------- ##
206 ## Subclass for when you are setting the databases via custom export vars
207 ## This is for when you have a replicating database setup that you are
208 ## going to test against. You'll need to define the correct $ENV and have
209 ## two slave databases to test against, as well as a replication system
210 ## that will replicate in less than 1 second.
211 ## --------------------------------------------------------------------- ##
213 package DBIx::Class::DBI::Replicated::TestReplication::Custom;
214 use base 'DBIx::Class::DBI::Replicated::TestReplication';
216 ## Return an Array of ArrayRefs where each ArrayRef is suitable to use for
217 ## $storage->connect_info to be used for connecting replicants.
219 sub generate_replicant_connect_info {
221 [$ENV{"DBICTEST_SLAVE0_DSN"}, $ENV{"DBICTEST_SLAVE0_DBUSER"}, $ENV{"DBICTEST_SLAVE0_DBPASS"}, {AutoCommit => 1}],
222 [$ENV{"DBICTEST_SLAVE1_DSN"}, $ENV{"DBICTEST_SLAVE1_DBUSER"}, $ENV{"DBICTEST_SLAVE1_DBPASS"}, {AutoCommit => 1}],
226 ## pause a bit to let the replication catch up
233 ## ----------------------------------------------------------------------------
234 ## Create an object and run some tests
235 ## ----------------------------------------------------------------------------
237 ## Thi first bunch of tests are basic, just make sure all the bits are behaving
239 my $replicated_class = DBICTest->has_custom_dsn ?
240 'DBIx::Class::DBI::Replicated::TestReplication::Custom' :
241 'DBIx::Class::DBI::Replicated::TestReplication::SQLite';
245 for my $method (qw/by_connect_info by_storage_type/) {
246 ok $replicated = $replicated_class->new($method)
247 => "Created a replication object $method";
249 isa_ok $replicated->schema
250 => 'DBIx::Class::Schema';
252 isa_ok $replicated->schema->storage
253 => 'DBIx::Class::Storage::DBI::Replicated';
255 isa_ok $replicated->schema->storage->balancer
256 => 'DBIx::Class::Storage::DBI::Replicated::Balancer::Random'
257 => 'configured balancer_type';
260 $replicated->schema->storage->debugcb(sub {my ($ob, $info) = @_; warn "\n\n$ob, $info\n\n"});
262 ok $replicated->schema->storage->meta
263 => 'has a meta object';
265 isa_ok $replicated->schema->storage->master
266 => 'DBIx::Class::Storage::DBI';
268 isa_ok $replicated->schema->storage->pool
269 => 'DBIx::Class::Storage::DBI::Replicated::Pool';
271 does_ok $replicated->schema->storage->balancer
272 => 'DBIx::Class::Storage::DBI::Replicated::Balancer';
274 ok my @replicant_connects = $replicated->generate_replicant_connect_info
275 => 'got replication connect information';
277 ok my @replicated_storages = $replicated->schema->storage->connect_replicants(@replicant_connects)
278 => 'Created some storages suitable for replicants';
280 ok my @all_storages = $replicated->schema->storage->all_storages
283 is scalar @all_storages,
285 => 'correct number of ->all_storages';
287 is ((grep $_->isa('DBIx::Class::Storage::DBI'), @all_storages),
289 => '->all_storages are correct type');
291 my @all_storage_opts =
292 grep { (reftype($_)||'') eq 'HASH' }
293 map @{ $_->_connect_info }, @all_storages;
295 is ((grep $_->{master_option}, @all_storage_opts),
297 => 'connect_info was merged from master to replicants');
299 my @replicant_names = keys %{ $replicated->schema->storage->replicants };
301 ok @replicant_names, "found replicant names @replicant_names";
303 ## Silence warning about not supporting the is_replicating method if using the
305 $replicated->schema->storage->debugobj->silence(1)
306 if first { m{^t/} } @replicant_names;
308 isa_ok $replicated->schema->storage->balancer->current_replicant
309 => 'DBIx::Class::Storage::DBI';
311 $replicated->schema->storage->debugobj->silence(0);
313 ok $replicated->schema->storage->pool->has_replicants
314 => 'does have replicants';
316 is $replicated->schema->storage->pool->num_replicants => 2
317 => 'has two replicants';
319 does_ok $replicated_storages[0]
320 => 'DBIx::Class::Storage::DBI::Replicated::Replicant';
322 does_ok $replicated_storages[1]
323 => 'DBIx::Class::Storage::DBI::Replicated::Replicant';
325 does_ok $replicated->schema->storage->replicants->{$replicant_names[0]}
326 => 'DBIx::Class::Storage::DBI::Replicated::Replicant';
328 does_ok $replicated->schema->storage->replicants->{$replicant_names[1]}
329 => 'DBIx::Class::Storage::DBI::Replicated::Replicant';
331 ## Add some info to the database
335 ->populate('Artist', [
336 [ qw/artistid name/ ],
337 [ 4, "Ozric Tentacles"],
340 ## Make sure all the slaves have the table definitions
342 $replicated->replicate;
343 $replicated->schema->storage->replicants->{$replicant_names[0]}->active(1);
344 $replicated->schema->storage->replicants->{$replicant_names[1]}->active(1);
346 ## Silence warning about not supporting the is_replicating method if using the
348 $replicated->schema->storage->debugobj->silence(1)
349 if first { m{^t/} } @replicant_names;
351 $replicated->schema->storage->pool->validate_replicants;
353 $replicated->schema->storage->debugobj->silence(0);
355 ## Make sure we can read the data.
357 ok my $artist1 = $replicated->schema->resultset('Artist')->find(4)
361 => 'DBICTest::Artist';
363 is $artist1->name, 'Ozric Tentacles'
364 => 'Found expected name for first result';
366 ## Check that master_read_weight is honored
368 no warnings qw/once redefine/;
371 *DBIx::Class::Storage::DBI::Replicated::Balancer::Random::_random_number =
374 $replicated->schema->storage->balancer->increment_storage;
376 is $replicated->schema->storage->balancer->current_replicant,
377 $replicated->schema->storage->master
378 => 'master_read_weight is honored';
380 ## turn it off for the duration of the test
381 $replicated->schema->storage->balancer->master_read_weight(0);
382 $replicated->schema->storage->balancer->increment_storage;
385 ## Add some new rows that only the master will have This is because
386 ## we overload any type of write operation so that is must hit the master
391 ->populate('Artist', [
392 [ qw/artistid name/ ],
393 [ 5, "Doom's Children"],
394 [ 6, "Dead On Arrival"],
398 ## Make sure all the slaves have the table definitions
399 $replicated->replicate;
401 ## Should find some data now
403 ok my $artist2 = $replicated->schema->resultset('Artist')->find(5)
407 => 'DBICTest::Artist';
409 is $artist2->name, "Doom's Children"
410 => 'Found expected name for first result';
412 ## What happens when we disconnect all the replicants?
414 is $replicated->schema->storage->pool->connected_replicants => 2
415 => "both replicants are connected";
417 $replicated->schema->storage->replicants->{$replicant_names[0]}->disconnect;
418 $replicated->schema->storage->replicants->{$replicant_names[1]}->disconnect;
420 is $replicated->schema->storage->pool->connected_replicants => 0
421 => "both replicants are now disconnected";
423 ## All these should pass, since the database should automatically reconnect
425 ok my $artist3 = $replicated->schema->resultset('Artist')->find(6)
426 => 'Still finding stuff.';
429 => 'DBICTest::Artist';
431 is $artist3->name, "Dead On Arrival"
432 => 'Found expected name for first result';
434 is $replicated->schema->storage->pool->connected_replicants => 1
435 => "At Least One replicant reconnected to handle the job";
437 ## What happens when we try to select something that doesn't exist?
439 ok ! $replicated->schema->resultset('Artist')->find(666)
440 => 'Correctly failed to find something.';
442 ## test the reliable option
446 $replicated->schema->storage->set_reliable_storage;
448 ok $replicated->schema->resultset('Artist')->find(2)
449 => 'Read from master 1';
451 ok $replicated->schema->resultset('Artist')->find(5)
452 => 'Read from master 2';
454 $replicated->schema->storage->set_balanced_storage;
456 ok $replicated->schema->resultset('Artist')->find(3)
457 => 'Read from replicant';
460 ## Make sure when reliable goes out of scope, we are using replicants again
462 ok $replicated->schema->resultset('Artist')->find(1)
463 => 'back to replicant 1.';
465 ok $replicated->schema->resultset('Artist')->find(2)
466 => 'back to replicant 2.';
468 ## set all the replicants to inactive, and make sure the balancer falls back to
471 $replicated->schema->storage->replicants->{$replicant_names[0]}->active(0);
472 $replicated->schema->storage->replicants->{$replicant_names[1]}->active(0);
475 ## catch the fallback to master warning
476 open my $debugfh, '>', \my $fallback_warning;
477 my $oldfh = $replicated->schema->storage->debugfh;
478 $replicated->schema->storage->debugfh($debugfh);
480 ok $replicated->schema->resultset('Artist')->find(2)
481 => 'Fallback to master';
483 like $fallback_warning, qr/falling back to master/
484 => 'emits falling back to master warning';
486 $replicated->schema->storage->debugfh($oldfh);
489 $replicated->schema->storage->replicants->{$replicant_names[0]}->active(1);
490 $replicated->schema->storage->replicants->{$replicant_names[1]}->active(1);
492 ## Silence warning about not supporting the is_replicating method if using the
494 $replicated->schema->storage->debugobj->silence(1)
495 if first { m{^t/} } @replicant_names;
497 $replicated->schema->storage->pool->validate_replicants;
499 $replicated->schema->storage->debugobj->silence(0);
501 ok $replicated->schema->resultset('Artist')->find(2)
502 => 'Returned to replicates';
504 ## Getting slave status tests
507 ## We skip this tests unless you have a custom replicants, since the default
508 ## sqlite based replication tests don't support these functions.
510 skip 'Cannot Test Replicant Status on Non Replicating Database', 9
511 unless DBICTest->has_custom_dsn && $ENV{"DBICTEST_SLAVE0_DSN"};
513 $replicated->replicate; ## Give the slaves a chance to catchup.
515 ok $replicated->schema->storage->replicants->{$replicant_names[0]}->is_replicating
516 => 'Replicants are replicating';
518 is $replicated->schema->storage->replicants->{$replicant_names[0]}->lag_behind_master, 0
519 => 'Replicant is zero seconds behind master';
521 ## Test the validate replicants
523 $replicated->schema->storage->pool->validate_replicants;
525 is $replicated->schema->storage->pool->active_replicants, 2
526 => 'Still have 2 replicants after validation';
528 ## Force the replicants to fail the validate test by required their lag to
529 ## be negative (ie ahead of the master!)
531 $replicated->schema->storage->pool->maximum_lag(-10);
532 $replicated->schema->storage->pool->validate_replicants;
534 is $replicated->schema->storage->pool->active_replicants, 0
535 => 'No way a replicant be be ahead of the master';
537 ## Let's be fair to the replicants again. Let them lag up to 5
539 $replicated->schema->storage->pool->maximum_lag(5);
540 $replicated->schema->storage->pool->validate_replicants;
542 is $replicated->schema->storage->pool->active_replicants, 2
543 => 'Both replicants in good standing again';
545 ## Check auto validate
547 is $replicated->schema->storage->balancer->auto_validate_every, 100
548 => "Got the expected value for auto validate";
550 ## This will make sure we auto validatge everytime
551 $replicated->schema->storage->balancer->auto_validate_every(0);
553 ## set all the replicants to inactive, and make sure the balancer falls back to
556 $replicated->schema->storage->replicants->{$replicant_names[0]}->active(0);
557 $replicated->schema->storage->replicants->{$replicant_names[1]}->active(0);
559 ## Ok, now when we go to run a query, autovalidate SHOULD reconnect
561 is $replicated->schema->storage->pool->active_replicants => 0
562 => "both replicants turned off";
564 ok $replicated->schema->resultset('Artist')->find(5)
565 => 'replicant reactivated';
567 is $replicated->schema->storage->pool->active_replicants => 2
568 => "both replicants reactivated";
571 ## Test the reliably callback
573 ok my $reliably = sub {
575 ok $replicated->schema->resultset('Artist')->find(5)
576 => 'replicant reactivated';
578 } => 'created coderef properly';
580 $replicated->schema->storage->execute_reliably($reliably);
582 ## Try something with an error
584 ok my $unreliably = sub {
586 ok $replicated->schema->resultset('ArtistXX')->find(5)
587 => 'replicant reactivated';
589 } => 'created coderef properly';
591 throws_ok {$replicated->schema->storage->execute_reliably($unreliably)}
592 qr/Can't find source for ArtistXX/
593 => 'Bad coderef throws proper error';
595 ## Make sure replication came back
597 ok $replicated->schema->resultset('Artist')->find(3)
598 => 'replicant reactivated';
600 ## make sure transactions are set to execute_reliably
602 ok my $transaction = sub {
608 ->populate('Artist', [
609 [ qw/artistid name/ ],
610 [ $id, "Children of the Grave"],
613 ok my $result = $replicated->schema->resultset('Artist')->find($id)
614 => "Found expected artist for $id";
616 ok my $more = $replicated->schema->resultset('Artist')->find(1)
617 => 'Found expected artist again for 1';
619 return ($result, $more);
621 } => 'Created a coderef properly';
623 ## Test the transaction with multi return
625 ok my @return = $replicated->schema->txn_do($transaction, 666)
626 => 'did transaction';
628 is $return[0]->id, 666
629 => 'first returned value is correct';
632 => 'second returned value is correct';
635 ## Test that asking for single return works
637 ok my @return = $replicated->schema->txn_do($transaction, 777)
638 => 'did transaction';
640 is $return[0]->id, 777
641 => 'first returned value is correct';
644 => 'second returned value is correct';
647 ## Test transaction returning a single value
650 ok my $result = $replicated->schema->txn_do(sub {
651 ok my $more = $replicated->schema->resultset('Artist')->find(1)
652 => 'found inside a transaction';
654 }) => 'successfully processed transaction';
657 => 'Got expected single result from transaction';
660 ## Make sure replication came back
662 ok $replicated->schema->resultset('Artist')->find(1)
663 => 'replicant reactivated';
665 ## Test Discard changes
668 ok my $artist = $replicated->schema->resultset('Artist')->find(2)
669 => 'got an artist to test discard changes';
671 ok $artist->discard_changes
672 => 'properly discard changes';
675 ## Test some edge cases, like trying to do a transaction inside a transaction, etc
678 ok my $result = $replicated->schema->txn_do(sub {
679 return $replicated->schema->txn_do(sub {
680 ok my $more = $replicated->schema->resultset('Artist')->find(1)
681 => 'found inside a transaction inside a transaction';
684 }) => 'successfully processed transaction';
687 => 'Got expected single result from transaction';
691 ok my $result = $replicated->schema->txn_do(sub {
692 return $replicated->schema->storage->execute_reliably(sub {
693 return $replicated->schema->txn_do(sub {
694 return $replicated->schema->storage->execute_reliably(sub {
695 ok my $more = $replicated->schema->resultset('Artist')->find(1)
696 => 'found inside crazy deep transactions and execute_reliably';
701 }) => 'successfully processed transaction';
704 => 'Got expected single result from transaction';
707 ## Test the force_pool resultset attribute.
710 ok my $artist_rs = $replicated->schema->resultset('Artist')
711 => 'got artist resultset';
713 ## Turn on Forced Pool Storage
714 ok my $reliable_artist_rs = $artist_rs->search(undef, {force_pool=>'master'})
715 => 'Created a resultset using force_pool storage';
717 ok my $artist = $reliable_artist_rs->find(2)
718 => 'got an artist result via force_pool storage';
721 ## Test the force_pool resultset attribute part two.
724 ok my $artist_rs = $replicated->schema->resultset('Artist')
725 => 'got artist resultset';
727 ## Turn on Forced Pool Storage
728 ok my $reliable_artist_rs = $artist_rs->search(undef, {force_pool=>$replicant_names[0]})
729 => 'Created a resultset using force_pool storage';
731 ok my $artist = $reliable_artist_rs->find(2)
732 => 'got an artist result via force_pool storage';
734 ## Delete the old database files
735 $replicated->cleanup;