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