workaround for Moose bug affecting Replicated storage
[dbsrgits/DBIx-Class.git] / lib / DBIx / Class / Storage / DBI / Replicated.pm
1 package DBIx::Class::Storage::DBI::Replicated;
2
3 BEGIN {
4   use Carp::Clan qw/^DBIx::Class/;
5
6   ## Modules required for Replication support not required for general DBIC
7   ## use, so we explicitly test for these.
8
9   my %replication_required = (
10     'Moose' => '0.90',
11     'MooseX::Types' => '0.21',
12     'namespace::clean' => '0.11',
13     'Hash::Merge' => '0.11'
14   );
15
16   my @didnt_load;
17
18   for my $module (keys %replication_required) {
19     eval "use $module $replication_required{$module}";
20     push @didnt_load, "$module $replication_required{$module}"
21       if $@;
22   }
23
24   croak("@{[ join ', ', @didnt_load ]} are missing and are required for Replication")
25     if @didnt_load;
26 }
27
28 use Moose;
29 use DBIx::Class::Storage::DBI;
30 use DBIx::Class::Storage::DBI::Replicated::Pool;
31 use DBIx::Class::Storage::DBI::Replicated::Balancer;
32 use DBIx::Class::Storage::DBI::Replicated::Types qw/BalancerClassNamePart DBICSchema DBICStorageDBI/;
33 use MooseX::Types::Moose qw/ClassName HashRef Object/;
34 use Scalar::Util 'reftype';
35 use Hash::Merge 'merge';
36
37 use namespace::clean -except => 'meta';
38
39 =head1 NAME
40
41 DBIx::Class::Storage::DBI::Replicated - BETA Replicated database support
42
43 =head1 SYNOPSIS
44
45 The Following example shows how to change an existing $schema to a replicated
46 storage type, add some replicated (readonly) databases, and perform reporting
47 tasks.
48
49 You should set the 'storage_type attribute to a replicated type.  You should
50 also define your arguments, such as which balancer you want and any arguments
51 that the Pool object should get.
52
53   my $schema = Schema::Class->clone;
54   $schema->storage_type( ['::DBI::Replicated', {balancer=>'::Random'}] );
55   $schema->connection(...);
56
57 Next, you need to add in the Replicants.  Basically this is an array of 
58 arrayrefs, where each arrayref is database connect information.  Think of these
59 arguments as what you'd pass to the 'normal' $schema->connect method.
60
61   $schema->storage->connect_replicants(
62     [$dsn1, $user, $pass, \%opts],
63     [$dsn2, $user, $pass, \%opts],
64     [$dsn3, $user, $pass, \%opts],
65   );
66
67 Now, just use the $schema as you normally would.  Automatically all reads will
68 be delegated to the replicants, while writes to the master.
69
70   $schema->resultset('Source')->search({name=>'etc'});
71
72 You can force a given query to use a particular storage using the search
73 attribute 'force_pool'.  For example:
74
75   my $RS = $schema->resultset('Source')->search(undef, {force_pool=>'master'});
76
77 Now $RS will force everything (both reads and writes) to use whatever was setup
78 as the master storage.  'master' is hardcoded to always point to the Master, 
79 but you can also use any Replicant name.  Please see:
80 L<DBIx::Class::Storage::DBI::Replicated::Pool> and the replicants attribute for more.
81
82 Also see transactions and L</execute_reliably> for alternative ways to
83 force read traffic to the master.  In general, you should wrap your statements
84 in a transaction when you are reading and writing to the same tables at the
85 same time, since your replicants will often lag a bit behind the master.
86
87 See L<DBIx::Class::Storage::DBI::Replicated::Instructions> for more help and
88 walkthroughs.
89
90 =head1 DESCRIPTION
91
92 Warning: This class is marked BETA.  This has been running a production
93 website using MySQL native replication as its backend and we have some decent
94 test coverage but the code hasn't yet been stressed by a variety of databases.
95 Individual DB's may have quirks we are not aware of.  Please use this in first
96 development and pass along your experiences/bug fixes.
97
98 This class implements replicated data store for DBI. Currently you can define
99 one master and numerous slave database connections. All write-type queries
100 (INSERT, UPDATE, DELETE and even LAST_INSERT_ID) are routed to master
101 database, all read-type queries (SELECTs) go to the slave database.
102
103 Basically, any method request that L<DBIx::Class::Storage::DBI> would normally
104 handle gets delegated to one of the two attributes: L</read_handler> or to
105 L</write_handler>.  Additionally, some methods need to be distributed
106 to all existing storages.  This way our storage class is a drop in replacement
107 for L<DBIx::Class::Storage::DBI>.
108
109 Read traffic is spread across the replicants (slaves) occuring to a user
110 selected algorithm.  The default algorithm is random weighted.
111
112 =head1 NOTES
113
114 The consistancy betweeen master and replicants is database specific.  The Pool
115 gives you a method to validate its replicants, removing and replacing them
116 when they fail/pass predefined criteria.  Please make careful use of the ways
117 to force a query to run against Master when needed.
118
119 =head1 REQUIREMENTS
120
121 Replicated Storage has additional requirements not currently part of L<DBIx::Class>
122
123   Moose => '0.90',
124   MooseX::Types => '0.21',
125   namespace::clean => '0.11',
126   Hash::Merge => '0.11'
127
128 You will need to install these modules manually via CPAN or make them part of the
129 Makefile for your distribution.
130
131 =head1 ATTRIBUTES
132
133 This class defines the following attributes.
134
135 =head2 schema
136
137 The underlying L<DBIx::Class::Schema> object this storage is attaching
138
139 =cut
140
141 has 'schema' => (
142     is=>'rw',
143     isa=>DBICSchema,
144     weak_ref=>1,
145     required=>1,
146 );
147
148 =head2 pool_type
149
150 Contains the classname which will instantiate the L</pool> object.  Defaults 
151 to: L<DBIx::Class::Storage::DBI::Replicated::Pool>.
152
153 =cut
154
155 has 'pool_type' => (
156   is=>'rw',
157   isa=>ClassName,
158   default=>'DBIx::Class::Storage::DBI::Replicated::Pool',
159   handles=>{
160     'create_pool' => 'new',
161   },
162 );
163
164 =head2 pool_args
165
166 Contains a hashref of initialized information to pass to the Balancer object.
167 See L<DBIx::Class::Storage::DBI::Replicated::Pool> for available arguments.
168
169 =cut
170
171 has 'pool_args' => (
172   is=>'rw',
173   isa=>HashRef,
174   lazy=>1,
175   default=>sub { {} },
176 );
177
178
179 =head2 balancer_type
180
181 The replication pool requires a balance class to provider the methods for
182 choose how to spread the query load across each replicant in the pool.
183
184 =cut
185
186 has 'balancer_type' => (
187   is=>'rw',
188   isa=>BalancerClassNamePart,
189   coerce=>1,
190   required=>1,
191   default=> 'DBIx::Class::Storage::DBI::Replicated::Balancer::First',
192   handles=>{
193     'create_balancer' => 'new',
194   },
195 );
196
197 =head2 balancer_args
198
199 Contains a hashref of initialized information to pass to the Balancer object.
200 See L<DBIx::Class::Storage::DBI::Replicated::Balancer> for available arguments.
201
202 =cut
203
204 has 'balancer_args' => (
205   is=>'rw',
206   isa=>HashRef,
207   lazy=>1,
208   required=>1,
209   default=>sub { {} },
210 );
211
212 =head2 pool
213
214 Is a <DBIx::Class::Storage::DBI::Replicated::Pool> or derived class.  This is a
215 container class for one or more replicated databases.
216
217 =cut
218
219 has 'pool' => (
220   is=>'ro',
221   isa=>'DBIx::Class::Storage::DBI::Replicated::Pool',
222   lazy_build=>1,
223   handles=>[qw/
224     connect_replicants
225     replicants
226     has_replicants
227   /],
228 );
229
230 =head2 balancer
231
232 Is a <DBIx::Class::Storage::DBI::Replicated::Balancer> or derived class.  This 
233 is a class that takes a pool (<DBIx::Class::Storage::DBI::Replicated::Pool>)
234
235 =cut
236
237 has 'balancer' => (
238   is=>'rw',
239   isa=>'DBIx::Class::Storage::DBI::Replicated::Balancer',
240   lazy_build=>1,
241   handles=>[qw/auto_validate_every/],
242 );
243
244 =head2 master
245
246 The master defines the canonical state for a pool of connected databases.  All
247 the replicants are expected to match this databases state.  Thus, in a classic
248 Master / Slaves distributed system, all the slaves are expected to replicate
249 the Master's state as quick as possible.  This is the only database in the
250 pool of databases that is allowed to handle write traffic.
251
252 =cut
253
254 has 'master' => (
255   is=> 'ro',
256   isa=>DBICStorageDBI,
257   lazy_build=>1,
258 );
259
260 =head1 ATTRIBUTES IMPLEMENTING THE DBIx::Storage::DBI INTERFACE
261
262 The following methods are delegated all the methods required for the 
263 L<DBIx::Class::Storage::DBI> interface.
264
265 =head2 read_handler
266
267 Defines an object that implements the read side of L<BIx::Class::Storage::DBI>.
268
269 =cut
270
271 has 'read_handler' => (
272   is=>'rw',
273   isa=>Object,
274   lazy_build=>1,
275   handles=>[qw/
276     select
277     select_single
278     columns_info_for
279   /],
280 );
281
282 =head2 write_handler
283
284 Defines an object that implements the write side of L<BIx::Class::Storage::DBI>.
285
286 =cut
287
288 has 'write_handler' => (
289   is=>'ro',
290   isa=>Object,
291   lazy_build=>1,
292   handles=>[qw/
293     on_connect_do
294     on_disconnect_do
295     connect_info
296     throw_exception
297     sql_maker
298     sqlt_type
299     create_ddl_dir
300     deployment_statements
301     datetime_parser
302     datetime_parser_type
303     build_datetime_parser
304     last_insert_id
305     insert
306     insert_bulk
307     update
308     delete
309     dbh
310     txn_begin
311     txn_do
312     txn_commit
313     txn_rollback
314     txn_scope_guard
315     sth
316     deploy
317     with_deferred_fk_checks
318     dbh_do
319     reload_row
320     with_deferred_fk_checks
321     _prep_for_execute
322
323     backup
324     is_datatype_numeric
325     _count_select
326     _subq_count_select
327     _subq_update_delete
328     svp_rollback
329     svp_begin
330     svp_release
331   /],
332 );
333
334 has _master_connect_info_opts =>
335   (is => 'rw', isa => HashRef, default => sub { {} });
336
337 =head2 around: connect_info
338
339 Preserve master's C<connect_info> options (for merging with replicants.)
340 Also set any Replicated related options from connect_info, such as
341 C<pool_type>, C<pool_args>, C<balancer_type> and C<balancer_args>.
342
343 =cut
344
345 around connect_info => sub {
346   my ($next, $self, $info, @extra) = @_;
347
348   my $wantarray = wantarray;
349
350   my %opts;
351   for my $arg (@$info) {
352     next unless (reftype($arg)||'') eq 'HASH';
353     %opts = %{ merge($arg, \%opts) };
354   }
355   delete $opts{dsn};
356
357   if (@opts{qw/pool_type pool_args/}) {
358     $self->pool_type(delete $opts{pool_type})
359       if $opts{pool_type};
360
361     $self->pool_args(
362       merge((delete $opts{pool_args} || {}), $self->pool_args)
363     );
364
365     $self->pool($self->_build_pool)
366       if $self->pool;
367   }
368
369   if (@opts{qw/balancer_type balancer_args/}) {
370     $self->balancer_type(delete $opts{balancer_type})
371       if $opts{balancer_type};
372
373     $self->balancer_args(
374       merge((delete $opts{balancer_args} || {}), $self->balancer_args)
375     );
376
377     $self->balancer($self->_build_balancer)
378       if $self->balancer;
379   }
380
381   $self->_master_connect_info_opts(\%opts);
382
383   my (@res, $res);
384   if ($wantarray) {
385     @res = $self->$next($info, @extra);
386   } else {
387     $res = $self->$next($info, @extra);
388   }
389
390   # Make sure master is blessed into the correct class and apply role to it.
391   my $master = $self->master;
392   $master->_determine_driver;
393   Moose::Meta::Class->initialize(ref $master);
394
395   my $class = Moose::Meta::Class->create_anon_class(
396     superclasses => [ ref $master ],
397     roles        => [ 'DBIx::Class::Storage::DBI::Replicated::WithDSN' ],
398     cache        => 1,
399   );
400   $class->rebless_instance($master);
401
402   # link pool back to master
403   $self->pool->master($master);
404
405   $wantarray ? @res : $res;
406 };
407
408 =head1 METHODS
409
410 This class defines the following methods.
411
412 =head2 BUILDARGS
413
414 L<DBIx::Class::Schema> when instantiating its storage passed itself as the
415 first argument.  So we need to massage the arguments a bit so that all the
416 bits get put into the correct places.
417
418 =cut
419
420 sub BUILDARGS {
421   my ($class, $schema, $storage_type_args, @args) = @_;  
422
423   return {
424     schema=>$schema,
425     %$storage_type_args,
426     @args
427   }
428 }
429
430 =head2 _build_master
431
432 Lazy builder for the L</master> attribute.
433
434 =cut
435
436 sub _build_master {
437   my $self = shift @_;
438   my $master = DBIx::Class::Storage::DBI->new($self->schema);
439   $master
440 }
441
442 =head2 _build_pool
443
444 Lazy builder for the L</pool> attribute.
445
446 =cut
447
448 sub _build_pool {
449   my $self = shift @_;
450   $self->create_pool(%{$self->pool_args});
451 }
452
453 =head2 _build_balancer
454
455 Lazy builder for the L</balancer> attribute.  This takes a Pool object so that
456 the balancer knows which pool it's balancing.
457
458 =cut
459
460 sub _build_balancer {
461   my $self = shift @_;
462   $self->create_balancer(
463     pool=>$self->pool,
464     master=>$self->master,
465     %{$self->balancer_args},
466   );
467 }
468
469 =head2 _build_write_handler
470
471 Lazy builder for the L</write_handler> attribute.  The default is to set this to
472 the L</master>.
473
474 =cut
475
476 sub _build_write_handler {
477   return shift->master;
478 }
479
480 =head2 _build_read_handler
481
482 Lazy builder for the L</read_handler> attribute.  The default is to set this to
483 the L</balancer>.
484
485 =cut
486
487 sub _build_read_handler {
488   return shift->balancer;
489 }
490
491 =head2 around: connect_replicants
492
493 All calls to connect_replicants needs to have an existing $schema tacked onto
494 top of the args, since L<DBIx::Storage::DBI> needs it, and any C<connect_info>
495 options merged with the master, with replicant opts having higher priority.
496
497 =cut
498
499 around connect_replicants => sub {
500   my ($next, $self, @args) = @_;
501
502   for my $r (@args) {
503     $r = [ $r ] unless reftype $r eq 'ARRAY';
504
505     $self->throw_exception('coderef replicant connect_info not supported')
506       if ref $r->[0] && reftype $r->[0] eq 'CODE';
507
508 # any connect_info options?
509     my $i = 0;
510     $i++ while $i < @$r && (reftype($r->[$i])||'') ne 'HASH';
511
512 # make one if none
513     $r->[$i] = {} unless $r->[$i];
514
515 # merge if two hashes
516     my @hashes = @$r[$i .. $#{$r}];
517
518     $self->throw_exception('invalid connect_info options')
519       if (grep { reftype($_) eq 'HASH' } @hashes) != @hashes;
520
521     $self->throw_exception('too many hashrefs in connect_info')
522       if @hashes > 2;
523
524     my %opts = %{ merge(reverse @hashes) };
525
526 # delete them
527     splice @$r, $i+1, ($#{$r} - $i), ();
528
529 # make sure master/replicants opts don't clash
530     my %master_opts = %{ $self->_master_connect_info_opts };
531     if (exists $opts{dbh_maker}) {
532         delete @master_opts{qw/dsn user password/};
533     }
534     delete $master_opts{dbh_maker};
535
536 # merge with master
537     %opts = %{ merge(\%opts, \%master_opts) };
538
539 # update
540     $r->[$i] = \%opts;
541   }
542
543   $self->$next($self->schema, @args);
544 };
545
546 =head2 all_storages
547
548 Returns an array of of all the connected storage backends.  The first element
549 in the returned array is the master, and the remainings are each of the
550 replicants.
551
552 =cut
553
554 sub all_storages {
555   my $self = shift @_;
556   return grep {defined $_ && blessed $_} (
557      $self->master,
558      values %{ $self->replicants },
559   );
560 }
561
562 =head2 execute_reliably ($coderef, ?@args)
563
564 Given a coderef, saves the current state of the L</read_handler>, forces it to
565 use reliable storage (ie sets it to the master), executes a coderef and then
566 restores the original state.
567
568 Example:
569
570   my $reliably = sub {
571     my $name = shift @_;
572     $schema->resultset('User')->create({name=>$name});
573     my $user_rs = $schema->resultset('User')->find({name=>$name}); 
574     return $user_rs;
575   };
576
577   my $user_rs = $schema->storage->execute_reliably($reliably, 'John');
578
579 Use this when you must be certain of your database state, such as when you just
580 inserted something and need to get a resultset including it, etc.
581
582 =cut
583
584 sub execute_reliably {
585   my ($self, $coderef, @args) = @_;
586
587   unless( ref $coderef eq 'CODE') {
588     $self->throw_exception('Second argument must be a coderef');
589   }
590
591   ##Get copy of master storage
592   my $master = $self->master;
593
594   ##Get whatever the current read hander is
595   my $current = $self->read_handler;
596
597   ##Set the read handler to master
598   $self->read_handler($master);
599
600   ## do whatever the caller needs
601   my @result;
602   my $want_array = wantarray;
603
604   eval {
605     if($want_array) {
606       @result = $coderef->(@args);
607     } elsif(defined $want_array) {
608       ($result[0]) = ($coderef->(@args));
609     } else {
610       $coderef->(@args);
611     }
612   };
613
614   ##Reset to the original state
615   $self->read_handler($current);
616
617   ##Exception testing has to come last, otherwise you might leave the 
618   ##read_handler set to master.
619
620   if($@) {
621     $self->throw_exception("coderef returned an error: $@");
622   } else {
623     return $want_array ? @result : $result[0];
624   }
625 }
626
627 =head2 set_reliable_storage
628
629 Sets the current $schema to be 'reliable', that is all queries, both read and
630 write are sent to the master
631
632 =cut
633
634 sub set_reliable_storage {
635   my $self = shift @_;
636   my $schema = $self->schema;
637   my $write_handler = $self->schema->storage->write_handler;
638
639   $schema->storage->read_handler($write_handler);
640 }
641
642 =head2 set_balanced_storage
643
644 Sets the current $schema to be use the </balancer> for all reads, while all
645 writea are sent to the master only
646
647 =cut
648
649 sub set_balanced_storage {
650   my $self = shift @_;
651   my $schema = $self->schema;
652   my $balanced_handler = $self->schema->storage->balancer;
653
654   $schema->storage->read_handler($balanced_handler);
655 }
656
657 =head2 connected
658
659 Check that the master and at least one of the replicants is connected.
660
661 =cut
662
663 sub connected {
664   my $self = shift @_;
665   return
666     $self->master->connected &&
667     $self->pool->connected_replicants;
668 }
669
670 =head2 ensure_connected
671
672 Make sure all the storages are connected.
673
674 =cut
675
676 sub ensure_connected {
677   my $self = shift @_;
678   foreach my $source ($self->all_storages) {
679     $source->ensure_connected(@_);
680   }
681 }
682
683 =head2 limit_dialect
684
685 Set the limit_dialect for all existing storages
686
687 =cut
688
689 sub limit_dialect {
690   my $self = shift @_;
691   foreach my $source ($self->all_storages) {
692     $source->limit_dialect(@_);
693   }
694   return $self->master->quote_char;
695 }
696
697 =head2 quote_char
698
699 Set the quote_char for all existing storages
700
701 =cut
702
703 sub quote_char {
704   my $self = shift @_;
705   foreach my $source ($self->all_storages) {
706     $source->quote_char(@_);
707   }
708   return $self->master->quote_char;
709 }
710
711 =head2 name_sep
712
713 Set the name_sep for all existing storages
714
715 =cut
716
717 sub name_sep {
718   my $self = shift @_;
719   foreach my $source ($self->all_storages) {
720     $source->name_sep(@_);
721   }
722   return $self->master->name_sep;
723 }
724
725 =head2 set_schema
726
727 Set the schema object for all existing storages
728
729 =cut
730
731 sub set_schema {
732   my $self = shift @_;
733   foreach my $source ($self->all_storages) {
734     $source->set_schema(@_);
735   }
736 }
737
738 =head2 debug
739
740 set a debug flag across all storages
741
742 =cut
743
744 sub debug {
745   my $self = shift @_;
746   if(@_) {
747     foreach my $source ($self->all_storages) {
748       $source->debug(@_);
749     }
750   }
751   return $self->master->debug;
752 }
753
754 =head2 debugobj
755
756 set a debug object
757
758 =cut
759
760 sub debugobj {
761   my $self = shift @_;
762   return $self->master->debugobj(@_);
763 }
764
765 =head2 debugfh
766
767 set a debugfh object
768
769 =cut
770
771 sub debugfh {
772   my $self = shift @_;
773   return $self->master->debugfh(@_);
774 }
775
776 =head2 debugcb
777
778 set a debug callback
779
780 =cut
781
782 sub debugcb {
783   my $self = shift @_;
784   return $self->master->debugcb(@_);
785 }
786
787 =head2 disconnect
788
789 disconnect everything
790
791 =cut
792
793 sub disconnect {
794   my $self = shift @_;
795   foreach my $source ($self->all_storages) {
796     $source->disconnect(@_);
797   }
798 }
799
800 =head2 cursor_class
801
802 set cursor class on all storages, or return master's
803
804 =cut
805
806 sub cursor_class {
807   my ($self, $cursor_class) = @_;
808
809   if ($cursor_class) {
810     $_->cursor_class($cursor_class) for $self->all_storages;
811   }
812   $self->master->cursor_class;
813 }
814
815 =head1 GOTCHAS
816
817 Due to the fact that replicants can lag behind a master, you must take care to
818 make sure you use one of the methods to force read queries to a master should
819 you need realtime data integrity.  For example, if you insert a row, and then
820 immediately re-read it from the database (say, by doing $row->discard_changes)
821 or you insert a row and then immediately build a query that expects that row
822 to be an item, you should force the master to handle reads.  Otherwise, due to
823 the lag, there is no certainty your data will be in the expected state.
824
825 For data integrity, all transactions automatically use the master storage for
826 all read and write queries.  Using a transaction is the preferred and recommended
827 method to force the master to handle all read queries.
828
829 Otherwise, you can force a single query to use the master with the 'force_pool'
830 attribute:
831
832   my $row = $resultset->search(undef, {force_pool=>'master'})->find($pk);
833
834 This attribute will safely be ignore by non replicated storages, so you can use
835 the same code for both types of systems.
836
837 Lastly, you can use the L</execute_reliably> method, which works very much like
838 a transaction.
839
840 For debugging, you can turn replication on/off with the methods L</set_reliable_storage>
841 and L</set_balanced_storage>, however this operates at a global level and is not
842 suitable if you have a shared Schema object being used by multiple processes,
843 such as on a web application server.  You can get around this limitation by
844 using the Schema clone method.
845
846   my $new_schema = $schema->clone;
847   $new_schema->set_reliable_storage;
848
849   ## $new_schema will use only the Master storage for all reads/writes while
850   ## the $schema object will use replicated storage.
851
852 =head1 AUTHOR
853
854   John Napiorkowski <john.napiorkowski@takkle.com>
855
856 Based on code originated by:
857
858   Norbert Csongrádi <bert@cpan.org>
859   Peter Siklósi <einon@einon.hu>
860
861 =head1 LICENSE
862
863 You may distribute this code under the same terms as Perl itself.
864
865 =cut
866
867 __PACKAGE__->meta->make_immutable;
868
869 1;