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,
92 sub get_schema_by_connect_info {
93 DBICTest->init_schema(
95 storage_type=> '::DBI::Replicated',
96 balancer_type=>'::Random',
98 auto_validate_every=>100,
106 sub generate_replicant_connect_info {}
110 ## --------------------------------------------------------------------- ##
111 ## Add a connect_info option to test option merging.
112 ## --------------------------------------------------------------------- ##
114 package DBIx::Class::Storage::DBI::Replicated;
118 __PACKAGE__->meta->make_mutable;
120 around connect_info => sub {
121 my ($next, $self, $info) = @_;
122 $info->[3]{master_option} = 1;
126 __PACKAGE__->meta->make_immutable;
131 ## --------------------------------------------------------------------- ##
132 ## Subclass for when you are using SQLite for testing, this provides a fake
133 ## replication support.
134 ## --------------------------------------------------------------------- ##
136 package DBIx::Class::DBI::Replicated::TestReplication::SQLite;
140 use base 'DBIx::Class::DBI::Replicated::TestReplication';
142 __PACKAGE__->mk_accessors( qw/master_path slave_paths/ );
144 ## Set the mastep path from DBICTest
147 my $class = shift @_;
148 my $self = $class->SUPER::new(@_);
150 $self->master_path( DBICTest->_sqlite_dbfilename );
152 "t/var/DBIxClass_slave1.db",
153 "t/var/DBIxClass_slave2.db",
159 ## Return an Array of ArrayRefs where each ArrayRef is suitable to use for
160 ## $storage->connect_info to be used for connecting replicants.
162 sub generate_replicant_connect_info {
166 } @{$self->slave_paths};
168 my @connect_infos = map { [$_,'','',{AutoCommit=>1}] } @dsn;
171 my $c = $connect_infos[0];
172 $connect_infos[0] = {
182 ## Do a 'good enough' replication by copying the master dbfile over each of
183 ## the slave dbfiles. If the master is SQLite we do this, otherwise we
184 ## just do a one second pause to let the slaves catch up.
188 foreach my $slave (@{$self->slave_paths}) {
189 copy($self->master_path, $slave);
193 ## Cleanup after ourselves. Unlink all gthe slave paths.
197 foreach my $slave (@{$self->slave_paths}) {
202 ## --------------------------------------------------------------------- ##
203 ## Subclass for when you are setting the databases via custom export vars
204 ## This is for when you have a replicating database setup that you are
205 ## going to test against. You'll need to define the correct $ENV and have
206 ## two slave databases to test against, as well as a replication system
207 ## that will replicate in less than 1 second.
208 ## --------------------------------------------------------------------- ##
210 package DBIx::Class::DBI::Replicated::TestReplication::Custom;
211 use base 'DBIx::Class::DBI::Replicated::TestReplication';
213 ## Return an Array of ArrayRefs where each ArrayRef is suitable to use for
214 ## $storage->connect_info to be used for connecting replicants.
216 sub generate_replicant_connect_info {
218 [$ENV{"DBICTEST_SLAVE0_DSN"}, $ENV{"DBICTEST_SLAVE0_DBUSER"}, $ENV{"DBICTEST_SLAVE0_DBPASS"}, {AutoCommit => 1}],
219 [$ENV{"DBICTEST_SLAVE1_DSN"}, $ENV{"DBICTEST_SLAVE1_DBUSER"}, $ENV{"DBICTEST_SLAVE1_DBPASS"}, {AutoCommit => 1}],
223 ## pause a bit to let the replication catch up
230 ## ----------------------------------------------------------------------------
231 ## Create an object and run some tests
232 ## ----------------------------------------------------------------------------
234 ## Thi first bunch of tests are basic, just make sure all the bits are behaving
236 my $replicated_class = DBICTest->has_custom_dsn ?
237 'DBIx::Class::DBI::Replicated::TestReplication::Custom' :
238 'DBIx::Class::DBI::Replicated::TestReplication::SQLite';
242 for my $method (qw/by_connect_info by_storage_type/) {
243 ok $replicated = $replicated_class->new($method)
244 => "Created a replication object $method";
246 isa_ok $replicated->schema
247 => 'DBIx::Class::Schema';
249 isa_ok $replicated->schema->storage
250 => 'DBIx::Class::Storage::DBI::Replicated';
252 isa_ok $replicated->schema->storage->balancer
253 => 'DBIx::Class::Storage::DBI::Replicated::Balancer::Random'
254 => 'configured balancer_type';
257 ok $replicated->schema->storage->meta
258 => 'has a meta object';
260 isa_ok $replicated->schema->storage->master
261 => 'DBIx::Class::Storage::DBI';
263 isa_ok $replicated->schema->storage->pool
264 => 'DBIx::Class::Storage::DBI::Replicated::Pool';
266 does_ok $replicated->schema->storage->balancer
267 => 'DBIx::Class::Storage::DBI::Replicated::Balancer';
269 ok my @replicant_connects = $replicated->generate_replicant_connect_info
270 => 'got replication connect information';
272 ok my @replicated_storages = $replicated->schema->storage->connect_replicants(@replicant_connects)
273 => 'Created some storages suitable for replicants';
275 ok my @all_storages = $replicated->schema->storage->all_storages
278 is scalar @all_storages,
280 => 'correct number of ->all_storages';
282 is ((grep $_->isa('DBIx::Class::Storage::DBI'), @all_storages),
284 => '->all_storages are correct type');
286 my @all_storage_opts =
287 grep { (reftype($_)||'') eq 'HASH' }
288 map @{ $_->_connect_info }, @all_storages;
290 is ((grep $_->{master_option}, @all_storage_opts),
292 => 'connect_info was merged from master to replicants');
294 my @replicant_names = keys %{ $replicated->schema->storage->replicants };
296 ## Silence warning about not supporting the is_replicating method if using the
298 $replicated->schema->storage->debugobj->silence(1)
299 if first { m{^t/} } @replicant_names;
301 isa_ok $replicated->schema->storage->balancer->current_replicant
302 => 'DBIx::Class::Storage::DBI';
304 $replicated->schema->storage->debugobj->silence(0);
306 ok $replicated->schema->storage->pool->has_replicants
307 => 'does have replicants';
309 is $replicated->schema->storage->pool->num_replicants => 2
310 => 'has two replicants';
312 does_ok $replicated_storages[0]
313 => 'DBIx::Class::Storage::DBI::Replicated::Replicant';
315 does_ok $replicated_storages[1]
316 => 'DBIx::Class::Storage::DBI::Replicated::Replicant';
318 does_ok $replicated->schema->storage->replicants->{$replicant_names[0]}
319 => 'DBIx::Class::Storage::DBI::Replicated::Replicant';
321 does_ok $replicated->schema->storage->replicants->{$replicant_names[1]}
322 => 'DBIx::Class::Storage::DBI::Replicated::Replicant';
324 ## Add some info to the database
328 ->populate('Artist', [
329 [ qw/artistid name/ ],
330 [ 4, "Ozric Tentacles"],
333 ## Make sure all the slaves have the table definitions
335 $replicated->replicate;
336 $replicated->schema->storage->replicants->{$replicant_names[0]}->active(1);
337 $replicated->schema->storage->replicants->{$replicant_names[1]}->active(1);
339 ## Silence warning about not supporting the is_replicating method if using the
341 $replicated->schema->storage->debugobj->silence(1)
342 if first { m{^t/} } @replicant_names;
344 $replicated->schema->storage->pool->validate_replicants;
346 $replicated->schema->storage->debugobj->silence(0);
348 ## Make sure we can read the data.
350 ok my $artist1 = $replicated->schema->resultset('Artist')->find(4)
354 => 'DBICTest::Artist';
356 is $artist1->name, 'Ozric Tentacles'
357 => 'Found expected name for first result';
359 ## Add some new rows that only the master will have This is because
360 ## we overload any type of write operation so that is must hit the master
365 ->populate('Artist', [
366 [ qw/artistid name/ ],
367 [ 5, "Doom's Children"],
368 [ 6, "Dead On Arrival"],
372 ## Make sure all the slaves have the table definitions
373 $replicated->replicate;
375 ## Should find some data now
377 ok my $artist2 = $replicated->schema->resultset('Artist')->find(5)
381 => 'DBICTest::Artist';
383 is $artist2->name, "Doom's Children"
384 => 'Found expected name for first result';
386 ## What happens when we disconnect all the replicants?
388 is $replicated->schema->storage->pool->connected_replicants => 2
389 => "both replicants are connected";
391 $replicated->schema->storage->replicants->{$replicant_names[0]}->disconnect;
392 $replicated->schema->storage->replicants->{$replicant_names[1]}->disconnect;
394 is $replicated->schema->storage->pool->connected_replicants => 0
395 => "both replicants are now disconnected";
397 ## All these should pass, since the database should automatically reconnect
399 ok my $artist3 = $replicated->schema->resultset('Artist')->find(6)
400 => 'Still finding stuff.';
403 => 'DBICTest::Artist';
405 is $artist3->name, "Dead On Arrival"
406 => 'Found expected name for first result';
408 is $replicated->schema->storage->pool->connected_replicants => 1
409 => "At Least One replicant reconnected to handle the job";
411 ## What happens when we try to select something that doesn't exist?
413 ok ! $replicated->schema->resultset('Artist')->find(666)
414 => 'Correctly failed to find something.';
416 ## test the reliable option
420 $replicated->schema->storage->set_reliable_storage;
422 ok $replicated->schema->resultset('Artist')->find(2)
423 => 'Read from master 1';
425 ok $replicated->schema->resultset('Artist')->find(5)
426 => 'Read from master 2';
428 $replicated->schema->storage->set_balanced_storage;
430 ok $replicated->schema->resultset('Artist')->find(3)
431 => 'Read from replicant';
434 ## Make sure when reliable goes out of scope, we are using replicants again
436 ok $replicated->schema->resultset('Artist')->find(1)
437 => 'back to replicant 1.';
439 ok $replicated->schema->resultset('Artist')->find(2)
440 => 'back to replicant 2.';
442 ## set all the replicants to inactive, and make sure the balancer falls back to
445 $replicated->schema->storage->replicants->{$replicant_names[0]}->active(0);
446 $replicated->schema->storage->replicants->{$replicant_names[1]}->active(0);
448 ## Silence warning about falling back to master.
449 $replicated->schema->storage->debugobj->silence(1);
451 ok $replicated->schema->resultset('Artist')->find(2)
452 => 'Fallback to master';
454 $replicated->schema->storage->debugobj->silence(0);
456 $replicated->schema->storage->replicants->{$replicant_names[0]}->active(1);
457 $replicated->schema->storage->replicants->{$replicant_names[1]}->active(1);
459 ## Silence warning about not supporting the is_replicating method if using the
461 $replicated->schema->storage->debugobj->silence(1)
462 if first { m{^t/} } @replicant_names;
464 $replicated->schema->storage->pool->validate_replicants;
466 $replicated->schema->storage->debugobj->silence(0);
468 ok $replicated->schema->resultset('Artist')->find(2)
469 => 'Returned to replicates';
471 ## Getting slave status tests
474 ## We skip this tests unless you have a custom replicants, since the default
475 ## sqlite based replication tests don't support these functions.
477 skip 'Cannot Test Replicant Status on Non Replicating Database', 9
478 unless DBICTest->has_custom_dsn && $ENV{"DBICTEST_SLAVE0_DSN"};
480 $replicated->replicate; ## Give the slaves a chance to catchup.
482 ok $replicated->schema->storage->replicants->{$replicant_names[0]}->is_replicating
483 => 'Replicants are replicating';
485 is $replicated->schema->storage->replicants->{$replicant_names[0]}->lag_behind_master, 0
486 => 'Replicant is zero seconds behind master';
488 ## Test the validate replicants
490 $replicated->schema->storage->pool->validate_replicants;
492 is $replicated->schema->storage->pool->active_replicants, 2
493 => 'Still have 2 replicants after validation';
495 ## Force the replicants to fail the validate test by required their lag to
496 ## be negative (ie ahead of the master!)
498 $replicated->schema->storage->pool->maximum_lag(-10);
499 $replicated->schema->storage->pool->validate_replicants;
501 is $replicated->schema->storage->pool->active_replicants, 0
502 => 'No way a replicant be be ahead of the master';
504 ## Let's be fair to the replicants again. Let them lag up to 5
506 $replicated->schema->storage->pool->maximum_lag(5);
507 $replicated->schema->storage->pool->validate_replicants;
509 is $replicated->schema->storage->pool->active_replicants, 2
510 => 'Both replicants in good standing again';
512 ## Check auto validate
514 is $replicated->schema->storage->balancer->auto_validate_every, 100
515 => "Got the expected value for auto validate";
517 ## This will make sure we auto validatge everytime
518 $replicated->schema->storage->balancer->auto_validate_every(0);
520 ## set all the replicants to inactive, and make sure the balancer falls back to
523 $replicated->schema->storage->replicants->{$replicant_names[0]}->active(0);
524 $replicated->schema->storage->replicants->{$replicant_names[1]}->active(0);
526 ## Ok, now when we go to run a query, autovalidate SHOULD reconnect
528 is $replicated->schema->storage->pool->active_replicants => 0
529 => "both replicants turned off";
531 ok $replicated->schema->resultset('Artist')->find(5)
532 => 'replicant reactivated';
534 is $replicated->schema->storage->pool->active_replicants => 2
535 => "both replicants reactivated";
538 ## Test the reliably callback
540 ok my $reliably = sub {
542 ok $replicated->schema->resultset('Artist')->find(5)
543 => 'replicant reactivated';
545 } => 'created coderef properly';
547 $replicated->schema->storage->execute_reliably($reliably);
549 ## Try something with an error
551 ok my $unreliably = sub {
553 ok $replicated->schema->resultset('ArtistXX')->find(5)
554 => 'replicant reactivated';
556 } => 'created coderef properly';
558 throws_ok {$replicated->schema->storage->execute_reliably($unreliably)}
559 qr/Can't find source for ArtistXX/
560 => 'Bad coderef throws proper error';
562 ## Make sure replication came back
564 ok $replicated->schema->resultset('Artist')->find(3)
565 => 'replicant reactivated';
567 ## make sure transactions are set to execute_reliably
569 ok my $transaction = sub {
575 ->populate('Artist', [
576 [ qw/artistid name/ ],
577 [ $id, "Children of the Grave"],
580 ok my $result = $replicated->schema->resultset('Artist')->find($id)
581 => 'Found expected artist';
583 ok my $more = $replicated->schema->resultset('Artist')->find(1)
584 => 'Found expected artist again';
586 return ($result, $more);
588 } => 'Created a coderef properly';
590 ## Test the transaction with multi return
592 ok my @return = $replicated->schema->txn_do($transaction, 666)
593 => 'did transaction';
595 is $return[0]->id, 666
596 => 'first returned value is correct';
599 => 'second returned value is correct';
602 ## Test that asking for single return works
604 ok my $return = $replicated->schema->txn_do($transaction, 777)
605 => 'did transaction';
608 => 'first returned value is correct';
611 ## Test transaction returning a single value
614 ok my $result = $replicated->schema->txn_do(sub {
615 ok my $more = $replicated->schema->resultset('Artist')->find(1)
616 => 'found inside a transaction';
618 }) => 'successfully processed transaction';
621 => 'Got expected single result from transaction';
624 ## Make sure replication came back
626 ok $replicated->schema->resultset('Artist')->find(1)
627 => 'replicant reactivated';
629 ## Test Discard changes
632 ok my $artist = $replicated->schema->resultset('Artist')->find(2)
633 => 'got an artist to test discard changes';
635 ok $artist->discard_changes
636 => 'properly discard changes';
639 ## Test some edge cases, like trying to do a transaction inside a transaction, etc
642 ok my $result = $replicated->schema->txn_do(sub {
643 return $replicated->schema->txn_do(sub {
644 ok my $more = $replicated->schema->resultset('Artist')->find(1)
645 => 'found inside a transaction inside a transaction';
648 }) => 'successfully processed transaction';
651 => 'Got expected single result from transaction';
655 ok my $result = $replicated->schema->txn_do(sub {
656 return $replicated->schema->storage->execute_reliably(sub {
657 return $replicated->schema->txn_do(sub {
658 return $replicated->schema->storage->execute_reliably(sub {
659 ok my $more = $replicated->schema->resultset('Artist')->find(1)
660 => 'found inside crazy deep transactions and execute_reliably';
665 }) => 'successfully processed transaction';
668 => 'Got expected single result from transaction';
671 ## Test the force_pool resultset attribute.
674 ok my $artist_rs = $replicated->schema->resultset('Artist')
675 => 'got artist resultset';
677 ## Turn on Forced Pool Storage
678 ok my $reliable_artist_rs = $artist_rs->search(undef, {force_pool=>'master'})
679 => 'Created a resultset using force_pool storage';
681 ok my $artist = $reliable_artist_rs->find(2)
682 => 'got an artist result via force_pool storage';
685 ## Delete the old database files
686 $replicated->cleanup;