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