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