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