7 use List::Util 'first';
8 use Scalar::Util 'reftype';
11 eval "use DBIx::Class::Storage::DBI::Replicated; use Test::Moose";
13 ? ( skip_all => "Deps not installed: $@" )
17 use_ok 'DBIx::Class::Storage::DBI::Replicated::Pool';
18 use_ok 'DBIx::Class::Storage::DBI::Replicated::Balancer';
19 use_ok 'DBIx::Class::Storage::DBI::Replicated::Replicant';
20 use_ok 'DBIx::Class::Storage::DBI::Replicated';
24 This is a test of the replicated storage system. This will work in one of
25 two ways, either it was try to fake replication with a couple of SQLite DBs
26 and creative use of copy, or if you define a couple of %ENV vars correctly
27 will try to test those. If you do that, it will assume the setup is properly
28 replicating. Your results may vary, but I have demonstrated this to work with
29 mysql native replication.
34 ## ----------------------------------------------------------------------------
35 ## Build a class to hold all our required testing data and methods.
36 ## ----------------------------------------------------------------------------
40 ## --------------------------------------------------------------------- ##
41 ## Create an object to contain your replicated stuff.
42 ## --------------------------------------------------------------------- ##
44 package DBIx::Class::DBI::Replicated::TestReplication;
47 use base qw/Class::Accessor::Fast/;
49 __PACKAGE__->mk_accessors( qw/schema/ );
51 ## Initialize the object
54 my ($class, $schema_method) = (shift, shift);
55 my $self = $class->SUPER::new(@_);
57 $self->schema( $self->init_schema($schema_method) );
61 ## Get the Schema and set the replication storage type
64 # current SQLT SQLite producer does not handle DROP TABLE IF EXISTS, trap warnings here
65 local $SIG{__WARN__} = sub { warn @_ unless $_[0] =~ /no such table.+DROP TABLE/ };
67 my ($class, $schema_method) = @_;
69 my $method = "get_schema_$schema_method";
70 my $schema = $class->$method;
75 sub get_schema_by_storage_type {
76 DBICTest->init_schema(
79 '::DBI::Replicated' => {
80 balancer_type=>'::Random',
82 auto_validate_every=>100,
83 master_read_weight => 1
93 sub get_schema_by_connect_info {
94 DBICTest->init_schema(
96 storage_type=> '::DBI::Replicated',
97 balancer_type=>'::Random',
99 auto_validate_every=>100,
100 master_read_weight => 1
108 sub generate_replicant_connect_info {}
112 ## --------------------------------------------------------------------- ##
113 ## Add a connect_info option to test option merging.
114 ## --------------------------------------------------------------------- ##
116 package DBIx::Class::Storage::DBI::Replicated;
120 __PACKAGE__->meta->make_mutable;
122 around connect_info => sub {
123 my ($next, $self, $info) = @_;
124 $info->[3]{master_option} = 1;
128 __PACKAGE__->meta->make_immutable;
133 ## --------------------------------------------------------------------- ##
134 ## Subclass for when you are using SQLite for testing, this provides a fake
135 ## replication support.
136 ## --------------------------------------------------------------------- ##
138 package DBIx::Class::DBI::Replicated::TestReplication::SQLite;
142 use base 'DBIx::Class::DBI::Replicated::TestReplication';
144 __PACKAGE__->mk_accessors( qw/master_path slave_paths/ );
146 ## Set the mastep path from DBICTest
149 my $class = shift @_;
150 my $self = $class->SUPER::new(@_);
152 $self->master_path( DBICTest->_sqlite_dbfilename );
154 "t/var/DBIxClass_slave1.db",
155 "t/var/DBIxClass_slave2.db",
161 ## Return an Array of ArrayRefs where each ArrayRef is suitable to use for
162 ## $storage->connect_info to be used for connecting replicants.
164 sub generate_replicant_connect_info {
168 } @{$self->slave_paths};
170 my @connect_infos = map { [$_,'','',{AutoCommit=>1}] } @dsn;
173 my $c = $connect_infos[0];
174 $connect_infos[0] = {
184 ## Do a 'good enough' replication by copying the master dbfile over each of
185 ## the slave dbfiles. If the master is SQLite we do this, otherwise we
186 ## just do a one second pause to let the slaves catch up.
190 foreach my $slave (@{$self->slave_paths}) {
191 copy($self->master_path, $slave);
195 ## Cleanup after ourselves. Unlink all gthe slave paths.
199 foreach my $slave (@{$self->slave_paths}) {
204 ## --------------------------------------------------------------------- ##
205 ## Subclass for when you are setting the databases via custom export vars
206 ## This is for when you have a replicating database setup that you are
207 ## going to test against. You'll need to define the correct $ENV and have
208 ## two slave databases to test against, as well as a replication system
209 ## that will replicate in less than 1 second.
210 ## --------------------------------------------------------------------- ##
212 package DBIx::Class::DBI::Replicated::TestReplication::Custom;
213 use base 'DBIx::Class::DBI::Replicated::TestReplication';
215 ## Return an Array of ArrayRefs where each ArrayRef is suitable to use for
216 ## $storage->connect_info to be used for connecting replicants.
218 sub generate_replicant_connect_info {
220 [$ENV{"DBICTEST_SLAVE0_DSN"}, $ENV{"DBICTEST_SLAVE0_DBUSER"}, $ENV{"DBICTEST_SLAVE0_DBPASS"}, {AutoCommit => 1}],
221 [$ENV{"DBICTEST_SLAVE1_DSN"}, $ENV{"DBICTEST_SLAVE1_DBUSER"}, $ENV{"DBICTEST_SLAVE1_DBPASS"}, {AutoCommit => 1}],
225 ## pause a bit to let the replication catch up
232 ## ----------------------------------------------------------------------------
233 ## Create an object and run some tests
234 ## ----------------------------------------------------------------------------
236 ## Thi first bunch of tests are basic, just make sure all the bits are behaving
238 my $replicated_class = DBICTest->has_custom_dsn ?
239 'DBIx::Class::DBI::Replicated::TestReplication::Custom' :
240 'DBIx::Class::DBI::Replicated::TestReplication::SQLite';
244 for my $method (qw/by_connect_info by_storage_type/) {
245 ok $replicated = $replicated_class->new($method)
246 => "Created a replication object $method";
248 isa_ok $replicated->schema
249 => 'DBIx::Class::Schema';
251 isa_ok $replicated->schema->storage
252 => 'DBIx::Class::Storage::DBI::Replicated';
254 isa_ok $replicated->schema->storage->balancer
255 => 'DBIx::Class::Storage::DBI::Replicated::Balancer::Random'
256 => 'configured balancer_type';
259 ok $replicated->schema->storage->meta
260 => 'has a meta object';
262 isa_ok $replicated->schema->storage->master
263 => 'DBIx::Class::Storage::DBI';
265 isa_ok $replicated->schema->storage->pool
266 => 'DBIx::Class::Storage::DBI::Replicated::Pool';
268 does_ok $replicated->schema->storage->balancer
269 => 'DBIx::Class::Storage::DBI::Replicated::Balancer';
271 ok my @replicant_connects = $replicated->generate_replicant_connect_info
272 => 'got replication connect information';
274 ok my @replicated_storages = $replicated->schema->storage->connect_replicants(@replicant_connects)
275 => 'Created some storages suitable for replicants';
277 ok my @all_storages = $replicated->schema->storage->all_storages
280 is scalar @all_storages,
282 => 'correct number of ->all_storages';
284 is ((grep $_->isa('DBIx::Class::Storage::DBI'), @all_storages),
286 => '->all_storages are correct type');
288 my @all_storage_opts =
289 grep { (reftype($_)||'') eq 'HASH' }
290 map @{ $_->_connect_info }, @all_storages;
292 is ((grep $_->{master_option}, @all_storage_opts),
294 => 'connect_info was merged from master to replicants');
296 my @replicant_names = keys %{ $replicated->schema->storage->replicants };
298 ## Silence warning about not supporting the is_replicating method if using the
300 $replicated->schema->storage->debugobj->silence(1)
301 if first { m{^t/} } @replicant_names;
303 isa_ok $replicated->schema->storage->balancer->current_replicant
304 => 'DBIx::Class::Storage::DBI';
306 $replicated->schema->storage->debugobj->silence(0);
308 ok $replicated->schema->storage->pool->has_replicants
309 => 'does have replicants';
311 is $replicated->schema->storage->pool->num_replicants => 2
312 => 'has two replicants';
314 does_ok $replicated_storages[0]
315 => 'DBIx::Class::Storage::DBI::Replicated::Replicant';
317 does_ok $replicated_storages[1]
318 => 'DBIx::Class::Storage::DBI::Replicated::Replicant';
320 does_ok $replicated->schema->storage->replicants->{$replicant_names[0]}
321 => 'DBIx::Class::Storage::DBI::Replicated::Replicant';
323 does_ok $replicated->schema->storage->replicants->{$replicant_names[1]}
324 => 'DBIx::Class::Storage::DBI::Replicated::Replicant';
326 ## Add some info to the database
330 ->populate('Artist', [
331 [ qw/artistid name/ ],
332 [ 4, "Ozric Tentacles"],
335 ## Make sure all the slaves have the table definitions
337 $replicated->replicate;
338 $replicated->schema->storage->replicants->{$replicant_names[0]}->active(1);
339 $replicated->schema->storage->replicants->{$replicant_names[1]}->active(1);
341 ## Silence warning about not supporting the is_replicating method if using the
343 $replicated->schema->storage->debugobj->silence(1)
344 if first { m{^t/} } @replicant_names;
346 $replicated->schema->storage->pool->validate_replicants;
348 $replicated->schema->storage->debugobj->silence(0);
350 ## Make sure we can read the data.
352 ok my $artist1 = $replicated->schema->resultset('Artist')->find(4)
356 => 'DBICTest::Artist';
358 is $artist1->name, 'Ozric Tentacles'
359 => 'Found expected name for first result';
361 ## Check that master_read_weight is honored
365 # turn off redefined warning
366 local $SIG{__WARN__} = sub {};
369 *DBIx::Class::Storage::DBI::Replicated::Balancer::Random::random_number =
372 $replicated->schema->storage->balancer->increment_storage;
374 is $replicated->schema->storage->balancer->current_replicant,
375 $replicated->schema->storage->master
376 => 'master_read_weight is honored';
378 ## turn it off for the duration of the test
379 $replicated->schema->storage->balancer->master_read_weight(0);
380 $replicated->schema->storage->balancer->increment_storage;
383 ## Add some new rows that only the master will have This is because
384 ## we overload any type of write operation so that is must hit the master
389 ->populate('Artist', [
390 [ qw/artistid name/ ],
391 [ 5, "Doom's Children"],
392 [ 6, "Dead On Arrival"],
396 ## Make sure all the slaves have the table definitions
397 $replicated->replicate;
399 ## Should find some data now
401 ok my $artist2 = $replicated->schema->resultset('Artist')->find(5)
405 => 'DBICTest::Artist';
407 is $artist2->name, "Doom's Children"
408 => 'Found expected name for first result';
410 ## What happens when we disconnect all the replicants?
412 is $replicated->schema->storage->pool->connected_replicants => 2
413 => "both replicants are connected";
415 $replicated->schema->storage->replicants->{$replicant_names[0]}->disconnect;
416 $replicated->schema->storage->replicants->{$replicant_names[1]}->disconnect;
418 is $replicated->schema->storage->pool->connected_replicants => 0
419 => "both replicants are now disconnected";
421 ## All these should pass, since the database should automatically reconnect
423 ok my $artist3 = $replicated->schema->resultset('Artist')->find(6)
424 => 'Still finding stuff.';
427 => 'DBICTest::Artist';
429 is $artist3->name, "Dead On Arrival"
430 => 'Found expected name for first result';
432 is $replicated->schema->storage->pool->connected_replicants => 1
433 => "At Least One replicant reconnected to handle the job";
435 ## What happens when we try to select something that doesn't exist?
437 ok ! $replicated->schema->resultset('Artist')->find(666)
438 => 'Correctly failed to find something.';
440 ## test the reliable option
444 $replicated->schema->storage->set_reliable_storage;
446 ok $replicated->schema->resultset('Artist')->find(2)
447 => 'Read from master 1';
449 ok $replicated->schema->resultset('Artist')->find(5)
450 => 'Read from master 2';
452 $replicated->schema->storage->set_balanced_storage;
454 ok $replicated->schema->resultset('Artist')->find(3)
455 => 'Read from replicant';
458 ## Make sure when reliable goes out of scope, we are using replicants again
460 ok $replicated->schema->resultset('Artist')->find(1)
461 => 'back to replicant 1.';
463 ok $replicated->schema->resultset('Artist')->find(2)
464 => 'back to replicant 2.';
466 ## set all the replicants to inactive, and make sure the balancer falls back to
469 $replicated->schema->storage->replicants->{$replicant_names[0]}->active(0);
470 $replicated->schema->storage->replicants->{$replicant_names[1]}->active(0);
472 ## Silence warning about falling back to master.
473 $replicated->schema->storage->debugobj->silence(1);
475 ok $replicated->schema->resultset('Artist')->find(2)
476 => 'Fallback to master';
478 $replicated->schema->storage->debugobj->silence(0);
480 $replicated->schema->storage->replicants->{$replicant_names[0]}->active(1);
481 $replicated->schema->storage->replicants->{$replicant_names[1]}->active(1);
483 ## Silence warning about not supporting the is_replicating method if using the
485 $replicated->schema->storage->debugobj->silence(1)
486 if first { m{^t/} } @replicant_names;
488 $replicated->schema->storage->pool->validate_replicants;
490 $replicated->schema->storage->debugobj->silence(0);
492 ok $replicated->schema->resultset('Artist')->find(2)
493 => 'Returned to replicates';
495 ## Getting slave status tests
498 ## We skip this tests unless you have a custom replicants, since the default
499 ## sqlite based replication tests don't support these functions.
501 skip 'Cannot Test Replicant Status on Non Replicating Database', 9
502 unless DBICTest->has_custom_dsn && $ENV{"DBICTEST_SLAVE0_DSN"};
504 $replicated->replicate; ## Give the slaves a chance to catchup.
506 ok $replicated->schema->storage->replicants->{$replicant_names[0]}->is_replicating
507 => 'Replicants are replicating';
509 is $replicated->schema->storage->replicants->{$replicant_names[0]}->lag_behind_master, 0
510 => 'Replicant is zero seconds behind master';
512 ## Test the validate replicants
514 $replicated->schema->storage->pool->validate_replicants;
516 is $replicated->schema->storage->pool->active_replicants, 2
517 => 'Still have 2 replicants after validation';
519 ## Force the replicants to fail the validate test by required their lag to
520 ## be negative (ie ahead of the master!)
522 $replicated->schema->storage->pool->maximum_lag(-10);
523 $replicated->schema->storage->pool->validate_replicants;
525 is $replicated->schema->storage->pool->active_replicants, 0
526 => 'No way a replicant be be ahead of the master';
528 ## Let's be fair to the replicants again. Let them lag up to 5
530 $replicated->schema->storage->pool->maximum_lag(5);
531 $replicated->schema->storage->pool->validate_replicants;
533 is $replicated->schema->storage->pool->active_replicants, 2
534 => 'Both replicants in good standing again';
536 ## Check auto validate
538 is $replicated->schema->storage->balancer->auto_validate_every, 100
539 => "Got the expected value for auto validate";
541 ## This will make sure we auto validatge everytime
542 $replicated->schema->storage->balancer->auto_validate_every(0);
544 ## set all the replicants to inactive, and make sure the balancer falls back to
547 $replicated->schema->storage->replicants->{$replicant_names[0]}->active(0);
548 $replicated->schema->storage->replicants->{$replicant_names[1]}->active(0);
550 ## Ok, now when we go to run a query, autovalidate SHOULD reconnect
552 is $replicated->schema->storage->pool->active_replicants => 0
553 => "both replicants turned off";
555 ok $replicated->schema->resultset('Artist')->find(5)
556 => 'replicant reactivated';
558 is $replicated->schema->storage->pool->active_replicants => 2
559 => "both replicants reactivated";
562 ## Test the reliably callback
564 ok my $reliably = sub {
566 ok $replicated->schema->resultset('Artist')->find(5)
567 => 'replicant reactivated';
569 } => 'created coderef properly';
571 $replicated->schema->storage->execute_reliably($reliably);
573 ## Try something with an error
575 ok my $unreliably = sub {
577 ok $replicated->schema->resultset('ArtistXX')->find(5)
578 => 'replicant reactivated';
580 } => 'created coderef properly';
582 throws_ok {$replicated->schema->storage->execute_reliably($unreliably)}
583 qr/Can't find source for ArtistXX/
584 => 'Bad coderef throws proper error';
586 ## Make sure replication came back
588 ok $replicated->schema->resultset('Artist')->find(3)
589 => 'replicant reactivated';
591 ## make sure transactions are set to execute_reliably
593 ok my $transaction = sub {
599 ->populate('Artist', [
600 [ qw/artistid name/ ],
601 [ $id, "Children of the Grave"],
604 ok my $result = $replicated->schema->resultset('Artist')->find($id)
605 => 'Found expected artist';
607 ok my $more = $replicated->schema->resultset('Artist')->find(1)
608 => 'Found expected artist again';
610 return ($result, $more);
612 } => 'Created a coderef properly';
614 ## Test the transaction with multi return
616 ok my @return = $replicated->schema->txn_do($transaction, 666)
617 => 'did transaction';
619 is $return[0]->id, 666
620 => 'first returned value is correct';
623 => 'second returned value is correct';
626 ## Test that asking for single return works
628 ok my $return = $replicated->schema->txn_do($transaction, 777)
629 => 'did transaction';
632 => 'first returned value is correct';
635 ## Test transaction returning a single value
638 ok my $result = $replicated->schema->txn_do(sub {
639 ok my $more = $replicated->schema->resultset('Artist')->find(1)
640 => 'found inside a transaction';
642 }) => 'successfully processed transaction';
645 => 'Got expected single result from transaction';
648 ## Make sure replication came back
650 ok $replicated->schema->resultset('Artist')->find(1)
651 => 'replicant reactivated';
653 ## Test Discard changes
656 ok my $artist = $replicated->schema->resultset('Artist')->find(2)
657 => 'got an artist to test discard changes';
659 ok $artist->discard_changes
660 => 'properly discard changes';
663 ## Test some edge cases, like trying to do a transaction inside a transaction, etc
666 ok my $result = $replicated->schema->txn_do(sub {
667 return $replicated->schema->txn_do(sub {
668 ok my $more = $replicated->schema->resultset('Artist')->find(1)
669 => 'found inside a transaction inside a transaction';
672 }) => 'successfully processed transaction';
675 => 'Got expected single result from transaction';
679 ok my $result = $replicated->schema->txn_do(sub {
680 return $replicated->schema->storage->execute_reliably(sub {
681 return $replicated->schema->txn_do(sub {
682 return $replicated->schema->storage->execute_reliably(sub {
683 ok my $more = $replicated->schema->resultset('Artist')->find(1)
684 => 'found inside crazy deep transactions and execute_reliably';
689 }) => 'successfully processed transaction';
692 => 'Got expected single result from transaction';
695 ## Test the force_pool resultset attribute.
698 ok my $artist_rs = $replicated->schema->resultset('Artist')
699 => 'got artist resultset';
701 ## Turn on Forced Pool Storage
702 ok my $reliable_artist_rs = $artist_rs->search(undef, {force_pool=>'master'})
703 => 'Created a resultset using force_pool storage';
705 ok my $artist = $reliable_artist_rs->find(2)
706 => 'got an artist result via force_pool storage';
709 ## Delete the old database files
710 $replicated->cleanup;