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