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