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