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',
14 'Hash::Merge' => '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
292 build_datetime_parser
306 with_deferred_fk_checks
309 with_deferred_fk_checks
323 has _master_connect_info_opts =>
324 (is => 'rw', isa => HashRef, default => sub { {} });
326 =head2 around: connect_info
328 Preserve master's C<connect_info> options (for merging with replicants.)
329 Also set any Replicated related options from connect_info, such as
330 C<pool_type>, C<pool_args>, C<balancer_type> and C<balancer_args>.
334 around connect_info => sub {
335 my ($next, $self, $info, @extra) = @_;
337 my $wantarray = wantarray;
340 for my $arg (@$info) {
341 next unless (reftype($arg)||'') eq 'HASH';
342 %opts = %{ merge($arg, \%opts) };
346 if (@opts{qw/pool_type pool_args/}) {
347 $self->pool_type(delete $opts{pool_type})
351 merge((delete $opts{pool_args} || {}), $self->pool_args)
354 $self->pool($self->_build_pool)
358 if (@opts{qw/balancer_type balancer_args/}) {
359 $self->balancer_type(delete $opts{balancer_type})
360 if $opts{balancer_type};
362 $self->balancer_args(
363 merge((delete $opts{balancer_args} || {}), $self->balancer_args)
366 $self->balancer($self->_build_balancer)
370 $self->_master_connect_info_opts(\%opts);
374 @res = $self->$next($info, @extra);
376 $res = $self->$next($info, @extra);
379 # Make sure master is blessed into the correct class and apply role to it.
380 my $master = $self->master;
381 $master->_determine_driver;
382 Moose::Meta::Class->initialize(ref $master);
383 DBIx::Class::Storage::DBI::Replicated::WithDSN->meta->apply($master);
385 $wantarray ? @res : $res;
390 This class defines the following methods.
394 L<DBIx::Class::Schema> when instantiating it's storage passed itself as the
395 first argument. So we need to massage the arguments a bit so that all the
396 bits get put into the correct places.
401 my ($class, $schema, $storage_type_args, @args) = @_;
412 Lazy builder for the L</master> attribute.
418 my $master = DBIx::Class::Storage::DBI->new($self->schema);
424 Lazy builder for the L</pool> attribute.
430 $self->create_pool(%{$self->pool_args});
433 =head2 _build_balancer
435 Lazy builder for the L</balancer> attribute. This takes a Pool object so that
436 the balancer knows which pool it's balancing.
440 sub _build_balancer {
442 $self->create_balancer(
444 master=>$self->master,
445 %{$self->balancer_args},
449 =head2 _build_write_handler
451 Lazy builder for the L</write_handler> attribute. The default is to set this to
456 sub _build_write_handler {
457 return shift->master;
460 =head2 _build_read_handler
462 Lazy builder for the L</read_handler> attribute. The default is to set this to
467 sub _build_read_handler {
468 return shift->balancer;
471 =head2 around: connect_replicants
473 All calls to connect_replicants needs to have an existing $schema tacked onto
474 top of the args, since L<DBIx::Storage::DBI> needs it, and any C<connect_info>
475 options merged with the master, with replicant opts having higher priority.
479 around connect_replicants => sub {
480 my ($next, $self, @args) = @_;
483 $r = [ $r ] unless reftype $r eq 'ARRAY';
485 croak "coderef replicant connect_info not supported"
486 if ref $r->[0] && reftype $r->[0] eq 'CODE';
488 # any connect_info options?
490 $i++ while $i < @$r && (reftype($r->[$i])||'') ne 'HASH';
493 $r->[$i] = {} unless $r->[$i];
495 # merge if two hashes
496 my @hashes = @$r[$i .. $#{$r}];
498 croak "invalid connect_info options"
499 if (grep { reftype($_) eq 'HASH' } @hashes) != @hashes;
501 croak "too many hashrefs in connect_info"
504 my %opts = %{ merge(reverse @hashes) };
507 splice @$r, $i+1, ($#{$r} - $i), ();
510 %opts = %{ merge(\%opts, $self->_master_connect_info_opts) };
516 $self->$next($self->schema, @args);
521 Returns an array of of all the connected storage backends. The first element
522 in the returned array is the master, and the remainings are each of the
529 return grep {defined $_ && blessed $_} (
531 values %{ $self->replicants },
535 =head2 execute_reliably ($coderef, ?@args)
537 Given a coderef, saves the current state of the L</read_handler>, forces it to
538 use reliable storage (ie sets it to the master), executes a coderef and then
539 restores the original state.
545 $schema->resultset('User')->create({name=>$name});
546 my $user_rs = $schema->resultset('User')->find({name=>$name});
550 my $user_rs = $schema->storage->execute_reliably($reliably, 'John');
552 Use this when you must be certain of your database state, such as when you just
553 inserted something and need to get a resultset including it, etc.
557 sub execute_reliably {
558 my ($self, $coderef, @args) = @_;
560 unless( ref $coderef eq 'CODE') {
561 $self->throw_exception('Second argument must be a coderef');
564 ##Get copy of master storage
565 my $master = $self->master;
567 ##Get whatever the current read hander is
568 my $current = $self->read_handler;
570 ##Set the read handler to master
571 $self->read_handler($master);
573 ## do whatever the caller needs
575 my $want_array = wantarray;
579 @result = $coderef->(@args);
580 } elsif(defined $want_array) {
581 ($result[0]) = ($coderef->(@args));
587 ##Reset to the original state
588 $self->read_handler($current);
590 ##Exception testing has to come last, otherwise you might leave the
591 ##read_handler set to master.
594 $self->throw_exception("coderef returned an error: $@");
596 return $want_array ? @result : $result[0];
600 =head2 set_reliable_storage
602 Sets the current $schema to be 'reliable', that is all queries, both read and
603 write are sent to the master
607 sub set_reliable_storage {
609 my $schema = $self->schema;
610 my $write_handler = $self->schema->storage->write_handler;
612 $schema->storage->read_handler($write_handler);
615 =head2 set_balanced_storage
617 Sets the current $schema to be use the </balancer> for all reads, while all
618 writea are sent to the master only
622 sub set_balanced_storage {
624 my $schema = $self->schema;
625 my $balanced_handler = $self->schema->storage->balancer;
627 $schema->storage->read_handler($balanced_handler);
632 Check that the master and at least one of the replicants is connected.
639 $self->master->connected &&
640 $self->pool->connected_replicants;
643 =head2 ensure_connected
645 Make sure all the storages are connected.
649 sub ensure_connected {
651 foreach my $source ($self->all_storages) {
652 $source->ensure_connected(@_);
658 Set the limit_dialect for all existing storages
664 foreach my $source ($self->all_storages) {
665 $source->limit_dialect(@_);
667 return $self->master->quote_char;
672 Set the quote_char for all existing storages
678 foreach my $source ($self->all_storages) {
679 $source->quote_char(@_);
681 return $self->master->quote_char;
686 Set the name_sep for all existing storages
692 foreach my $source ($self->all_storages) {
693 $source->name_sep(@_);
695 return $self->master->name_sep;
700 Set the schema object for all existing storages
706 foreach my $source ($self->all_storages) {
707 $source->set_schema(@_);
713 set a debug flag across all storages
720 foreach my $source ($self->all_storages) {
724 return $self->master->debug;
729 set a debug object across all storages
736 foreach my $source ($self->all_storages) {
737 $source->debugobj(@_);
740 return $self->master->debugobj;
745 set a debugfh object across all storages
752 foreach my $source ($self->all_storages) {
753 $source->debugfh(@_);
756 return $self->master->debugfh;
761 set a debug callback across all storages
768 foreach my $source ($self->all_storages) {
769 $source->debugcb(@_);
772 return $self->master->debugcb;
777 disconnect everything
783 foreach my $source ($self->all_storages) {
784 $source->disconnect(@_);
790 set cursor class on all storages, or return master's
795 my ($self, $cursor_class) = @_;
798 $_->cursor_class($cursor_class) for $self->all_storages;
800 $self->master->cursor_class;
805 Due to the fact that replicants can lag behind a master, you must take care to
806 make sure you use one of the methods to force read queries to a master should
807 you need realtime data integrity. For example, if you insert a row, and then
808 immediately re-read it from the database (say, by doing $row->discard_changes)
809 or you insert a row and then immediately build a query that expects that row
810 to be an item, you should force the master to handle reads. Otherwise, due to
811 the lag, there is no certainty your data will be in the expected state.
813 For data integrity, all transactions automatically use the master storage for
814 all read and write queries. Using a transaction is the preferred and recommended
815 method to force the master to handle all read queries.
817 Otherwise, you can force a single query to use the master with the 'force_pool'
820 my $row = $resultset->search(undef, {force_pool=>'master'})->find($pk);
822 This attribute will safely be ignore by non replicated storages, so you can use
823 the same code for both types of systems.
825 Lastly, you can use the L</execute_reliably> method, which works very much like
828 For debugging, you can turn replication on/off with the methods L</set_reliable_storage>
829 and L</set_balanced_storage>, however this operates at a global level and is not
830 suitable if you have a shared Schema object being used by multiple processes,
831 such as on a web application server. You can get around this limitation by
832 using the Schema clone method.
834 my $new_schema = $schema->clone;
835 $new_schema->set_reliable_storage;
837 ## $new_schema will use only the Master storage for all reads/writes while
838 ## the $schema object will use replicated storage.
842 John Napiorkowski <john.napiorkowski@takkle.com>
844 Based on code originated by:
846 Norbert Csongrádi <bert@cpan.org>
847 Peter Siklósi <einon@einon.hu>
851 You may distribute this code under the same terms as Perl itself.
855 __PACKAGE__->meta->make_immutable;