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