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 ok $replicated->schema->storage->meta
261 => 'has a meta object';
263 isa_ok $replicated->schema->storage->master
264 => 'DBIx::Class::Storage::DBI';
266 isa_ok $replicated->schema->storage->pool
267 => 'DBIx::Class::Storage::DBI::Replicated::Pool';
269 does_ok $replicated->schema->storage->balancer
270 => 'DBIx::Class::Storage::DBI::Replicated::Balancer';
272 ok my @replicant_connects = $replicated->generate_replicant_connect_info
273 => 'got replication connect information';
275 ok my @replicated_storages = $replicated->schema->storage->connect_replicants(@replicant_connects)
276 => 'Created some storages suitable for replicants';
278 ok my @all_storages = $replicated->schema->storage->all_storages
281 is scalar @all_storages,
283 => 'correct number of ->all_storages';
285 is ((grep $_->isa('DBIx::Class::Storage::DBI'), @all_storages),
287 => '->all_storages are correct type');
289 my @all_storage_opts =
290 grep { (reftype($_)||'') eq 'HASH' }
291 map @{ $_->_connect_info }, @all_storages;
293 is ((grep $_->{master_option}, @all_storage_opts),
295 => 'connect_info was merged from master to replicants');
297 my @replicant_names = keys %{ $replicated->schema->storage->replicants };
299 ## Silence warning about not supporting the is_replicating method if using the
301 $replicated->schema->storage->debugobj->silence(1)
302 if first { m{^t/} } @replicant_names;
304 isa_ok $replicated->schema->storage->balancer->current_replicant
305 => 'DBIx::Class::Storage::DBI';
307 $replicated->schema->storage->debugobj->silence(0);
309 ok $replicated->schema->storage->pool->has_replicants
310 => 'does have replicants';
312 is $replicated->schema->storage->pool->num_replicants => 2
313 => 'has two replicants';
315 does_ok $replicated_storages[0]
316 => 'DBIx::Class::Storage::DBI::Replicated::Replicant';
318 does_ok $replicated_storages[1]
319 => 'DBIx::Class::Storage::DBI::Replicated::Replicant';
321 does_ok $replicated->schema->storage->replicants->{$replicant_names[0]}
322 => 'DBIx::Class::Storage::DBI::Replicated::Replicant';
324 does_ok $replicated->schema->storage->replicants->{$replicant_names[1]}
325 => 'DBIx::Class::Storage::DBI::Replicated::Replicant';
327 ## Add some info to the database
331 ->populate('Artist', [
332 [ qw/artistid name/ ],
333 [ 4, "Ozric Tentacles"],
336 ## Make sure all the slaves have the table definitions
338 $replicated->replicate;
339 $replicated->schema->storage->replicants->{$replicant_names[0]}->active(1);
340 $replicated->schema->storage->replicants->{$replicant_names[1]}->active(1);
342 ## Silence warning about not supporting the is_replicating method if using the
344 $replicated->schema->storage->debugobj->silence(1)
345 if first { m{^t/} } @replicant_names;
347 $replicated->schema->storage->pool->validate_replicants;
349 $replicated->schema->storage->debugobj->silence(0);
351 ## Make sure we can read the data.
353 ok my $artist1 = $replicated->schema->resultset('Artist')->find(4)
357 => 'DBICTest::Artist';
359 is $artist1->name, 'Ozric Tentacles'
360 => 'Found expected name for first result';
362 ## Check that master_read_weight is honored
366 # turn off redefined warning
367 local $SIG{__WARN__} = sub {};
370 *DBIx::Class::Storage::DBI::Replicated::Balancer::Random::_random_number =
373 $replicated->schema->storage->balancer->increment_storage;
375 is $replicated->schema->storage->balancer->current_replicant,
376 $replicated->schema->storage->master
377 => 'master_read_weight is honored';
379 ## turn it off for the duration of the test
380 $replicated->schema->storage->balancer->master_read_weight(0);
381 $replicated->schema->storage->balancer->increment_storage;
384 ## Add some new rows that only the master will have This is because
385 ## we overload any type of write operation so that is must hit the master
390 ->populate('Artist', [
391 [ qw/artistid name/ ],
392 [ 5, "Doom's Children"],
393 [ 6, "Dead On Arrival"],
397 ## Make sure all the slaves have the table definitions
398 $replicated->replicate;
400 ## Should find some data now
402 ok my $artist2 = $replicated->schema->resultset('Artist')->find(5)
406 => 'DBICTest::Artist';
408 is $artist2->name, "Doom's Children"
409 => 'Found expected name for first result';
411 ## What happens when we disconnect all the replicants?
413 is $replicated->schema->storage->pool->connected_replicants => 2
414 => "both replicants are connected";
416 $replicated->schema->storage->replicants->{$replicant_names[0]}->disconnect;
417 $replicated->schema->storage->replicants->{$replicant_names[1]}->disconnect;
419 is $replicated->schema->storage->pool->connected_replicants => 0
420 => "both replicants are now disconnected";
422 ## All these should pass, since the database should automatically reconnect
424 ok my $artist3 = $replicated->schema->resultset('Artist')->find(6)
425 => 'Still finding stuff.';
428 => 'DBICTest::Artist';
430 is $artist3->name, "Dead On Arrival"
431 => 'Found expected name for first result';
433 is $replicated->schema->storage->pool->connected_replicants => 1
434 => "At Least One replicant reconnected to handle the job";
436 ## What happens when we try to select something that doesn't exist?
438 ok ! $replicated->schema->resultset('Artist')->find(666)
439 => 'Correctly failed to find something.';
441 ## test the reliable option
445 $replicated->schema->storage->set_reliable_storage;
447 ok $replicated->schema->resultset('Artist')->find(2)
448 => 'Read from master 1';
450 ok $replicated->schema->resultset('Artist')->find(5)
451 => 'Read from master 2';
453 $replicated->schema->storage->set_balanced_storage;
455 ok $replicated->schema->resultset('Artist')->find(3)
456 => 'Read from replicant';
459 ## Make sure when reliable goes out of scope, we are using replicants again
461 ok $replicated->schema->resultset('Artist')->find(1)
462 => 'back to replicant 1.';
464 ok $replicated->schema->resultset('Artist')->find(2)
465 => 'back to replicant 2.';
467 ## set all the replicants to inactive, and make sure the balancer falls back to
470 $replicated->schema->storage->replicants->{$replicant_names[0]}->active(0);
471 $replicated->schema->storage->replicants->{$replicant_names[1]}->active(0);
474 ## catch the fallback to master warning
475 open my $debugfh, '>', \my $fallback_warning;
476 my $oldfh = $replicated->schema->storage->debugfh;
477 $replicated->schema->storage->debugfh($debugfh);
479 ok $replicated->schema->resultset('Artist')->find(2)
480 => 'Fallback to master';
482 like $fallback_warning, qr/falling back to master/
483 => 'emits falling back to master warning';
485 $replicated->schema->storage->debugfh($oldfh);
488 $replicated->schema->storage->replicants->{$replicant_names[0]}->active(1);
489 $replicated->schema->storage->replicants->{$replicant_names[1]}->active(1);
491 ## Silence warning about not supporting the is_replicating method if using the
493 $replicated->schema->storage->debugobj->silence(1)
494 if first { m{^t/} } @replicant_names;
496 $replicated->schema->storage->pool->validate_replicants;
498 $replicated->schema->storage->debugobj->silence(0);
500 ok $replicated->schema->resultset('Artist')->find(2)
501 => 'Returned to replicates';
503 ## Getting slave status tests
506 ## We skip this tests unless you have a custom replicants, since the default
507 ## sqlite based replication tests don't support these functions.
509 skip 'Cannot Test Replicant Status on Non Replicating Database', 9
510 unless DBICTest->has_custom_dsn && $ENV{"DBICTEST_SLAVE0_DSN"};
512 $replicated->replicate; ## Give the slaves a chance to catchup.
514 ok $replicated->schema->storage->replicants->{$replicant_names[0]}->is_replicating
515 => 'Replicants are replicating';
517 is $replicated->schema->storage->replicants->{$replicant_names[0]}->lag_behind_master, 0
518 => 'Replicant is zero seconds behind master';
520 ## Test the validate replicants
522 $replicated->schema->storage->pool->validate_replicants;
524 is $replicated->schema->storage->pool->active_replicants, 2
525 => 'Still have 2 replicants after validation';
527 ## Force the replicants to fail the validate test by required their lag to
528 ## be negative (ie ahead of the master!)
530 $replicated->schema->storage->pool->maximum_lag(-10);
531 $replicated->schema->storage->pool->validate_replicants;
533 is $replicated->schema->storage->pool->active_replicants, 0
534 => 'No way a replicant be be ahead of the master';
536 ## Let's be fair to the replicants again. Let them lag up to 5
538 $replicated->schema->storage->pool->maximum_lag(5);
539 $replicated->schema->storage->pool->validate_replicants;
541 is $replicated->schema->storage->pool->active_replicants, 2
542 => 'Both replicants in good standing again';
544 ## Check auto validate
546 is $replicated->schema->storage->balancer->auto_validate_every, 100
547 => "Got the expected value for auto validate";
549 ## This will make sure we auto validatge everytime
550 $replicated->schema->storage->balancer->auto_validate_every(0);
552 ## set all the replicants to inactive, and make sure the balancer falls back to
555 $replicated->schema->storage->replicants->{$replicant_names[0]}->active(0);
556 $replicated->schema->storage->replicants->{$replicant_names[1]}->active(0);
558 ## Ok, now when we go to run a query, autovalidate SHOULD reconnect
560 is $replicated->schema->storage->pool->active_replicants => 0
561 => "both replicants turned off";
563 ok $replicated->schema->resultset('Artist')->find(5)
564 => 'replicant reactivated';
566 is $replicated->schema->storage->pool->active_replicants => 2
567 => "both replicants reactivated";
570 ## Test the reliably callback
572 ok my $reliably = sub {
574 ok $replicated->schema->resultset('Artist')->find(5)
575 => 'replicant reactivated';
577 } => 'created coderef properly';
579 $replicated->schema->storage->execute_reliably($reliably);
581 ## Try something with an error
583 ok my $unreliably = sub {
585 ok $replicated->schema->resultset('ArtistXX')->find(5)
586 => 'replicant reactivated';
588 } => 'created coderef properly';
590 throws_ok {$replicated->schema->storage->execute_reliably($unreliably)}
591 qr/Can't find source for ArtistXX/
592 => 'Bad coderef throws proper error';
594 ## Make sure replication came back
596 ok $replicated->schema->resultset('Artist')->find(3)
597 => 'replicant reactivated';
599 ## make sure transactions are set to execute_reliably
601 ok my $transaction = sub {
607 ->populate('Artist', [
608 [ qw/artistid name/ ],
609 [ $id, "Children of the Grave"],
612 ok my $result = $replicated->schema->resultset('Artist')->find($id)
613 => 'Found expected artist';
615 ok my $more = $replicated->schema->resultset('Artist')->find(1)
616 => 'Found expected artist again';
618 return ($result, $more);
620 } => 'Created a coderef properly';
622 ## Test the transaction with multi return
624 ok my @return = $replicated->schema->txn_do($transaction, 666)
625 => 'did transaction';
627 is $return[0]->id, 666
628 => 'first returned value is correct';
631 => 'second returned value is correct';
634 ## Test that asking for single return works
636 ok my $return = $replicated->schema->txn_do($transaction, 777)
637 => 'did transaction';
640 => 'first returned value is correct';
643 ## Test transaction returning a single value
646 ok my $result = $replicated->schema->txn_do(sub {
647 ok my $more = $replicated->schema->resultset('Artist')->find(1)
648 => 'found inside a transaction';
650 }) => 'successfully processed transaction';
653 => 'Got expected single result from transaction';
656 ## Make sure replication came back
658 ok $replicated->schema->resultset('Artist')->find(1)
659 => 'replicant reactivated';
661 ## Test Discard changes
664 ok my $artist = $replicated->schema->resultset('Artist')->find(2)
665 => 'got an artist to test discard changes';
667 ok $artist->discard_changes
668 => 'properly discard changes';
671 ## Test some edge cases, like trying to do a transaction inside a transaction, etc
674 ok my $result = $replicated->schema->txn_do(sub {
675 return $replicated->schema->txn_do(sub {
676 ok my $more = $replicated->schema->resultset('Artist')->find(1)
677 => 'found inside a transaction inside a transaction';
680 }) => 'successfully processed transaction';
683 => 'Got expected single result from transaction';
687 ok my $result = $replicated->schema->txn_do(sub {
688 return $replicated->schema->storage->execute_reliably(sub {
689 return $replicated->schema->txn_do(sub {
690 return $replicated->schema->storage->execute_reliably(sub {
691 ok my $more = $replicated->schema->resultset('Artist')->find(1)
692 => 'found inside crazy deep transactions and execute_reliably';
697 }) => 'successfully processed transaction';
700 => 'Got expected single result from transaction';
703 ## Test the force_pool resultset attribute.
706 ok my $artist_rs = $replicated->schema->resultset('Artist')
707 => 'got artist resultset';
709 ## Turn on Forced Pool Storage
710 ok my $reliable_artist_rs = $artist_rs->search(undef, {force_pool=>'master'})
711 => 'Created a resultset using force_pool storage';
713 ok my $artist = $reliable_artist_rs->find(2)
714 => 'got an artist result via force_pool storage';
717 ## Delete the old database files
718 $replicated->cleanup;