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