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