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