Lazy-load as many of the non-essential modules as possible
[dbsrgits/DBIx-Class.git] / t / storage / replicated.t
1 use strict;
2 use warnings;
3
4 use Test::More;
5
6 BEGIN {
7     require DBIx::Class;
8     plan skip_all => 'Test needs ' . DBIx::Class::Optional::Dependencies->req_missing_for ('test_replicated')
9       unless DBIx::Class::Optional::Dependencies->req_ok_for ('test_replicated');
10 }
11
12 use lib qw(t/lib);
13 use DBICTest;
14
15 if (DBICTest::RunMode->is_smoker) {
16   my $mver = Moose->VERSION;
17   plan skip_all => "A trial version $mver of Moose detected known to break replication - skipping test known to fail"
18     if ($mver >= 1.99 and $mver <= 1.9902);
19 }
20
21 use Test::Moose;
22 use Test::Exception;
23 use List::Util 'first';
24 use Scalar::Util 'reftype';
25 use File::Spec;
26 use IO::Handle;
27 use Moose();
28 use MooseX::Types();
29 note "Using Moose version $Moose::VERSION and MooseX::Types version $MooseX::Types::VERSION";
30
31 my $var_dir = quotemeta ( File::Spec->catdir(qw/t var/) );
32
33 use_ok 'DBIx::Class::Storage::DBI::Replicated::Pool';
34 use_ok 'DBIx::Class::Storage::DBI::Replicated::Balancer';
35 use_ok 'DBIx::Class::Storage::DBI::Replicated::Replicant';
36 use_ok 'DBIx::Class::Storage::DBI::Replicated';
37
38
39 =head1 HOW TO USE
40
41     This is a test of the replicated storage system.  This will work in one of
42     two ways, either it was try to fake replication with a couple of SQLite DBs
43     and creative use of copy, or if you define a couple of %ENV vars correctly
44     will try to test those.  If you do that, it will assume the setup is properly
45     replicating.  Your results may vary, but I have demonstrated this to work with
46     mysql native replication.
47
48 =cut
49
50
51 ## ----------------------------------------------------------------------------
52 ## Build a class to hold all our required testing data and methods.
53 ## ----------------------------------------------------------------------------
54
55 TESTSCHEMACLASSES: {
56
57     ## --------------------------------------------------------------------- ##
58     ## Create an object to contain your replicated stuff.
59     ## --------------------------------------------------------------------- ##
60
61     package DBIx::Class::DBI::Replicated::TestReplication;
62
63     use DBICTest;
64     use base qw/Class::Accessor::Fast/;
65
66     __PACKAGE__->mk_accessors( qw/schema/ );
67
68     ## Initialize the object
69
70     sub new {
71         my ($class, $schema_method) = (shift, shift);
72         my $self = $class->SUPER::new(@_);
73
74         $self->schema( $self->init_schema($schema_method) );
75         return $self;
76     }
77
78     ## Get the Schema and set the replication storage type
79
80     sub init_schema {
81         # current SQLT SQLite producer does not handle DROP TABLE IF EXISTS, trap warnings here
82         local $SIG{__WARN__} = sub { warn @_ unless $_[0] =~ /no such table.+DROP TABLE/s };
83
84         my ($class, $schema_method) = @_;
85
86         my $method = "get_schema_$schema_method";
87         my $schema = $class->$method;
88
89         return $schema;
90     }
91
92     sub get_schema_by_storage_type {
93       DBICTest->init_schema(
94         sqlite_use_file => 1,
95         storage_type=>{
96           '::DBI::Replicated' => {
97             balancer_type=>'::Random',
98             balancer_args=>{
99               auto_validate_every=>100,
100               master_read_weight => 1
101             },
102           }
103         },
104         deploy_args=>{
105           add_drop_table => 1,
106         },
107       );
108     }
109
110     sub get_schema_by_connect_info {
111       DBICTest->init_schema(
112         sqlite_use_file => 1,
113         storage_type=> '::DBI::Replicated',
114         balancer_type=>'::Random',
115         balancer_args=> {
116             auto_validate_every=>100,
117             master_read_weight => 1
118         },
119         pool_args=>{
120             maximum_lag=>1,
121         },
122         deploy_args=>{
123           add_drop_table => 1,
124         },
125       );
126     }
127
128     sub generate_replicant_connect_info {}
129     sub replicate {}
130     sub cleanup {}
131
132     ## --------------------------------------------------------------------- ##
133     ## Add a connect_info option to test option merging.
134     ## --------------------------------------------------------------------- ##
135     {
136     package DBIx::Class::Storage::DBI::Replicated;
137
138     use Moose;
139
140     __PACKAGE__->meta->make_mutable;
141
142     around connect_info => sub {
143       my ($next, $self, $info) = @_;
144       $info->[3]{master_option} = 1;
145       $self->$next($info);
146     };
147
148     __PACKAGE__->meta->make_immutable;
149
150     no Moose;
151     }
152
153     ## --------------------------------------------------------------------- ##
154     ## Subclass for when you are using SQLite for testing, this provides a fake
155     ## replication support.
156     ## --------------------------------------------------------------------- ##
157
158     package DBIx::Class::DBI::Replicated::TestReplication::SQLite;
159
160     use DBICTest;
161     use File::Copy;
162     use base 'DBIx::Class::DBI::Replicated::TestReplication';
163
164     __PACKAGE__->mk_accessors(qw/master_path slave_paths/);
165
166     ## Set the master path from DBICTest
167
168     sub new {
169         my $class = shift @_;
170         my $self = $class->SUPER::new(@_);
171
172         $self->master_path( DBICTest->_sqlite_dbfilename );
173         $self->slave_paths([
174             File::Spec->catfile(qw/t var DBIxClass_slave1.db/),
175             File::Spec->catfile(qw/t var DBIxClass_slave2.db/),
176         ]);
177
178         return $self;
179     }
180
181     ## Return an Array of ArrayRefs where each ArrayRef is suitable to use for
182     ## $storage->connect_info to be used for connecting replicants.
183
184     sub generate_replicant_connect_info {
185         my $self = shift @_;
186         my @dsn = map {
187             "dbi:SQLite:${_}";
188         } @{$self->slave_paths};
189
190         my @connect_infos = map { [$_,'','',{AutoCommit=>1}] } @dsn;
191
192         ## Make sure nothing is left over from a failed test
193         $self->cleanup;
194
195         ## try a hashref too
196         my $c = $connect_infos[0];
197         $connect_infos[0] = {
198           dsn => $c->[0],
199           user => $c->[1],
200           password => $c->[2],
201           %{ $c->[3] }
202         };
203
204         @connect_infos
205     }
206
207     ## Do a 'good enough' replication by copying the master dbfile over each of
208     ## the slave dbfiles.  If the master is SQLite we do this, otherwise we
209     ## just do a one second pause to let the slaves catch up.
210
211     sub replicate {
212         my $self = shift @_;
213         foreach my $slave (@{$self->slave_paths}) {
214             copy($self->master_path, $slave);
215         }
216     }
217
218     ## Cleanup after ourselves.  Unlink all gthe slave paths.
219
220     sub cleanup {
221         my $self = shift @_;
222         foreach my $slave (@{$self->slave_paths}) {
223             if(-e $slave) {
224                 unlink $slave;
225             }
226         }
227     }
228
229     ## --------------------------------------------------------------------- ##
230     ## Subclass for when you are setting the databases via custom export vars
231     ## This is for when you have a replicating database setup that you are
232     ## going to test against.  You'll need to define the correct $ENV and have
233     ## two slave databases to test against, as well as a replication system
234     ## that will replicate in less than 1 second.
235     ## --------------------------------------------------------------------- ##
236
237     package DBIx::Class::DBI::Replicated::TestReplication::Custom;
238     use base 'DBIx::Class::DBI::Replicated::TestReplication';
239
240     ## Return an Array of ArrayRefs where each ArrayRef is suitable to use for
241     ## $storage->connect_info to be used for connecting replicants.
242
243     sub generate_replicant_connect_info {
244         return (
245             [$ENV{"DBICTEST_SLAVE0_DSN"}, $ENV{"DBICTEST_SLAVE0_DBUSER"}, $ENV{"DBICTEST_SLAVE0_DBPASS"}, {AutoCommit => 1}],
246             [$ENV{"DBICTEST_SLAVE1_DSN"}, $ENV{"DBICTEST_SLAVE1_DBUSER"}, $ENV{"DBICTEST_SLAVE1_DBPASS"}, {AutoCommit => 1}],
247         );
248     }
249
250     ## pause a bit to let the replication catch up
251
252     sub replicate {
253         sleep 1;
254     }
255 }
256
257 ## ----------------------------------------------------------------------------
258 ## Create an object and run some tests
259 ## ----------------------------------------------------------------------------
260
261 ## Thi first bunch of tests are basic, just make sure all the bits are behaving
262
263 my $replicated_class = DBICTest->has_custom_dsn ?
264     'DBIx::Class::DBI::Replicated::TestReplication::Custom' :
265     'DBIx::Class::DBI::Replicated::TestReplication::SQLite';
266
267 my $replicated;
268
269 for my $method (qw/by_connect_info by_storage_type/) {
270   undef $replicated;
271   ok $replicated = $replicated_class->new($method)
272       => "Created a replication object $method";
273
274   isa_ok $replicated->schema
275       => 'DBIx::Class::Schema';
276
277   isa_ok $replicated->schema->storage
278       => 'DBIx::Class::Storage::DBI::Replicated';
279
280   isa_ok $replicated->schema->storage->balancer
281       => 'DBIx::Class::Storage::DBI::Replicated::Balancer::Random'
282       => 'configured balancer_type';
283 }
284
285 ### check that all Storage::DBI methods are handled by ::Replicated
286 {
287   my @storage_dbi_methods = Class::MOP::Class
288     ->initialize('DBIx::Class::Storage::DBI')->get_all_method_names;
289
290   my @replicated_methods  = DBIx::Class::Storage::DBI::Replicated->meta
291     ->get_all_method_names;
292
293 # remove constants and OTHER_CRAP
294   @storage_dbi_methods = grep !/^[A-Z_]+\z/, @storage_dbi_methods;
295
296 # remove CAG accessors
297   @storage_dbi_methods = grep !/_accessor\z/, @storage_dbi_methods;
298
299 # remove DBIx::Class (the root parent, with CAG and stuff) methods
300   my @root_methods = Class::MOP::Class->initialize('DBIx::Class')
301     ->get_all_method_names;
302   my %count;
303   $count{$_}++ for (@storage_dbi_methods, @root_methods);
304
305   @storage_dbi_methods = grep $count{$_} != 2, @storage_dbi_methods;
306
307 # make hashes
308   my %storage_dbi_methods;
309   @storage_dbi_methods{@storage_dbi_methods} = ();
310   my %replicated_methods;
311   @replicated_methods{@replicated_methods} = ();
312
313 # remove ::Replicated-specific methods
314   for my $method (@replicated_methods) {
315     delete $replicated_methods{$method}
316       unless exists $storage_dbi_methods{$method};
317   }
318   @replicated_methods = keys %replicated_methods;
319
320 # check that what's left is implemented
321   %count = ();
322   $count{$_}++ for (@storage_dbi_methods, @replicated_methods);
323
324   if ((grep $count{$_} == 2, @storage_dbi_methods) == @storage_dbi_methods) {
325     pass 'all DBIx::Class::Storage::DBI methods implemented';
326   }
327   else {
328     my @unimplemented = grep $count{$_} == 1, @storage_dbi_methods;
329
330     fail 'the following DBIx::Class::Storage::DBI methods are unimplemented: '
331       . "@unimplemented";
332   }
333 }
334
335 ok $replicated->schema->storage->meta
336     => 'has a meta object';
337
338 isa_ok $replicated->schema->storage->master
339     => 'DBIx::Class::Storage::DBI';
340
341 isa_ok $replicated->schema->storage->pool
342     => 'DBIx::Class::Storage::DBI::Replicated::Pool';
343
344 does_ok $replicated->schema->storage->balancer
345     => 'DBIx::Class::Storage::DBI::Replicated::Balancer';
346
347 ok my @replicant_connects = $replicated->generate_replicant_connect_info
348     => 'got replication connect information';
349
350 ok my @replicated_storages = $replicated->schema->storage->connect_replicants(@replicant_connects)
351     => 'Created some storages suitable for replicants';
352
353 our %debug;
354 $replicated->schema->storage->debug(1);
355 $replicated->schema->storage->debugcb(sub {
356     my ($op, $info) = @_;
357     ##warn "\n$op, $info\n";
358     %debug = (
359         op => $op,
360         info => $info,
361         dsn => ($info=~m/\[(.+)\]/)[0],
362         storage_type => $info=~m/REPLICANT/ ? 'REPLICANT' : 'MASTER',
363     );
364 });
365
366 ok my @all_storages = $replicated->schema->storage->all_storages
367     => '->all_storages';
368
369 is scalar @all_storages,
370     3
371     => 'correct number of ->all_storages';
372
373 is ((grep $_->isa('DBIx::Class::Storage::DBI'), @all_storages),
374     3
375     => '->all_storages are correct type');
376
377 my @all_storage_opts =
378   grep { (reftype($_)||'') eq 'HASH' }
379     map @{ $_->_connect_info }, @all_storages;
380
381 is ((grep $_->{master_option}, @all_storage_opts),
382     3
383     => 'connect_info was merged from master to replicants');
384
385 my @replicant_names = keys %{ $replicated->schema->storage->replicants };
386
387 ok @replicant_names, "found replicant names @replicant_names";
388
389 ## Silence warning about not supporting the is_replicating method if using the
390 ## sqlite dbs.
391 $replicated->schema->storage->debugobj->silence(1)
392   if first { $_ =~ /$var_dir/ } @replicant_names;
393
394 isa_ok $replicated->schema->storage->balancer->current_replicant
395     => 'DBIx::Class::Storage::DBI';
396
397 $replicated->schema->storage->debugobj->silence(0);
398
399 ok $replicated->schema->storage->pool->has_replicants
400     => 'does have replicants';
401
402 is $replicated->schema->storage->pool->num_replicants => 2
403     => 'has two replicants';
404
405 does_ok $replicated_storages[0]
406     => 'DBIx::Class::Storage::DBI::Replicated::Replicant';
407
408 does_ok $replicated_storages[1]
409     => 'DBIx::Class::Storage::DBI::Replicated::Replicant';
410
411 does_ok $replicated->schema->storage->replicants->{$replicant_names[0]}
412     => 'DBIx::Class::Storage::DBI::Replicated::Replicant';
413
414 does_ok $replicated->schema->storage->replicants->{$replicant_names[1]}
415     => 'DBIx::Class::Storage::DBI::Replicated::Replicant';
416
417 ## Add some info to the database
418
419 $replicated
420     ->schema
421     ->populate('Artist', [
422         [ qw/artistid name/ ],
423         [ 4, "Ozric Tentacles"],
424     ]);
425
426     is $debug{storage_type}, 'MASTER',
427         "got last query from a master: $debug{dsn}";
428
429     like $debug{info}, qr/INSERT/, 'Last was an insert';
430
431 ## Make sure all the slaves have the table definitions
432
433 $replicated->replicate;
434 $replicated->schema->storage->replicants->{$replicant_names[0]}->active(1);
435 $replicated->schema->storage->replicants->{$replicant_names[1]}->active(1);
436
437 ## Silence warning about not supporting the is_replicating method if using the
438 ## sqlite dbs.
439 $replicated->schema->storage->debugobj->silence(1)
440   if first { $_ =~ /$var_dir/ } @replicant_names;
441
442 $replicated->schema->storage->pool->validate_replicants;
443
444 $replicated->schema->storage->debugobj->silence(0);
445
446 ## Make sure we can read the data.
447
448 ok my $artist1 = $replicated->schema->resultset('Artist')->find(4)
449     => 'Created Result';
450
451 ## We removed testing here since master read weight is on, so we can't tell in
452 ## advance what storage to expect.  We turn master read weight off a bit lower
453 ## is $debug{storage_type}, 'REPLICANT'
454 ##     => "got last query from a replicant: $debug{dsn}, $debug{info}";
455
456 isa_ok $artist1
457     => 'DBICTest::Artist';
458
459 is $artist1->name, 'Ozric Tentacles'
460     => 'Found expected name for first result';
461
462 ## Check that master_read_weight is honored
463 {
464     no warnings qw/once redefine/;
465
466     local
467     *DBIx::Class::Storage::DBI::Replicated::Balancer::Random::_random_number =
468     sub { 999 };
469
470     $replicated->schema->storage->balancer->increment_storage;
471
472     is $replicated->schema->storage->balancer->current_replicant,
473        $replicated->schema->storage->master
474        => 'master_read_weight is honored';
475
476     ## turn it off for the duration of the test
477     $replicated->schema->storage->balancer->master_read_weight(0);
478     $replicated->schema->storage->balancer->increment_storage;
479 }
480
481 ## Add some new rows that only the master will have  This is because
482 ## we overload any type of write operation so that is must hit the master
483 ## database.
484
485 $replicated
486     ->schema
487     ->populate('Artist', [
488         [ qw/artistid name/ ],
489         [ 5, "Doom's Children"],
490         [ 6, "Dead On Arrival"],
491         [ 7, "Watergate"],
492     ]);
493
494     is $debug{storage_type}, 'MASTER',
495         "got last query from a master: $debug{dsn}";
496
497     like $debug{info}, qr/INSERT/, 'Last was an insert';
498
499 ## Make sure all the slaves have the table definitions
500 $replicated->replicate;
501
502 ## Should find some data now
503
504 ok my $artist2 = $replicated->schema->resultset('Artist')->find(5)
505     => 'Sync succeed';
506
507 is $debug{storage_type}, 'REPLICANT'
508     => "got last query from a replicant: $debug{dsn}";
509
510 isa_ok $artist2
511     => 'DBICTest::Artist';
512
513 is $artist2->name, "Doom's Children"
514     => 'Found expected name for first result';
515
516 ## What happens when we disconnect all the replicants?
517
518 is $replicated->schema->storage->pool->connected_replicants => 2
519     => "both replicants are connected";
520
521 $replicated->schema->storage->replicants->{$replicant_names[0]}->disconnect;
522 $replicated->schema->storage->replicants->{$replicant_names[1]}->disconnect;
523
524 is $replicated->schema->storage->pool->connected_replicants => 0
525     => "both replicants are now disconnected";
526
527 ## All these should pass, since the database should automatically reconnect
528
529 ok my $artist3 = $replicated->schema->resultset('Artist')->find(6)
530     => 'Still finding stuff.';
531
532 is $debug{storage_type}, 'REPLICANT'
533     => "got last query from a replicant: $debug{dsn}";
534
535 isa_ok $artist3
536     => 'DBICTest::Artist';
537
538 is $artist3->name, "Dead On Arrival"
539     => 'Found expected name for first result';
540
541 is $replicated->schema->storage->pool->connected_replicants => 1
542     => "At Least One replicant reconnected to handle the job";
543
544 ## What happens when we try to select something that doesn't exist?
545
546 ok ! $replicated->schema->resultset('Artist')->find(666)
547     => 'Correctly failed to find something.';
548
549 is $debug{storage_type}, 'REPLICANT'
550     => "got last query from a replicant: $debug{dsn}";
551
552 ## test the reliable option
553
554 TESTRELIABLE: {
555
556     $replicated->schema->storage->set_reliable_storage;
557
558     ok $replicated->schema->resultset('Artist')->find(2)
559         => 'Read from master 1';
560
561     is $debug{storage_type}, 'MASTER',
562         "got last query from a master: $debug{dsn}";
563
564     ok $replicated->schema->resultset('Artist')->find(5)
565         => 'Read from master 2';
566
567     is $debug{storage_type}, 'MASTER',
568         "got last query from a master: $debug{dsn}";
569
570     $replicated->schema->storage->set_balanced_storage;
571
572     ok $replicated->schema->resultset('Artist')->find(3)
573         => 'Read from replicant';
574
575     is $debug{storage_type}, 'REPLICANT',
576         "got last query from a replicant: $debug{dsn}";
577 }
578
579 ## Make sure when reliable goes out of scope, we are using replicants again
580
581 ok $replicated->schema->resultset('Artist')->find(1)
582     => 'back to replicant 1.';
583
584     is $debug{storage_type}, 'REPLICANT',
585         "got last query from a replicant: $debug{dsn}";
586
587 ok $replicated->schema->resultset('Artist')->find(2)
588     => 'back to replicant 2.';
589
590     is $debug{storage_type}, 'REPLICANT',
591         "got last query from a replicant: $debug{dsn}";
592
593 ## set all the replicants to inactive, and make sure the balancer falls back to
594 ## the master.
595
596 $replicated->schema->storage->replicants->{$replicant_names[0]}->active(0);
597 $replicated->schema->storage->replicants->{$replicant_names[1]}->active(0);
598
599 {
600     ## catch the fallback to master warning
601     open my $debugfh, '>', \my $fallback_warning;
602     my $oldfh = $replicated->schema->storage->debugfh;
603     $replicated->schema->storage->debugfh($debugfh);
604
605     ok $replicated->schema->resultset('Artist')->find(2)
606         => 'Fallback to master';
607
608     is $debug{storage_type}, 'MASTER',
609         "got last query from a master: $debug{dsn}";
610
611     like $fallback_warning, qr/falling back to master/
612         => 'emits falling back to master debug';
613
614     $replicated->schema->storage->debugfh($oldfh);
615 }
616
617 $replicated->schema->storage->replicants->{$replicant_names[0]}->active(1);
618 $replicated->schema->storage->replicants->{$replicant_names[1]}->active(1);
619
620 ## Silence warning about not supporting the is_replicating method if using the
621 ## sqlite dbs.
622 $replicated->schema->storage->debugobj->silence(1)
623   if first { $_ =~ /$var_dir/ } @replicant_names;
624
625 $replicated->schema->storage->pool->validate_replicants;
626
627 $replicated->schema->storage->debugobj->silence(0);
628
629 {
630     ## catch the fallback to master warning
631     open my $debugfh, '>', \my $return_warning;
632     my $oldfh = $replicated->schema->storage->debugfh;
633     $replicated->schema->storage->debugfh($debugfh);
634
635     ok $replicated->schema->resultset('Artist')->find(2)
636         => 'Return to replicants';
637
638     is $debug{storage_type}, 'REPLICANT',
639       "got last query from a replicant: $debug{dsn}";
640
641     like $return_warning, qr/Moved back to slave/
642         => 'emits returning to slave debug';
643
644     $replicated->schema->storage->debugfh($oldfh);
645 }
646
647 ## Getting slave status tests
648
649 SKIP: {
650     ## We skip this tests unless you have a custom replicants, since the default
651     ## sqlite based replication tests don't support these functions.
652
653     skip 'Cannot Test Replicant Status on Non Replicating Database', 10
654      unless DBICTest->has_custom_dsn && $ENV{"DBICTEST_SLAVE0_DSN"};
655
656     $replicated->replicate; ## Give the slaves a chance to catchup.
657
658     ok $replicated->schema->storage->replicants->{$replicant_names[0]}->is_replicating
659         => 'Replicants are replicating';
660
661     is $replicated->schema->storage->replicants->{$replicant_names[0]}->lag_behind_master, 0
662         => 'Replicant is zero seconds behind master';
663
664     ## Test the validate replicants
665
666     $replicated->schema->storage->pool->validate_replicants;
667
668     is $replicated->schema->storage->pool->active_replicants, 2
669         => 'Still have 2 replicants after validation';
670
671     ## Force the replicants to fail the validate test by required their lag to
672     ## be negative (ie ahead of the master!)
673
674     $replicated->schema->storage->pool->maximum_lag(-10);
675     $replicated->schema->storage->pool->validate_replicants;
676
677     is $replicated->schema->storage->pool->active_replicants, 0
678         => 'No way a replicant be be ahead of the master';
679
680     ## Let's be fair to the replicants again.  Let them lag up to 5
681
682     $replicated->schema->storage->pool->maximum_lag(5);
683     $replicated->schema->storage->pool->validate_replicants;
684
685     is $replicated->schema->storage->pool->active_replicants, 2
686         => 'Both replicants in good standing again';
687
688     ## Check auto validate
689
690     is $replicated->schema->storage->balancer->auto_validate_every, 100
691         => "Got the expected value for auto validate";
692
693         ## This will make sure we auto validatge everytime
694         $replicated->schema->storage->balancer->auto_validate_every(0);
695
696         ## set all the replicants to inactive, and make sure the balancer falls back to
697         ## the master.
698
699         $replicated->schema->storage->replicants->{$replicant_names[0]}->active(0);
700         $replicated->schema->storage->replicants->{$replicant_names[1]}->active(0);
701
702         ## Ok, now when we go to run a query, autovalidate SHOULD reconnect
703
704     is $replicated->schema->storage->pool->active_replicants => 0
705         => "both replicants turned off";
706
707     ok $replicated->schema->resultset('Artist')->find(5)
708         => 'replicant reactivated';
709
710     is $debug{storage_type}, 'REPLICANT',
711         "got last query from a replicant: $debug{dsn}";
712
713     is $replicated->schema->storage->pool->active_replicants => 2
714         => "both replicants reactivated";
715 }
716
717 ## Test the reliably callback
718
719 ok my $reliably = sub {
720
721     ok $replicated->schema->resultset('Artist')->find(5)
722         => 'replicant reactivated';
723
724     is $debug{storage_type}, 'MASTER',
725         "got last query from a master: $debug{dsn}";
726
727 } => 'created coderef properly';
728
729 $replicated->schema->storage->execute_reliably($reliably);
730
731 ## Try something with an error
732
733 ok my $unreliably = sub {
734
735     ok $replicated->schema->resultset('ArtistXX')->find(5)
736         => 'replicant reactivated';
737
738 } => 'created coderef properly';
739
740 throws_ok {$replicated->schema->storage->execute_reliably($unreliably)}
741     qr/Can't find source for ArtistXX/
742     => 'Bad coderef throws proper error';
743
744 ## Make sure replication came back
745
746 ok $replicated->schema->resultset('Artist')->find(3)
747     => 'replicant reactivated';
748
749 is $debug{storage_type}, 'REPLICANT', "got last query from a replicant: $debug{dsn}";
750
751 ## make sure transactions are set to execute_reliably
752
753 ok my $transaction = sub {
754
755     my $id = shift @_;
756
757     $replicated
758         ->schema
759         ->populate('Artist', [
760             [ qw/artistid name/ ],
761             [ $id, "Children of the Grave $id"],
762         ]);
763
764     ok my $result = $replicated->schema->resultset('Artist')->find($id)
765         => "Found expected artist for $id";
766
767     is $debug{storage_type}, 'MASTER',
768         "got last query from a master: $debug{dsn}";
769
770     ok my $more = $replicated->schema->resultset('Artist')->find(1)
771         => 'Found expected artist again for 1';
772
773     is $debug{storage_type}, 'MASTER',
774         "got last query from a master: $debug{dsn}";
775
776    return ($result, $more);
777
778 } => 'Created a coderef properly';
779
780 ## Test the transaction with multi return
781 {
782     ok my @return = $replicated->schema->txn_do($transaction, 666)
783         => 'did transaction';
784
785         is $return[0]->id, 666
786             => 'first returned value is correct';
787
788         is $debug{storage_type}, 'MASTER',
789             "got last query from a master: $debug{dsn}";
790
791         is $return[1]->id, 1
792             => 'second returned value is correct';
793
794         is $debug{storage_type}, 'MASTER',
795              "got last query from a master: $debug{dsn}";
796
797 }
798
799 ## Test that asking for single return works
800 {
801     ok my @return = $replicated->schema->txn_do($transaction, 777)
802         => 'did transaction';
803
804         is $return[0]->id, 777
805             => 'first returned value is correct';
806
807         is $return[1]->id, 1
808             => 'second returned value is correct';
809 }
810
811 ## Test transaction returning a single value
812
813 {
814     ok my $result = $replicated->schema->txn_do(sub {
815         ok my $more = $replicated->schema->resultset('Artist')->find(1)
816         => 'found inside a transaction';
817         is $debug{storage_type}, 'MASTER', "got last query from a master: $debug{dsn}";
818         return $more;
819     }) => 'successfully processed transaction';
820
821     is $result->id, 1
822        => 'Got expected single result from transaction';
823 }
824
825 ## Make sure replication came back
826
827 ok $replicated->schema->resultset('Artist')->find(1)
828     => 'replicant reactivated';
829
830 is $debug{storage_type}, 'REPLICANT', "got last query from a replicant: $debug{dsn}";
831
832 ## Test Discard changes
833
834 {
835     ok my $artist = $replicated->schema->resultset('Artist')->find(2)
836         => 'got an artist to test discard changes';
837
838     is $debug{storage_type}, 'REPLICANT', "got last query from a replicant: $debug{dsn}";
839
840     ok $artist->get_from_storage({force_pool=>'master'})
841        => 'properly discard changes';
842
843     is $debug{storage_type}, 'MASTER', "got last query from a master: $debug{dsn}";
844
845     ok $artist->discard_changes({force_pool=>'master'})
846        => 'properly called discard_changes against master (manual attrs)';
847
848     is $debug{storage_type}, 'MASTER', "got last query from a master: $debug{dsn}";
849
850     ok $artist->discard_changes()
851        => 'properly called discard_changes against master (default attrs)';
852
853     is $debug{storage_type}, 'MASTER', "got last query from a master: $debug{dsn}";
854
855     ok $artist->discard_changes({force_pool=>$replicant_names[0]})
856        => 'properly able to override the default attributes';
857
858     is $debug{storage_type}, 'REPLICANT', "got last query from a replicant: $debug{dsn}"
859 }
860
861 ## Test some edge cases, like trying to do a transaction inside a transaction, etc
862
863 {
864     ok my $result = $replicated->schema->txn_do(sub {
865         return $replicated->schema->txn_do(sub {
866             ok my $more = $replicated->schema->resultset('Artist')->find(1)
867             => 'found inside a transaction inside a transaction';
868             is $debug{storage_type}, 'MASTER', "got last query from a master: $debug{dsn}";
869             return $more;
870         });
871     }) => 'successfully processed transaction';
872
873     is $result->id, 1
874        => 'Got expected single result from transaction';
875 }
876
877 {
878     ok my $result = $replicated->schema->txn_do(sub {
879         return $replicated->schema->storage->execute_reliably(sub {
880             return $replicated->schema->txn_do(sub {
881                 return $replicated->schema->storage->execute_reliably(sub {
882                     ok my $more = $replicated->schema->resultset('Artist')->find(1)
883                       => 'found inside crazy deep transactions and execute_reliably';
884                     is $debug{storage_type}, 'MASTER', "got last query from a master: $debug{dsn}";
885                     return $more;
886                 });
887             });
888         });
889     }) => 'successfully processed transaction';
890
891     is $result->id, 1
892        => 'Got expected single result from transaction';
893 }
894
895 ## Test the force_pool resultset attribute.
896
897 {
898     ok my $artist_rs = $replicated->schema->resultset('Artist')
899         => 'got artist resultset';
900
901     ## Turn on Forced Pool Storage
902     ok my $reliable_artist_rs = $artist_rs->search(undef, {force_pool=>'master'})
903         => 'Created a resultset using force_pool storage';
904
905     ok my $artist = $reliable_artist_rs->find(2)
906         => 'got an artist result via force_pool storage';
907
908     is $debug{storage_type}, 'MASTER', "got last query from a master: $debug{dsn}";
909 }
910
911 ## Test the force_pool resultset attribute part two.
912
913 {
914     ok my $artist_rs = $replicated->schema->resultset('Artist')
915         => 'got artist resultset';
916
917     ## Turn on Forced Pool Storage
918     ok my $reliable_artist_rs = $artist_rs->search(undef, {force_pool=>$replicant_names[0]})
919         => 'Created a resultset using force_pool storage';
920
921     ok my $artist = $reliable_artist_rs->find(2)
922         => 'got an artist result via force_pool storage';
923
924     is $debug{storage_type}, 'REPLICANT', "got last query from a replicant: $debug{dsn}";
925 }
926 ## Delete the old database files
927 $replicated->cleanup;
928
929 done_testing;
930
931 # vim: sw=4 sts=4 :