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
364 no warnings qw/once redefine/;
367 *DBIx::Class::Storage::DBI::Replicated::Balancer::Random::_random_number =
370 $replicated->schema->storage->balancer->increment_storage;
372 is $replicated->schema->storage->balancer->current_replicant,
373 $replicated->schema->storage->master
374 => 'master_read_weight is honored';
376 ## turn it off for the duration of the test
377 $replicated->schema->storage->balancer->master_read_weight(0);
378 $replicated->schema->storage->balancer->increment_storage;
381 ## Add some new rows that only the master will have This is because
382 ## we overload any type of write operation so that is must hit the master
387 ->populate('Artist', [
388 [ qw/artistid name/ ],
389 [ 5, "Doom's Children"],
390 [ 6, "Dead On Arrival"],
394 ## Make sure all the slaves have the table definitions
395 $replicated->replicate;
397 ## Should find some data now
399 ok my $artist2 = $replicated->schema->resultset('Artist')->find(5)
403 => 'DBICTest::Artist';
405 is $artist2->name, "Doom's Children"
406 => 'Found expected name for first result';
408 ## What happens when we disconnect all the replicants?
410 is $replicated->schema->storage->pool->connected_replicants => 2
411 => "both replicants are connected";
413 $replicated->schema->storage->replicants->{$replicant_names[0]}->disconnect;
414 $replicated->schema->storage->replicants->{$replicant_names[1]}->disconnect;
416 is $replicated->schema->storage->pool->connected_replicants => 0
417 => "both replicants are now disconnected";
419 ## All these should pass, since the database should automatically reconnect
421 ok my $artist3 = $replicated->schema->resultset('Artist')->find(6)
422 => 'Still finding stuff.';
425 => 'DBICTest::Artist';
427 is $artist3->name, "Dead On Arrival"
428 => 'Found expected name for first result';
430 is $replicated->schema->storage->pool->connected_replicants => 1
431 => "At Least One replicant reconnected to handle the job";
433 ## What happens when we try to select something that doesn't exist?
435 ok ! $replicated->schema->resultset('Artist')->find(666)
436 => 'Correctly failed to find something.';
438 ## test the reliable option
442 $replicated->schema->storage->set_reliable_storage;
444 ok $replicated->schema->resultset('Artist')->find(2)
445 => 'Read from master 1';
447 ok $replicated->schema->resultset('Artist')->find(5)
448 => 'Read from master 2';
450 $replicated->schema->storage->set_balanced_storage;
452 ok $replicated->schema->resultset('Artist')->find(3)
453 => 'Read from replicant';
456 ## Make sure when reliable goes out of scope, we are using replicants again
458 ok $replicated->schema->resultset('Artist')->find(1)
459 => 'back to replicant 1.';
461 ok $replicated->schema->resultset('Artist')->find(2)
462 => 'back to replicant 2.';
464 ## set all the replicants to inactive, and make sure the balancer falls back to
467 $replicated->schema->storage->replicants->{$replicant_names[0]}->active(0);
468 $replicated->schema->storage->replicants->{$replicant_names[1]}->active(0);
471 ## catch the fallback to master warning
472 open my $debugfh, '>', \my $fallback_warning;
473 my $oldfh = $replicated->schema->storage->debugfh;
474 $replicated->schema->storage->debugfh($debugfh);
476 ok $replicated->schema->resultset('Artist')->find(2)
477 => 'Fallback to master';
479 like $fallback_warning, qr/falling back to master/
480 => 'emits falling back to master warning';
482 $replicated->schema->storage->debugfh($oldfh);
485 $replicated->schema->storage->replicants->{$replicant_names[0]}->active(1);
486 $replicated->schema->storage->replicants->{$replicant_names[1]}->active(1);
488 ## Silence warning about not supporting the is_replicating method if using the
490 $replicated->schema->storage->debugobj->silence(1)
491 if first { m{^t/} } @replicant_names;
493 $replicated->schema->storage->pool->validate_replicants;
495 $replicated->schema->storage->debugobj->silence(0);
497 ok $replicated->schema->resultset('Artist')->find(2)
498 => 'Returned to replicates';
500 ## Getting slave status tests
503 ## We skip this tests unless you have a custom replicants, since the default
504 ## sqlite based replication tests don't support these functions.
506 skip 'Cannot Test Replicant Status on Non Replicating Database', 9
507 unless DBICTest->has_custom_dsn && $ENV{"DBICTEST_SLAVE0_DSN"};
509 $replicated->replicate; ## Give the slaves a chance to catchup.
511 ok $replicated->schema->storage->replicants->{$replicant_names[0]}->is_replicating
512 => 'Replicants are replicating';
514 is $replicated->schema->storage->replicants->{$replicant_names[0]}->lag_behind_master, 0
515 => 'Replicant is zero seconds behind master';
517 ## Test the validate replicants
519 $replicated->schema->storage->pool->validate_replicants;
521 is $replicated->schema->storage->pool->active_replicants, 2
522 => 'Still have 2 replicants after validation';
524 ## Force the replicants to fail the validate test by required their lag to
525 ## be negative (ie ahead of the master!)
527 $replicated->schema->storage->pool->maximum_lag(-10);
528 $replicated->schema->storage->pool->validate_replicants;
530 is $replicated->schema->storage->pool->active_replicants, 0
531 => 'No way a replicant be be ahead of the master';
533 ## Let's be fair to the replicants again. Let them lag up to 5
535 $replicated->schema->storage->pool->maximum_lag(5);
536 $replicated->schema->storage->pool->validate_replicants;
538 is $replicated->schema->storage->pool->active_replicants, 2
539 => 'Both replicants in good standing again';
541 ## Check auto validate
543 is $replicated->schema->storage->balancer->auto_validate_every, 100
544 => "Got the expected value for auto validate";
546 ## This will make sure we auto validatge everytime
547 $replicated->schema->storage->balancer->auto_validate_every(0);
549 ## set all the replicants to inactive, and make sure the balancer falls back to
552 $replicated->schema->storage->replicants->{$replicant_names[0]}->active(0);
553 $replicated->schema->storage->replicants->{$replicant_names[1]}->active(0);
555 ## Ok, now when we go to run a query, autovalidate SHOULD reconnect
557 is $replicated->schema->storage->pool->active_replicants => 0
558 => "both replicants turned off";
560 ok $replicated->schema->resultset('Artist')->find(5)
561 => 'replicant reactivated';
563 is $replicated->schema->storage->pool->active_replicants => 2
564 => "both replicants reactivated";
567 ## Test the reliably callback
569 ok my $reliably = sub {
571 ok $replicated->schema->resultset('Artist')->find(5)
572 => 'replicant reactivated';
574 } => 'created coderef properly';
576 $replicated->schema->storage->execute_reliably($reliably);
578 ## Try something with an error
580 ok my $unreliably = sub {
582 ok $replicated->schema->resultset('ArtistXX')->find(5)
583 => 'replicant reactivated';
585 } => 'created coderef properly';
587 throws_ok {$replicated->schema->storage->execute_reliably($unreliably)}
588 qr/Can't find source for ArtistXX/
589 => 'Bad coderef throws proper error';
591 ## Make sure replication came back
593 ok $replicated->schema->resultset('Artist')->find(3)
594 => 'replicant reactivated';
596 ## make sure transactions are set to execute_reliably
598 ok my $transaction = sub {
604 ->populate('Artist', [
605 [ qw/artistid name/ ],
606 [ $id, "Children of the Grave"],
609 ok my $result = $replicated->schema->resultset('Artist')->find($id)
610 => 'Found expected artist';
612 ok my $more = $replicated->schema->resultset('Artist')->find(1)
613 => 'Found expected artist again';
615 return ($result, $more);
617 } => 'Created a coderef properly';
619 ## Test the transaction with multi return
621 ok my @return = $replicated->schema->txn_do($transaction, 666)
622 => 'did transaction';
624 is $return[0]->id, 666
625 => 'first returned value is correct';
628 => 'second returned value is correct';
631 ## Test that asking for single return works
633 ok my $return = $replicated->schema->txn_do($transaction, 777)
634 => 'did transaction';
637 => 'first returned value is correct';
640 ## Test transaction returning a single value
643 ok my $result = $replicated->schema->txn_do(sub {
644 ok my $more = $replicated->schema->resultset('Artist')->find(1)
645 => 'found inside a transaction';
647 }) => 'successfully processed transaction';
650 => 'Got expected single result from transaction';
653 ## Make sure replication came back
655 ok $replicated->schema->resultset('Artist')->find(1)
656 => 'replicant reactivated';
658 ## Test Discard changes
661 ok my $artist = $replicated->schema->resultset('Artist')->find(2)
662 => 'got an artist to test discard changes';
664 ok $artist->discard_changes
665 => 'properly discard changes';
668 ## Test some edge cases, like trying to do a transaction inside a transaction, etc
671 ok my $result = $replicated->schema->txn_do(sub {
672 return $replicated->schema->txn_do(sub {
673 ok my $more = $replicated->schema->resultset('Artist')->find(1)
674 => 'found inside a transaction inside a transaction';
677 }) => 'successfully processed transaction';
680 => 'Got expected single result from transaction';
684 ok my $result = $replicated->schema->txn_do(sub {
685 return $replicated->schema->storage->execute_reliably(sub {
686 return $replicated->schema->txn_do(sub {
687 return $replicated->schema->storage->execute_reliably(sub {
688 ok my $more = $replicated->schema->resultset('Artist')->find(1)
689 => 'found inside crazy deep transactions and execute_reliably';
694 }) => 'successfully processed transaction';
697 => 'Got expected single result from transaction';
700 ## Test the force_pool resultset attribute.
703 ok my $artist_rs = $replicated->schema->resultset('Artist')
704 => 'got artist resultset';
706 ## Turn on Forced Pool Storage
707 ok my $reliable_artist_rs = $artist_rs->search(undef, {force_pool=>'master'})
708 => 'Created a resultset using force_pool storage';
710 ok my $artist = $reliable_artist_rs->find(2)
711 => 'got an artist result via force_pool storage';
714 ## Delete the old database files
715 $replicated->cleanup;