1 package DBIx::Class::Storage::DBI::Replicated;
4 use Carp::Clan qw/^DBIx::Class/;
6 ## Modules required for Replication support not required for general DBIC
7 ## use, so we explicitly test for these.
9 my %replication_required = (
11 MooseX::AttributeHelpers => '0.12',
12 MooseX::Types => '0.10',
13 namespace::clean => '0.11',
19 for my $module (keys %replication_required) {
20 eval "use $module $replication_required{$module}";
21 push @didnt_load, "$module $replication_required{$module}"
25 croak("@{[ join ', ', @didnt_load ]} are missing and are required for Replication")
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 'BalancerClassNamePart';
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';
39 use namespace::clean -except => 'meta';
43 DBIx::Class::Storage::DBI::Replicated - BETA Replicated database support
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
51 ## Change storage_type in your schema class
52 $schema->storage_type( ['::DBI::Replicated', {balancer=>'::Random'}] );
54 ## Add some slaves. Basically this is an array of arrayrefs, where each
55 ## arrayref is database connect information
57 $schema->storage->connect_replicants(
58 [$dsn1, $user, $pass, \%opts],
59 [$dsn2, $user, $pass, \%opts],
60 [$dsn3, $user, $pass, \%opts],
63 ## Now, just use the $schema as normal
64 $schema->resultset('Source')->search({name=>'etc'});
66 ## You can force a given query to use a particular storage using the search
67 ### attribute 'force_pool'. For example:
69 my $RS = $schema->resultset('Source')->search(undef, {force_pool=>'master'});
71 ## Now $RS will force everything (both reads and writes) to use whatever was
72 ## setup as the master storage. 'master' is hardcoded to always point to the
73 ## Master, but you can also use any Replicant name. Please see:
74 ## L<DBIx::Class::Storage::Replicated::Pool> and the replicants attribute for
75 ## More. Also see transactions and L</execute_reliably> for alternative ways
76 ## to force read traffic to the master.
80 Warning: This class is marked BETA. This has been running a production
81 website using MySQL native replication as its backend and we have some decent
82 test coverage but the code hasn't yet been stressed by a variety of databases.
83 Individual DB's may have quirks we are not aware of. Please use this in first
84 development and pass along your experiences/bug fixes.
86 This class implements replicated data store for DBI. Currently you can define
87 one master and numerous slave database connections. All write-type queries
88 (INSERT, UPDATE, DELETE and even LAST_INSERT_ID) are routed to master
89 database, all read-type queries (SELECTs) go to the slave database.
91 Basically, any method request that L<DBIx::Class::Storage::DBI> would normally
92 handle gets delegated to one of the two attributes: L</read_handler> or to
93 L</write_handler>. Additionally, some methods need to be distributed
94 to all existing storages. This way our storage class is a drop in replacement
95 for L<DBIx::Class::Storage::DBI>.
97 Read traffic is spread across the replicants (slaves) occuring to a user
98 selected algorithm. The default algorithm is random weighted.
102 The consistancy betweeen master and replicants is database specific. The Pool
103 gives you a method to validate it's replicants, removing and replacing them
104 when they fail/pass predefined criteria. Please make careful use of the ways
105 to force a query to run against Master when needed.
109 Replicated Storage has additional requirements not currently part of L<DBIx::Class>
112 MooseX::AttributeHelpers => 0.12
113 MooseX::Types => 0.10
114 namespace::clean => 0.11
117 You will need to install these modules manually via CPAN or make them part of the
118 Makefile for your distribution.
122 This class defines the following attributes.
126 The underlying L<DBIx::Class::Schema> object this storage is attaching
132 isa=>'DBIx::Class::Schema',
139 Contains the classname which will instantiate the L</pool> object. Defaults
140 to: L<DBIx::Class::Storage::DBI::Replicated::Pool>.
147 default=>'DBIx::Class::Storage::DBI::Replicated::Pool',
149 'create_pool' => 'new',
155 Contains a hashref of initialized information to pass to the Balancer object.
156 See L<DBIx::Class::Storage::Replicated::Pool> for available arguments.
170 The replication pool requires a balance class to provider the methods for
171 choose how to spread the query load across each replicant in the pool.
175 has 'balancer_type' => (
177 isa=>BalancerClassNamePart,
180 default=> 'DBIx::Class::Storage::DBI::Replicated::Balancer::First',
182 'create_balancer' => 'new',
188 Contains a hashref of initialized information to pass to the Balancer object.
189 See L<DBIx::Class::Storage::Replicated::Balancer> for available arguments.
193 has 'balancer_args' => (
203 Is a <DBIx::Class::Storage::DBI::Replicated::Pool> or derived class. This is a
204 container class for one or more replicated databases.
210 isa=>'DBIx::Class::Storage::DBI::Replicated::Pool',
221 Is a <DBIx::Class::Storage::DBI::Replicated::Balancer> or derived class. This
222 is a class that takes a pool (<DBIx::Class::Storage::DBI::Replicated::Pool>)
228 isa=>'DBIx::Class::Storage::DBI::Replicated::Balancer',
230 handles=>[qw/auto_validate_every/],
235 The master defines the canonical state for a pool of connected databases. All
236 the replicants are expected to match this databases state. Thus, in a classic
237 Master / Slaves distributed system, all the slaves are expected to replicate
238 the Master's state as quick as possible. This is the only database in the
239 pool of databases that is allowed to handle write traffic.
245 isa=>'DBIx::Class::Storage::DBI',
249 =head1 ATTRIBUTES IMPLEMENTING THE DBIx::Storage::DBI INTERFACE
251 The following methods are delegated all the methods required for the
252 L<DBIx::Class::Storage::DBI> interface.
256 Defines an object that implements the read side of L<BIx::Class::Storage::DBI>.
260 has 'read_handler' => (
273 Defines an object that implements the write side of L<BIx::Class::Storage::DBI>.
277 has 'write_handler' => (
289 deployment_statements
305 with_deferred_fk_checks
313 has _master_connect_info_opts =>
314 (is => 'rw', isa => HashRef, default => sub { {} });
316 =head2 around: connect_info
318 Preserve master's C<connect_info> options (for merging with replicants.)
319 Also set any Replicated related options from connect_info, such as
320 C<pool_type>, C<pool_args>, C<balancer_type> and C<balancer_args>.
324 around connect_info => sub {
325 my ($next, $self, $info, @extra) = @_;
327 my $wantarray = wantarray;
330 for my $arg (@$info) {
331 next unless (reftype($arg)||'') eq 'HASH';
332 %opts = %{ merge($arg, \%opts) };
336 if (@opts{qw/pool_type pool_args/}) {
337 $self->pool_type(delete $opts{pool_type})
341 merge((delete $opts{pool_args} || {}), $self->pool_args)
344 $self->pool($self->_build_pool)
348 if (@opts{qw/balancer_type balancer_args/}) {
349 $self->balancer_type(delete $opts{balancer_type})
350 if $opts{balancer_type};
352 $self->balancer_args(
353 merge((delete $opts{balancer_args} || {}), $self->balancer_args)
356 $self->balancer($self->_build_balancer)
360 $self->_master_connect_info_opts(\%opts);
364 @res = $self->$next($info, @extra);
366 $res = $self->$next($info, @extra);
369 # Make sure master is blessed into the correct class and apply role to it.
370 my $master = $self->master;
371 $master->_determine_driver;
372 Moose::Meta::Class->initialize(ref $master);
373 DBIx::Class::Storage::DBI::Replicated::WithDSN->meta->apply($master);
375 $wantarray ? @res : $res;
380 This class defines the following methods.
384 L<DBIx::Class::Schema> when instantiating it's storage passed itself as the
385 first argument. So we need to massage the arguments a bit so that all the
386 bits get put into the correct places.
391 my ($class, $schema, $storage_type_args, @args) = @_;
402 Lazy builder for the L</master> attribute.
408 my $master = DBIx::Class::Storage::DBI->new($self->schema);
414 Lazy builder for the L</pool> attribute.
420 $self->create_pool(%{$self->pool_args});
423 =head2 _build_balancer
425 Lazy builder for the L</balancer> attribute. This takes a Pool object so that
426 the balancer knows which pool it's balancing.
430 sub _build_balancer {
432 $self->create_balancer(
434 master=>$self->master,
435 %{$self->balancer_args},
439 =head2 _build_write_handler
441 Lazy builder for the L</write_handler> attribute. The default is to set this to
446 sub _build_write_handler {
447 return shift->master;
450 =head2 _build_read_handler
452 Lazy builder for the L</read_handler> attribute. The default is to set this to
457 sub _build_read_handler {
458 return shift->balancer;
461 =head2 around: connect_replicants
463 All calls to connect_replicants needs to have an existing $schema tacked onto
464 top of the args, since L<DBIx::Storage::DBI> needs it, and any C<connect_info>
465 options merged with the master, with replicant opts having higher priority.
469 around connect_replicants => sub {
470 my ($next, $self, @args) = @_;
473 $r = [ $r ] unless reftype $r eq 'ARRAY';
475 croak "coderef replicant connect_info not supported"
476 if ref $r->[0] && reftype $r->[0] eq 'CODE';
478 # any connect_info options?
480 $i++ while $i < @$r && (reftype($r->[$i])||'') ne 'HASH';
483 $r->[$i] = {} unless $r->[$i];
485 # merge if two hashes
486 my @hashes = @$r[$i .. $#{$r}];
488 croak "invalid connect_info options"
489 if (grep { reftype($_) eq 'HASH' } @hashes) != @hashes;
491 croak "too many hashrefs in connect_info"
494 my %opts = %{ merge(reverse @hashes) };
497 splice @$r, $i+1, ($#{$r} - $i), ();
500 %opts = %{ merge(\%opts, $self->_master_connect_info_opts) };
506 $self->$next($self->schema, @args);
511 Returns an array of of all the connected storage backends. The first element
512 in the returned array is the master, and the remainings are each of the
519 return grep {defined $_ && blessed $_} (
521 values %{ $self->replicants },
525 =head2 execute_reliably ($coderef, ?@args)
527 Given a coderef, saves the current state of the L</read_handler>, forces it to
528 use reliable storage (ie sets it to the master), executes a coderef and then
529 restores the original state.
535 $schema->resultset('User')->create({name=>$name});
536 my $user_rs = $schema->resultset('User')->find({name=>$name});
540 my $user_rs = $schema->storage->execute_reliably($reliably, 'John');
542 Use this when you must be certain of your database state, such as when you just
543 inserted something and need to get a resultset including it, etc.
547 sub execute_reliably {
548 my ($self, $coderef, @args) = @_;
550 unless( ref $coderef eq 'CODE') {
551 $self->throw_exception('Second argument must be a coderef');
554 ##Get copy of master storage
555 my $master = $self->master;
557 ##Get whatever the current read hander is
558 my $current = $self->read_handler;
560 ##Set the read handler to master
561 $self->read_handler($master);
563 ## do whatever the caller needs
565 my $want_array = wantarray;
569 @result = $coderef->(@args);
570 } elsif(defined $want_array) {
571 ($result[0]) = ($coderef->(@args));
577 ##Reset to the original state
578 $self->read_handler($current);
580 ##Exception testing has to come last, otherwise you might leave the
581 ##read_handler set to master.
584 $self->throw_exception("coderef returned an error: $@");
586 return $want_array ? @result : $result[0];
590 =head2 set_reliable_storage
592 Sets the current $schema to be 'reliable', that is all queries, both read and
593 write are sent to the master
597 sub set_reliable_storage {
599 my $schema = $self->schema;
600 my $write_handler = $self->schema->storage->write_handler;
602 $schema->storage->read_handler($write_handler);
605 =head2 set_balanced_storage
607 Sets the current $schema to be use the </balancer> for all reads, while all
608 writea are sent to the master only
612 sub set_balanced_storage {
614 my $schema = $self->schema;
615 my $write_handler = $self->schema->storage->balancer;
617 $schema->storage->read_handler($write_handler);
620 =head2 around: txn_do ($coderef)
622 Overload to the txn_do method, which is delegated to whatever the
623 L<write_handler> is set to. We overload this in order to wrap in inside a
624 L</execute_reliably> method.
628 around 'txn_do' => sub {
629 my($txn_do, $self, $coderef, @args) = @_;
630 $self->execute_reliably(sub {$self->$txn_do($coderef, @args)});
635 Check that the master and at least one of the replicants is connected.
642 $self->master->connected &&
643 $self->pool->connected_replicants;
646 =head2 ensure_connected
648 Make sure all the storages are connected.
652 sub ensure_connected {
654 foreach my $source ($self->all_storages) {
655 $source->ensure_connected(@_);
661 Set the limit_dialect for all existing storages
667 foreach my $source ($self->all_storages) {
668 $source->limit_dialect(@_);
670 return $self->master->quote_char;
675 Set the quote_char for all existing storages
681 foreach my $source ($self->all_storages) {
682 $source->quote_char(@_);
684 return $self->master->quote_char;
689 Set the name_sep for all existing storages
695 foreach my $source ($self->all_storages) {
696 $source->name_sep(@_);
698 return $self->master->name_sep;
703 Set the schema object for all existing storages
709 foreach my $source ($self->all_storages) {
710 $source->set_schema(@_);
716 set a debug flag across all storages
723 foreach my $source ($self->all_storages) {
727 return $self->master->debug;
732 set a debug object across all storages
739 foreach my $source ($self->all_storages) {
740 $source->debugobj(@_);
743 return $self->master->debugobj;
748 set a debugfh object across all storages
755 foreach my $source ($self->all_storages) {
756 $source->debugfh(@_);
759 return $self->master->debugfh;
764 set a debug callback across all storages
771 foreach my $source ($self->all_storages) {
772 $source->debugcb(@_);
775 return $self->master->debugcb;
780 disconnect everything
786 foreach my $source ($self->all_storages) {
787 $source->disconnect(@_);
793 set cursor class on all storages, or return master's
798 my ($self, $cursor_class) = @_;
801 $_->cursor_class($cursor_class) for $self->all_storages;
803 $self->master->cursor_class;
808 Due to the fact that replicants can lag behind a master, you must take care to
809 make sure you use one of the methods to force read queries to a master should
810 you need realtime data integrity. For example, if you insert a row, and then
811 immediately re-read it from the database (say, by doing $row->discard_changes)
812 or you insert a row and then immediately build a query that expects that row
813 to be an item, you should force the master to handle reads. Otherwise, due to
814 the lag, there is no certainty your data will be in the expected state.
816 For data integrity, all transactions automatically use the master storage for
817 all read and write queries. Using a transaction is the preferred and recommended
818 method to force the master to handle all read queries.
820 Otherwise, you can force a single query to use the master with the 'force_pool'
823 my $row = $resultset->search(undef, {force_pool=>'master'})->find($pk);
825 This attribute will safely be ignore by non replicated storages, so you can use
826 the same code for both types of systems.
828 Lastly, you can use the L</execute_reliably> method, which works very much like
831 For debugging, you can turn replication on/off with the methods L</set_reliable_storage>
832 and L</set_balanced_storage>, however this operates at a global level and is not
833 suitable if you have a shared Schema object being used by multiple processes,
834 such as on a web application server. You can get around this limitation by
835 using the Schema clone method.
837 my $new_schema = $schema->clone;
838 $new_schema->set_reliable_storage;
840 ## $new_schema will use only the Master storage for all reads/writes while
841 ## the $schema object will use replicated storage.
845 John Napiorkowski <john.napiorkowski@takkle.com>
847 Based on code originated by:
849 Norbert Csongrádi <bert@cpan.org>
850 Peter Siklósi <einon@einon.hu>
854 You may distribute this code under the same terms as Perl itself.
858 __PACKAGE__->meta->make_immutable;