Replicated - fixup types and namespace::clean
[dbsrgits/DBIx-Class.git] / t / 93storage_replication.t
CommitLineData
e4dc89b3 1use strict;
2use warnings;
3use lib qw(t/lib);
e4dc89b3 4use Test::More;
c4d3fae2 5use Test::Exception;
857d66ca 6use DBICTest;
9901aad7 7use List::Util 'first';
8f7986d6 8
86583fa7 9BEGIN {
650c0574 10 eval "use DBIx::Class::Storage::DBI::Replicated; use Test::Moose";
86583fa7 11 plan $@
467799e8 12 ? ( skip_all => "Deps not installed: $@" )
6412a592 13 : ( tests => 82 );
26ab719a 14}
15
16use_ok 'DBIx::Class::Storage::DBI::Replicated::Pool';
17use_ok 'DBIx::Class::Storage::DBI::Replicated::Balancer';
18use_ok 'DBIx::Class::Storage::DBI::Replicated::Replicant';
19use_ok 'DBIx::Class::Storage::DBI::Replicated';
0f83441a 20
89cf6a70 21=head1 HOW TO USE
22
23 This is a test of the replicated storage system. This will work in one of
24 two ways, either it was try to fake replication with a couple of SQLite DBs
25 and creative use of copy, or if you define a couple of %ENV vars correctly
26 will try to test those. If you do that, it will assume the setup is properly
27 replicating. Your results may vary, but I have demonstrated this to work with
28 mysql native replication.
29
30=cut
31
32
0f83441a 33## ----------------------------------------------------------------------------
34## Build a class to hold all our required testing data and methods.
35## ----------------------------------------------------------------------------
36
857d66ca 37TESTSCHEMACLASSES: {
2bf79155 38
857d66ca 39 ## --------------------------------------------------------------------- ##
40 ## Create an object to contain your replicated stuff.
41 ## --------------------------------------------------------------------- ##
42
2bf79155 43 package DBIx::Class::DBI::Replicated::TestReplication;
44
45 use DBICTest;
46 use base qw/Class::Accessor::Fast/;
47
857d66ca 48 __PACKAGE__->mk_accessors( qw/schema/ );
2bf79155 49
50 ## Initialize the object
51
52 sub new {
26ab719a 53 my $class = shift @_;
54 my $self = $class->SUPER::new(@_);
2bf79155 55
56 $self->schema( $self->init_schema );
2bf79155 57 return $self;
58 }
59
26ab719a 60 ## Get the Schema and set the replication storage type
2bf79155 61
62 sub init_schema {
f6ace689 63 # current SQLT SQLite producer does not handle DROP TABLE IF EXISTS, trap warnings here
64 local $SIG{__WARN__} = sub { warn @_ unless $_[0] =~ /no such table.+DROP TABLE/ };
65
2bf79155 66 my $class = shift @_;
f6ace689 67
cb6ec758 68 my $schema = DBICTest->init_schema(
bcb3e850 69 sqlite_use_file => 1,
161fb223 70 storage_type=>{
106d5f3b 71 '::DBI::Replicated' => {
72 balancer_type=>'::Random',
17b05c13 73 balancer_args=>{
74 auto_validate_every=>100,
75 },
89cf6a70 76 }
161fb223 77 },
89cf6a70 78 deploy_args=>{
79 add_drop_table => 1,
80 },
81 );
cb6ec758 82
2bf79155 83 return $schema;
84 }
26ab719a 85
857d66ca 86 sub generate_replicant_connect_info {}
87 sub replicate {}
88 sub cleanup {}
89
90
91 ## --------------------------------------------------------------------- ##
92 ## Subclass for when you are using SQLite for testing, this provides a fake
93 ## replication support.
94 ## --------------------------------------------------------------------- ##
95
96 package DBIx::Class::DBI::Replicated::TestReplication::SQLite;
97
98 use DBICTest;
99 use File::Copy;
100 use base 'DBIx::Class::DBI::Replicated::TestReplication';
101
102 __PACKAGE__->mk_accessors( qw/master_path slave_paths/ );
103
104 ## Set the mastep path from DBICTest
105
106 sub new {
107 my $class = shift @_;
108 my $self = $class->SUPER::new(@_);
109
110 $self->master_path( DBICTest->_sqlite_dbfilename );
111 $self->slave_paths([
112 "t/var/DBIxClass_slave1.db",
113 "t/var/DBIxClass_slave2.db",
114 ]);
115
116 return $self;
117 }
118
26ab719a 119 ## Return an Array of ArrayRefs where each ArrayRef is suitable to use for
120 ## $storage->connect_info to be used for connecting replicants.
121
122 sub generate_replicant_connect_info {
857d66ca 123 my $self = shift @_;
26ab719a 124 my @dsn = map {
125 "dbi:SQLite:${_}";
126 } @{$self->slave_paths};
127
9901aad7 128 my @connect_infos = map { [$_,'','',{AutoCommit=>1}] } @dsn;
129
130 # try a hashref too
131 my $c = $connect_infos[0];
132 $connect_infos[0] = {
133 dsn => $c->[0],
134 user => $c->[1],
135 password => $c->[2],
136 %{ $c->[3] }
137 };
138
139 @connect_infos
26ab719a 140 }
9901aad7 141
26ab719a 142 ## Do a 'good enough' replication by copying the master dbfile over each of
50336325 143 ## the slave dbfiles. If the master is SQLite we do this, otherwise we
144 ## just do a one second pause to let the slaves catch up.
26ab719a 145
146 sub replicate {
147 my $self = shift @_;
148 foreach my $slave (@{$self->slave_paths}) {
149 copy($self->master_path, $slave);
150 }
151 }
152
153 ## Cleanup after ourselves. Unlink all gthe slave paths.
154
155 sub cleanup {
156 my $self = shift @_;
157 foreach my $slave (@{$self->slave_paths}) {
158 unlink $slave;
159 }
160 }
857d66ca 161
162 ## --------------------------------------------------------------------- ##
163 ## Subclass for when you are setting the databases via custom export vars
164 ## This is for when you have a replicating database setup that you are
165 ## going to test against. You'll need to define the correct $ENV and have
166 ## two slave databases to test against, as well as a replication system
167 ## that will replicate in less than 1 second.
168 ## --------------------------------------------------------------------- ##
169
170 package DBIx::Class::DBI::Replicated::TestReplication::Custom;
171 use base 'DBIx::Class::DBI::Replicated::TestReplication';
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 return (
178 [$ENV{"DBICTEST_SLAVE0_DSN"}, $ENV{"DBICTEST_SLAVE0_DBUSER"}, $ENV{"DBICTEST_SLAVE0_DBPASS"}, {AutoCommit => 1}],
179 [$ENV{"DBICTEST_SLAVE1_DSN"}, $ENV{"DBICTEST_SLAVE1_DBUSER"}, $ENV{"DBICTEST_SLAVE1_DBPASS"}, {AutoCommit => 1}],
180 );
181 }
182
183 ## pause a bit to let the replication catch up
184
185 sub replicate {
186 sleep 1;
187 }
2bf79155 188}
189
190## ----------------------------------------------------------------------------
191## Create an object and run some tests
192## ----------------------------------------------------------------------------
193
26ab719a 194## Thi first bunch of tests are basic, just make sure all the bits are behaving
2bf79155 195
857d66ca 196my $replicated_class = DBICTest->has_custom_dsn ?
197 'DBIx::Class::DBI::Replicated::TestReplication::Custom' :
198 'DBIx::Class::DBI::Replicated::TestReplication::SQLite';
199
200ok my $replicated = $replicated_class->new
201 => 'Created a replication object';
2bf79155 202
26ab719a 203isa_ok $replicated->schema
2bf79155 204 => 'DBIx::Class::Schema';
205
26ab719a 206isa_ok $replicated->schema->storage
207 => 'DBIx::Class::Storage::DBI::Replicated';
208
209ok $replicated->schema->storage->meta
210 => 'has a meta object';
211
212isa_ok $replicated->schema->storage->master
213 => 'DBIx::Class::Storage::DBI';
214
215isa_ok $replicated->schema->storage->pool
216 => 'DBIx::Class::Storage::DBI::Replicated::Pool';
217
17b05c13 218does_ok $replicated->schema->storage->balancer
26ab719a 219 => 'DBIx::Class::Storage::DBI::Replicated::Balancer';
220
221ok my @replicant_connects = $replicated->generate_replicant_connect_info
222 => 'got replication connect information';
223
955a6df6 224ok my @replicated_storages = $replicated->schema->storage->connect_replicants(@replicant_connects)
26ab719a 225 => 'Created some storages suitable for replicants';
6412a592 226
227ok my @all_storages = $replicated->schema->storage->all_storages
228 => '->all_storages';
229
230ok @all_storages == 3
231 => 'correct number of ->all_storages';
232
233ok ((grep $_->isa('DBIx::Class::Storage::DBI'), @all_storages) == 3
234 => '->all_storages are correct type');
9901aad7 235
236my @replicant_names = keys %{ $replicated->schema->storage->replicants };
237
238## Silence warning about not supporting the is_replicating method if using the
239## sqlite dbs.
240$replicated->schema->storage->debugobj->silence(1)
241 if first { m{^t/} } @replicant_names;
242
cb6ec758 243isa_ok $replicated->schema->storage->balancer->current_replicant
9901aad7 244 => 'DBIx::Class::Storage::DBI';
245
246$replicated->schema->storage->debugobj->silence(0);
247
26ab719a 248ok $replicated->schema->storage->pool->has_replicants
249 => 'does have replicants';
250
17b05c13 251is $replicated->schema->storage->pool->num_replicants => 2
26ab719a 252 => 'has two replicants';
253
de5dc9ef 254does_ok $replicated_storages[0]
26ab719a 255 => 'DBIx::Class::Storage::DBI::Replicated::Replicant';
256
de5dc9ef 257does_ok $replicated_storages[1]
26ab719a 258 => 'DBIx::Class::Storage::DBI::Replicated::Replicant';
259
de5dc9ef 260does_ok $replicated->schema->storage->replicants->{$replicant_names[0]}
26ab719a 261 => 'DBIx::Class::Storage::DBI::Replicated::Replicant';
262
de5dc9ef 263does_ok $replicated->schema->storage->replicants->{$replicant_names[1]}
26ab719a 264 => 'DBIx::Class::Storage::DBI::Replicated::Replicant';
265
266## Add some info to the database
267
268$replicated
269 ->schema
270 ->populate('Artist', [
271 [ qw/artistid name/ ],
272 [ 4, "Ozric Tentacles"],
273 ]);
274
275## Make sure all the slaves have the table definitions
276
277$replicated->replicate;
5c1d82d2 278$replicated->schema->storage->replicants->{$replicant_names[0]}->active(1);
279$replicated->schema->storage->replicants->{$replicant_names[1]}->active(1);
9901aad7 280
281## Silence warning about not supporting the is_replicating method if using the
282## sqlite dbs.
283$replicated->schema->storage->debugobj->silence(1)
284 if first { m{^t/} } @replicant_names;
285
f15afa13 286$replicated->schema->storage->pool->validate_replicants;
26ab719a 287
9901aad7 288$replicated->schema->storage->debugobj->silence(0);
289
26ab719a 290## Make sure we can read the data.
291
292ok my $artist1 = $replicated->schema->resultset('Artist')->find(4)
293 => 'Created Result';
294
295isa_ok $artist1
296 => 'DBICTest::Artist';
297
298is $artist1->name, 'Ozric Tentacles'
299 => 'Found expected name for first result';
300
301## Add some new rows that only the master will have This is because
302## we overload any type of write operation so that is must hit the master
303## database.
304
305$replicated
306 ->schema
307 ->populate('Artist', [
308 [ qw/artistid name/ ],
309 [ 5, "Doom's Children"],
310 [ 6, "Dead On Arrival"],
311 [ 7, "Watergate"],
312 ]);
313
26ab719a 314## Make sure all the slaves have the table definitions
315$replicated->replicate;
316
317## Should find some data now
318
319ok my $artist2 = $replicated->schema->resultset('Artist')->find(5)
320 => 'Sync succeed';
321
322isa_ok $artist2
323 => 'DBICTest::Artist';
324
325is $artist2->name, "Doom's Children"
326 => 'Found expected name for first result';
327
328## What happens when we disconnect all the replicants?
329
50336325 330is $replicated->schema->storage->pool->connected_replicants => 2
331 => "both replicants are connected";
332
89cf6a70 333$replicated->schema->storage->replicants->{$replicant_names[0]}->disconnect;
334$replicated->schema->storage->replicants->{$replicant_names[1]}->disconnect;
26ab719a 335
50336325 336is $replicated->schema->storage->pool->connected_replicants => 0
337 => "both replicants are now disconnected";
338
339## All these should pass, since the database should automatically reconnect
340
26ab719a 341ok my $artist3 = $replicated->schema->resultset('Artist')->find(6)
342 => 'Still finding stuff.';
2bf79155 343
26ab719a 344isa_ok $artist3
345 => 'DBICTest::Artist';
2bf79155 346
26ab719a 347is $artist3->name, "Dead On Arrival"
348 => 'Found expected name for first result';
2bf79155 349
50336325 350is $replicated->schema->storage->pool->connected_replicants => 1
13b9e828 351 => "At Least One replicant reconnected to handle the job";
6f6fb437 352
353## What happens when we try to select something that doesn't exist?
354
355ok ! $replicated->schema->resultset('Artist')->find(666)
356 => 'Correctly failed to find something.';
cb6ec758 357
358## test the reliable option
359
360TESTRELIABLE: {
361
362 $replicated->schema->storage->set_reliable_storage;
363
364 ok $replicated->schema->resultset('Artist')->find(2)
365 => 'Read from master 1';
366
367 ok $replicated->schema->resultset('Artist')->find(5)
368 => 'Read from master 2';
369
370 $replicated->schema->storage->set_balanced_storage;
371
372 ok $replicated->schema->resultset('Artist')->find(3)
9c748388 373 => 'Read from replicant';
cb6ec758 374}
375
9c748388 376## Make sure when reliable goes out of scope, we are using replicants again
cb6ec758 377
378ok $replicated->schema->resultset('Artist')->find(1)
379 => 'back to replicant 1.';
380
381ok $replicated->schema->resultset('Artist')->find(2)
382 => 'back to replicant 2.';
2156bbdd 383
106d5f3b 384## set all the replicants to inactive, and make sure the balancer falls back to
385## the master.
386
89cf6a70 387$replicated->schema->storage->replicants->{$replicant_names[0]}->active(0);
388$replicated->schema->storage->replicants->{$replicant_names[1]}->active(0);
9901aad7 389
390## Silence warning about falling back to master.
391$replicated->schema->storage->debugobj->silence(1);
392
106d5f3b 393ok $replicated->schema->resultset('Artist')->find(2)
de5dc9ef 394 => 'Fallback to master';
395
9901aad7 396$replicated->schema->storage->debugobj->silence(0);
397
de5dc9ef 398$replicated->schema->storage->replicants->{$replicant_names[0]}->active(1);
399$replicated->schema->storage->replicants->{$replicant_names[1]}->active(1);
9901aad7 400
401## Silence warning about not supporting the is_replicating method if using the
402## sqlite dbs.
403$replicated->schema->storage->debugobj->silence(1)
404 if first { m{^t/} } @replicant_names;
405
f15afa13 406$replicated->schema->storage->pool->validate_replicants;
de5dc9ef 407
9901aad7 408$replicated->schema->storage->debugobj->silence(0);
409
de5dc9ef 410ok $replicated->schema->resultset('Artist')->find(2)
411 => 'Returned to replicates';
412
413## Getting slave status tests
414
f797e89e 415SKIP: {
416 ## We skip this tests unless you have a custom replicants, since the default
417 ## sqlite based replication tests don't support these functions.
418
17b05c13 419 skip 'Cannot Test Replicant Status on Non Replicating Database', 9
f797e89e 420 unless DBICTest->has_custom_dsn && $ENV{"DBICTEST_SLAVE0_DSN"};
421
422 $replicated->replicate; ## Give the slaves a chance to catchup.
423
424 ok $replicated->schema->storage->replicants->{$replicant_names[0]}->is_replicating
425 => 'Replicants are replicating';
426
427 is $replicated->schema->storage->replicants->{$replicant_names[0]}->lag_behind_master, 0
428 => 'Replicant is zero seconds behind master';
7edf5f1c 429
430 ## Test the validate replicants
431
432 $replicated->schema->storage->pool->validate_replicants;
433
434 is $replicated->schema->storage->pool->active_replicants, 2
435 => 'Still have 2 replicants after validation';
436
437 ## Force the replicants to fail the validate test by required their lag to
438 ## be negative (ie ahead of the master!)
439
440 $replicated->schema->storage->pool->maximum_lag(-10);
441 $replicated->schema->storage->pool->validate_replicants;
442
443 is $replicated->schema->storage->pool->active_replicants, 0
444 => 'No way a replicant be be ahead of the master';
445
446 ## Let's be fair to the replicants again. Let them lag up to 5
447
448 $replicated->schema->storage->pool->maximum_lag(5);
449 $replicated->schema->storage->pool->validate_replicants;
450
451 is $replicated->schema->storage->pool->active_replicants, 2
452 => 'Both replicants in good standing again';
17b05c13 453
454 ## Check auto validate
455
456 is $replicated->schema->storage->balancer->auto_validate_every, 100
457 => "Got the expected value for auto validate";
458
459 ## This will make sure we auto validatge everytime
460 $replicated->schema->storage->balancer->auto_validate_every(0);
461
462 ## set all the replicants to inactive, and make sure the balancer falls back to
463 ## the master.
464
465 $replicated->schema->storage->replicants->{$replicant_names[0]}->active(0);
466 $replicated->schema->storage->replicants->{$replicant_names[1]}->active(0);
467
468 ## Ok, now when we go to run a query, autovalidate SHOULD reconnect
469
470 is $replicated->schema->storage->pool->active_replicants => 0
471 => "both replicants turned off";
472
473 ok $replicated->schema->resultset('Artist')->find(5)
474 => 'replicant reactivated';
475
476 is $replicated->schema->storage->pool->active_replicants => 2
477 => "both replicants reactivated";
f797e89e 478}
479
c4d3fae2 480## Test the reliably callback
481
482ok my $reliably = sub {
483
484 ok $replicated->schema->resultset('Artist')->find(5)
485 => 'replicant reactivated';
486
487} => 'created coderef properly';
488
489$replicated->schema->storage->execute_reliably($reliably);
490
491## Try something with an error
492
493ok my $unreliably = sub {
494
495 ok $replicated->schema->resultset('ArtistXX')->find(5)
496 => 'replicant reactivated';
497
498} => 'created coderef properly';
499
500throws_ok {$replicated->schema->storage->execute_reliably($unreliably)}
ed213e85 501 qr/Can't find source for ArtistXX/
c4d3fae2 502 => 'Bad coderef throws proper error';
503
ed213e85 504## Make sure replication came back
505
506ok $replicated->schema->resultset('Artist')->find(3)
507 => 'replicant reactivated';
508
c4d3fae2 509## make sure transactions are set to execute_reliably
510
511ok my $transaction = sub {
512
ed213e85 513 my $id = shift @_;
514
c4d3fae2 515 $replicated
516 ->schema
517 ->populate('Artist', [
518 [ qw/artistid name/ ],
ed213e85 519 [ $id, "Children of the Grave"],
c4d3fae2 520 ]);
521
64cdad22 522 ok my $result = $replicated->schema->resultset('Artist')->find($id)
523 => 'Found expected artist';
524
525 ok my $more = $replicated->schema->resultset('Artist')->find(1)
526 => 'Found expected artist again';
527
ed213e85 528 return ($result, $more);
c4d3fae2 529
64cdad22 530} => 'Created a coderef properly';
c4d3fae2 531
ed213e85 532## Test the transaction with multi return
533{
534 ok my @return = $replicated->schema->txn_do($transaction, 666)
535 => 'did transaction';
536
537 is $return[0]->id, 666
538 => 'first returned value is correct';
539
540 is $return[1]->id, 1
541 => 'second returned value is correct';
542}
543
544## Test that asking for single return works
545{
546 ok my $return = $replicated->schema->txn_do($transaction, 777)
547 => 'did transaction';
548
549 is $return->id, 777
550 => 'first returned value is correct';
551}
552
553## Test transaction returning a single value
554
555{
556 ok my $result = $replicated->schema->txn_do(sub {
64cdad22 557 ok my $more = $replicated->schema->resultset('Artist')->find(1)
558 => 'found inside a transaction';
ed213e85 559 return $more;
560 }) => 'successfully processed transaction';
561
562 is $result->id, 1
563 => 'Got expected single result from transaction';
564}
c4d3fae2 565
566## Make sure replication came back
567
ed213e85 568ok $replicated->schema->resultset('Artist')->find(1)
c4d3fae2 569 => 'replicant reactivated';
ed213e85 570
571## Test Discard changes
572
573{
574 ok my $artist = $replicated->schema->resultset('Artist')->find(2)
575 => 'got an artist to test discard changes';
576
577 ok $artist->discard_changes
578 => 'properly discard changes';
579}
64cdad22 580
581## Test some edge cases, like trying to do a transaction inside a transaction, etc
582
583{
584 ok my $result = $replicated->schema->txn_do(sub {
585 return $replicated->schema->txn_do(sub {
586 ok my $more = $replicated->schema->resultset('Artist')->find(1)
587 => 'found inside a transaction inside a transaction';
588 return $more;
589 });
590 }) => 'successfully processed transaction';
591
592 is $result->id, 1
593 => 'Got expected single result from transaction';
594}
595
596{
597 ok my $result = $replicated->schema->txn_do(sub {
598 return $replicated->schema->storage->execute_reliably(sub {
599 return $replicated->schema->txn_do(sub {
600 return $replicated->schema->storage->execute_reliably(sub {
601 ok my $more = $replicated->schema->resultset('Artist')->find(1)
602 => 'found inside crazy deep transactions and execute_reliably';
603 return $more;
604 });
605 });
606 });
607 }) => 'successfully processed transaction';
608
609 is $result->id, 1
610 => 'Got expected single result from transaction';
611}
2ce6e9a6 612
7e38d850 613## Test the force_pool resultset attribute.
bbafcf26 614
615{
616 ok my $artist_rs = $replicated->schema->resultset('Artist')
617 => 'got artist resultset';
618
7e38d850 619 ## Turn on Forced Pool Storage
620 ok my $reliable_artist_rs = $artist_rs->search(undef, {force_pool=>'master'})
621 => 'Created a resultset using force_pool storage';
bbafcf26 622
623 ok my $artist = $reliable_artist_rs->find(2)
7e38d850 624 => 'got an artist result via force_pool storage';
bbafcf26 625}
626
0f83441a 627## Delete the old database files
50336325 628$replicated->cleanup;