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