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