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) = @_;
328 for my $arg (@$info) {
329 next unless (reftype($arg)||'') eq 'HASH';
330 %opts = %{ merge($arg, \%opts) };
334 if (@opts{qw/pool_type pool_args/}) {
335 $self->pool_type(delete $opts{pool_type})
339 merge((delete $opts{pool_args} || {}), $self->pool_args)
342 $self->pool($self->_build_pool)
346 if (@opts{qw/balancer_type balancer_args/}) {
347 $self->balancer_type(delete $opts{balancer_type})
348 if $opts{balancer_type};
350 $self->balancer_args(
351 merge((delete $opts{balancer_args} || {}), $self->balancer_args)
354 $self->balancer($self->_build_balancer)
358 $self->_master_connect_info_opts(\%opts);
360 $self->$next($info, @extra);
365 This class defines the following methods.
369 L<DBIx::Class::Schema> when instantiating it's storage passed itself as the
370 first argument. So we need to massage the arguments a bit so that all the
371 bits get put into the correct places.
376 my ($class, $schema, $storage_type_args, @args) = @_;
387 Lazy builder for the L</master> attribute.
393 my $master = DBIx::Class::Storage::DBI->new($self->schema);
394 DBIx::Class::Storage::DBI::Replicated::WithDSN->meta->apply($master);
400 Lazy builder for the L</pool> attribute.
406 $self->create_pool(%{$self->pool_args});
409 =head2 _build_balancer
411 Lazy builder for the L</balancer> attribute. This takes a Pool object so that
412 the balancer knows which pool it's balancing.
416 sub _build_balancer {
418 $self->create_balancer(
420 master=>$self->master,
421 %{$self->balancer_args},
425 =head2 _build_write_handler
427 Lazy builder for the L</write_handler> attribute. The default is to set this to
432 sub _build_write_handler {
433 return shift->master;
436 =head2 _build_read_handler
438 Lazy builder for the L</read_handler> attribute. The default is to set this to
443 sub _build_read_handler {
444 return shift->balancer;
447 =head2 around: connect_replicants
449 All calls to connect_replicants needs to have an existing $schema tacked onto
450 top of the args, since L<DBIx::Storage::DBI> needs it, and any C<connect_info>
451 options merged with the master, with replicant opts having higher priority.
455 around connect_replicants => sub {
456 my ($next, $self, @args) = @_;
459 $r = [ $r ] unless reftype $r eq 'ARRAY';
461 croak "coderef replicant connect_info not supported"
462 if ref $r->[0] && reftype $r->[0] eq 'CODE';
464 # any connect_info options?
466 $i++ while $i < @$r && (reftype($r->[$i])||'') ne 'HASH';
469 $r->[$i] = {} unless $r->[$i];
471 # merge if two hashes
472 my @hashes = @$r[$i .. $#{$r}];
474 croak "invalid connect_info options"
475 if (grep { reftype($_) eq 'HASH' } @hashes) != @hashes;
477 croak "too many hashrefs in connect_info"
480 my %opts = %{ merge(reverse @hashes) };
483 splice @$r, $i+1, ($#{$r} - $i), ();
486 %opts = %{ merge(\%opts, $self->_master_connect_info_opts) };
492 $self->$next($self->schema, @args);
497 Returns an array of of all the connected storage backends. The first element
498 in the returned array is the master, and the remainings are each of the
505 return grep {defined $_ && blessed $_} (
507 values %{ $self->replicants },
511 =head2 execute_reliably ($coderef, ?@args)
513 Given a coderef, saves the current state of the L</read_handler>, forces it to
514 use reliable storage (ie sets it to the master), executes a coderef and then
515 restores the original state.
521 $schema->resultset('User')->create({name=>$name});
522 my $user_rs = $schema->resultset('User')->find({name=>$name});
526 my $user_rs = $schema->storage->execute_reliably($reliably, 'John');
528 Use this when you must be certain of your database state, such as when you just
529 inserted something and need to get a resultset including it, etc.
533 sub execute_reliably {
534 my ($self, $coderef, @args) = @_;
536 unless( ref $coderef eq 'CODE') {
537 $self->throw_exception('Second argument must be a coderef');
540 ##Get copy of master storage
541 my $master = $self->master;
543 ##Get whatever the current read hander is
544 my $current = $self->read_handler;
546 ##Set the read handler to master
547 $self->read_handler($master);
549 ## do whatever the caller needs
551 my $want_array = wantarray;
555 @result = $coderef->(@args);
556 } elsif(defined $want_array) {
557 ($result[0]) = ($coderef->(@args));
563 ##Reset to the original state
564 $self->read_handler($current);
566 ##Exception testing has to come last, otherwise you might leave the
567 ##read_handler set to master.
570 $self->throw_exception("coderef returned an error: $@");
572 return $want_array ? @result : $result[0];
576 =head2 set_reliable_storage
578 Sets the current $schema to be 'reliable', that is all queries, both read and
579 write are sent to the master
583 sub set_reliable_storage {
585 my $schema = $self->schema;
586 my $write_handler = $self->schema->storage->write_handler;
588 $schema->storage->read_handler($write_handler);
591 =head2 set_balanced_storage
593 Sets the current $schema to be use the </balancer> for all reads, while all
594 writea are sent to the master only
598 sub set_balanced_storage {
600 my $schema = $self->schema;
601 my $write_handler = $self->schema->storage->balancer;
603 $schema->storage->read_handler($write_handler);
606 =head2 around: txn_do ($coderef)
608 Overload to the txn_do method, which is delegated to whatever the
609 L<write_handler> is set to. We overload this in order to wrap in inside a
610 L</execute_reliably> method.
614 around 'txn_do' => sub {
615 my($txn_do, $self, $coderef, @args) = @_;
616 $self->execute_reliably(sub {$self->$txn_do($coderef, @args)});
621 Check that the master and at least one of the replicants is connected.
628 $self->master->connected &&
629 $self->pool->connected_replicants;
632 =head2 ensure_connected
634 Make sure all the storages are connected.
638 sub ensure_connected {
640 foreach my $source ($self->all_storages) {
641 $source->ensure_connected(@_);
647 Set the limit_dialect for all existing storages
653 foreach my $source ($self->all_storages) {
654 $source->limit_dialect(@_);
656 return $self->master->quote_char;
661 Set the quote_char for all existing storages
667 foreach my $source ($self->all_storages) {
668 $source->quote_char(@_);
670 return $self->master->quote_char;
675 Set the name_sep for all existing storages
681 foreach my $source ($self->all_storages) {
682 $source->name_sep(@_);
684 return $self->master->name_sep;
689 Set the schema object for all existing storages
695 foreach my $source ($self->all_storages) {
696 $source->set_schema(@_);
702 set a debug flag across all storages
709 foreach my $source ($self->all_storages) {
713 return $self->master->debug;
718 set a debug object across all storages
725 foreach my $source ($self->all_storages) {
726 $source->debugobj(@_);
729 return $self->master->debugobj;
734 set a debugfh object across all storages
741 foreach my $source ($self->all_storages) {
742 $source->debugfh(@_);
745 return $self->master->debugfh;
750 set a debug callback across all storages
757 foreach my $source ($self->all_storages) {
758 $source->debugcb(@_);
761 return $self->master->debugcb;
766 disconnect everything
772 foreach my $source ($self->all_storages) {
773 $source->disconnect(@_);
779 set cursor class on all storages, or return master's
784 my ($self, $cursor_class) = @_;
787 $_->cursor_class($cursor_class) for $self->all_storages;
789 $self->master->cursor_class;
794 Due to the fact that replicants can lag behind a master, you must take care to
795 make sure you use one of the methods to force read queries to a master should
796 you need realtime data integrity. For example, if you insert a row, and then
797 immediately re-read it from the database (say, by doing $row->discard_changes)
798 or you insert a row and then immediately build a query that expects that row
799 to be an item, you should force the master to handle reads. Otherwise, due to
800 the lag, there is no certainty your data will be in the expected state.
802 For data integrity, all transactions automatically use the master storage for
803 all read and write queries. Using a transaction is the preferred and recommended
804 method to force the master to handle all read queries.
806 Otherwise, you can force a single query to use the master with the 'force_pool'
809 my $row = $resultset->search(undef, {force_pool=>'master'})->find($pk);
811 This attribute will safely be ignore by non replicated storages, so you can use
812 the same code for both types of systems.
814 Lastly, you can use the L</execute_reliably> method, which works very much like
817 For debugging, you can turn replication on/off with the methods L</set_reliable_storage>
818 and L</set_balanced_storage>, however this operates at a global level and is not
819 suitable if you have a shared Schema object being used by multiple processes,
820 such as on a web application server. You can get around this limitation by
821 using the Schema clone method.
823 my $new_schema = $schema->clone;
824 $new_schema->set_reliable_storage;
826 ## $new_schema will use only the Master storage for all reads/writes while
827 ## the $schema object will use replicated storage.
831 John Napiorkowski <john.napiorkowski@takkle.com>
833 Based on code originated by:
835 Norbert Csongrádi <bert@cpan.org>
836 Peter Siklósi <einon@einon.hu>
840 You may distribute this code under the same terms as Perl itself.
844 __PACKAGE__->meta->make_immutable;