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',
18 for my $module (keys %replication_required) {
19 eval "use $module $replication_required{$module}";
20 push @didnt_load, "$module $replication_required{$module}"
24 croak("@{[ join ', ', @didnt_load ]} are missing and are required for Replication")
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 'BalancerClassNamePart';
33 use MooseX::Types::Moose qw/ClassName HashRef Object/;
34 use Scalar::Util 'reftype';
35 use Carp::Clan qw/^DBIx::Class/;
37 use namespace::clean -except => 'meta';
41 DBIx::Class::Storage::DBI::Replicated - BETA Replicated database support
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
49 ## Change storage_type in your schema class
50 $schema->storage_type( ['::DBI::Replicated', {balancer=>'::Random'}] );
52 ## Add some slaves. Basically this is an array of arrayrefs, where each
53 ## arrayref is database connect information
55 $schema->storage->connect_replicants(
56 [$dsn1, $user, $pass, \%opts],
57 [$dsn2, $user, $pass, \%opts],
58 [$dsn3, $user, $pass, \%opts],
61 ## Now, just use the $schema as normal
62 $schema->resultset('Source')->search({name=>'etc'});
64 ## You can force a given query to use a particular storage using the search
65 ### attribute 'force_pool'. For example:
67 my $RS = $schema->resultset('Source')->search(undef, {force_pool=>'master'});
69 ## Now $RS will force everything (both reads and writes) to use whatever was
70 ## setup as the master storage. 'master' is hardcoded to always point to the
71 ## Master, but you can also use any Replicant name. Please see:
72 ## L<DBIx::Class::Storage::Replicated::Pool> and the replicants attribute for
73 ## More. Also see transactions and L</execute_reliably> for alternative ways
74 ## to force read traffic to the master.
78 Warning: This class is marked BETA. This has been running a production
79 website using MySQL native replication as its backend and we have some decent
80 test coverage but the code hasn't yet been stressed by a variety of databases.
81 Individual DB's may have quirks we are not aware of. Please use this in first
82 development and pass along your experiences/bug fixes.
84 This class implements replicated data store for DBI. Currently you can define
85 one master and numerous slave database connections. All write-type queries
86 (INSERT, UPDATE, DELETE and even LAST_INSERT_ID) are routed to master
87 database, all read-type queries (SELECTs) go to the slave database.
89 Basically, any method request that L<DBIx::Class::Storage::DBI> would normally
90 handle gets delegated to one of the two attributes: L</read_handler> or to
91 L</write_handler>. Additionally, some methods need to be distributed
92 to all existing storages. This way our storage class is a drop in replacement
93 for L<DBIx::Class::Storage::DBI>.
95 Read traffic is spread across the replicants (slaves) occuring to a user
96 selected algorithm. The default algorithm is random weighted.
100 The consistancy betweeen master and replicants is database specific. The Pool
101 gives you a method to validate it's replicants, removing and replacing them
102 when they fail/pass predefined criteria. Please make careful use of the ways
103 to force a query to run against Master when needed.
107 Replicated Storage has additional requirements not currently part of L<DBIx::Class>
110 MooseX::AttributeHelpers => 0.12
111 MooseX::Types => 0.10
112 namespace::clean => 0.11
114 You will need to install these modules manually via CPAN or make them part of the
115 Makefile for your distribution.
119 This class defines the following attributes.
123 The underlying L<DBIx::Class::Schema> object this storage is attaching
129 isa=>'DBIx::Class::Schema',
136 Contains the classname which will instantiate the L</pool> object. Defaults
137 to: L<DBIx::Class::Storage::DBI::Replicated::Pool>.
144 default=>'DBIx::Class::Storage::DBI::Replicated::Pool',
146 'create_pool' => 'new',
152 Contains a hashref of initialized information to pass to the Balancer object.
153 See L<DBIx::Class::Storage::Replicated::Pool> for available arguments.
167 The replication pool requires a balance class to provider the methods for
168 choose how to spread the query load across each replicant in the pool.
172 has 'balancer_type' => (
174 isa=>BalancerClassNamePart,
177 default=> 'DBIx::Class::Storage::DBI::Replicated::Balancer::First',
179 'create_balancer' => 'new',
185 Contains a hashref of initialized information to pass to the Balancer object.
186 See L<DBIx::Class::Storage::Replicated::Balancer> for available arguments.
190 has 'balancer_args' => (
200 Is a <DBIx::Class::Storage::DBI::Replicated::Pool> or derived class. This is a
201 container class for one or more replicated databases.
207 isa=>'DBIx::Class::Storage::DBI::Replicated::Pool',
218 Is a <DBIx::Class::Storage::DBI::Replicated::Balancer> or derived class. This
219 is a class that takes a pool (<DBIx::Class::Storage::DBI::Replicated::Pool>)
225 isa=>'DBIx::Class::Storage::DBI::Replicated::Balancer',
227 handles=>[qw/auto_validate_every/],
232 The master defines the canonical state for a pool of connected databases. All
233 the replicants are expected to match this databases state. Thus, in a classic
234 Master / Slaves distributed system, all the slaves are expected to replicate
235 the Master's state as quick as possible. This is the only database in the
236 pool of databases that is allowed to handle write traffic.
242 isa=>'DBIx::Class::Storage::DBI',
246 =head1 ATTRIBUTES IMPLEMENTING THE DBIx::Storage::DBI INTERFACE
248 The following methods are delegated all the methods required for the
249 L<DBIx::Class::Storage::DBI> interface.
253 Defines an object that implements the read side of L<BIx::Class::Storage::DBI>.
257 has 'read_handler' => (
270 Defines an object that implements the write side of L<BIx::Class::Storage::DBI>.
274 has 'write_handler' => (
287 deployment_statements
303 with_deferred_fk_checks
311 has _master_connect_info_opts =>
312 (is => 'rw', isa => HashRef, default => sub { {} });
314 =head2 around: connect_info
316 Preserve master's C<connect_info> options (for merging with replicants.)
317 Also set any Replicated related options from connect_info, such as
318 C<pool_type>, C<pool_args>, C<balancer_type> and C<balancer_args>.
322 around connect_info => sub {
323 my ($next, $self, $info, @extra) = @_;
326 for my $arg (@$info) {
327 next unless (reftype($arg)||'') eq 'HASH';
328 %opts = (%opts, %$arg);
332 if (@opts{qw/pool_type pool_args/}) {
333 $self->pool_type(delete $opts{pool_type})
337 %{ $self->pool_args },
338 %{ delete $opts{pool_args} || {} }
341 $self->pool($self->_build_pool);
344 if (@opts{qw/balancer_type balancer_args/}) {
345 $self->balancer_type(delete $opts{balancer_type})
346 if $opts{balancer_type};
348 $self->balancer_args({
349 %{ $self->balancer_args },
350 %{ delete $opts{balancer_args} || {} }
353 $self->balancer($self->_build_balancer);
356 $self->_master_connect_info_opts(\%opts);
358 $self->$next($info, @extra);
363 This class defines the following methods.
367 L<DBIx::Class::Schema> when instantiating it's storage passed itself as the
368 first argument. So we need to massage the arguments a bit so that all the
369 bits get put into the correct places.
374 my ($class, $schema, $storage_type_args, @args) = @_;
385 Lazy builder for the L</master> attribute.
391 DBIx::Class::Storage::DBI->new($self->schema);
396 Lazy builder for the L</pool> attribute.
402 $self->create_pool(%{$self->pool_args});
405 =head2 _build_balancer
407 Lazy builder for the L</balancer> attribute. This takes a Pool object so that
408 the balancer knows which pool it's balancing.
412 sub _build_balancer {
414 $self->create_balancer(
416 master=>$self->master,
417 %{$self->balancer_args},
421 =head2 _build_write_handler
423 Lazy builder for the L</write_handler> attribute. The default is to set this to
428 sub _build_write_handler {
429 return shift->master;
432 =head2 _build_read_handler
434 Lazy builder for the L</read_handler> attribute. The default is to set this to
439 sub _build_read_handler {
440 return shift->balancer;
443 =head2 around: connect_replicants
445 All calls to connect_replicants needs to have an existing $schema tacked onto
446 top of the args, since L<DBIx::Storage::DBI> needs it, and any C<connect_info>
447 options merged with the master, with replicant opts having higher priority.
451 around connect_replicants => sub {
452 my ($next, $self, @args) = @_;
455 $r = [ $r ] unless reftype $r eq 'ARRAY';
457 croak "coderef replicant connect_info not supported"
458 if ref $r->[0] && reftype $r->[0] eq 'CODE';
460 # any connect_info options?
462 $i++ while $i < @$r && (reftype($r->[$i])||'') ne 'HASH';
465 $r->[$i] = {} unless $r->[$i];
467 # merge if two hashes
468 my %opts = map %$_, @$r[$i .. $#{$r}];
469 splice @$r, $i+1, ($#{$r} - $i), ();
472 %opts = (%{ $self->_master_connect_info_opts }, %opts);
478 $self->$next($self->schema, @args);
483 Returns an array of of all the connected storage backends. The first element
484 in the returned array is the master, and the remainings are each of the
491 return grep {defined $_ && blessed $_} (
493 values %{ $self->replicants },
497 =head2 execute_reliably ($coderef, ?@args)
499 Given a coderef, saves the current state of the L</read_handler>, forces it to
500 use reliable storage (ie sets it to the master), executes a coderef and then
501 restores the original state.
507 $schema->resultset('User')->create({name=>$name});
508 my $user_rs = $schema->resultset('User')->find({name=>$name});
512 my $user_rs = $schema->storage->execute_reliably($reliably, 'John');
514 Use this when you must be certain of your database state, such as when you just
515 inserted something and need to get a resultset including it, etc.
519 sub execute_reliably {
520 my ($self, $coderef, @args) = @_;
522 unless( ref $coderef eq 'CODE') {
523 $self->throw_exception('Second argument must be a coderef');
526 ##Get copy of master storage
527 my $master = $self->master;
529 ##Get whatever the current read hander is
530 my $current = $self->read_handler;
532 ##Set the read handler to master
533 $self->read_handler($master);
535 ## do whatever the caller needs
537 my $want_array = wantarray;
541 @result = $coderef->(@args);
542 } elsif(defined $want_array) {
543 ($result[0]) = ($coderef->(@args));
549 ##Reset to the original state
550 $self->read_handler($current);
552 ##Exception testing has to come last, otherwise you might leave the
553 ##read_handler set to master.
556 $self->throw_exception("coderef returned an error: $@");
558 return $want_array ? @result : $result[0];
562 =head2 set_reliable_storage
564 Sets the current $schema to be 'reliable', that is all queries, both read and
565 write are sent to the master
569 sub set_reliable_storage {
571 my $schema = $self->schema;
572 my $write_handler = $self->schema->storage->write_handler;
574 $schema->storage->read_handler($write_handler);
577 =head2 set_balanced_storage
579 Sets the current $schema to be use the </balancer> for all reads, while all
580 writea are sent to the master only
584 sub set_balanced_storage {
586 my $schema = $self->schema;
587 my $write_handler = $self->schema->storage->balancer;
589 $schema->storage->read_handler($write_handler);
592 =head2 around: txn_do ($coderef)
594 Overload to the txn_do method, which is delegated to whatever the
595 L<write_handler> is set to. We overload this in order to wrap in inside a
596 L</execute_reliably> method.
600 around 'txn_do' => sub {
601 my($txn_do, $self, $coderef, @args) = @_;
602 $self->execute_reliably(sub {$self->$txn_do($coderef, @args)});
607 Check that the master and at least one of the replicants is connected.
614 $self->master->connected &&
615 $self->pool->connected_replicants;
618 =head2 ensure_connected
620 Make sure all the storages are connected.
624 sub ensure_connected {
626 foreach my $source ($self->all_storages) {
627 $source->ensure_connected(@_);
633 Set the limit_dialect for all existing storages
639 foreach my $source ($self->all_storages) {
640 $source->limit_dialect(@_);
642 return $self->master->quote_char;
647 Set the quote_char for all existing storages
653 foreach my $source ($self->all_storages) {
654 $source->quote_char(@_);
656 return $self->master->quote_char;
661 Set the name_sep for all existing storages
667 foreach my $source ($self->all_storages) {
668 $source->name_sep(@_);
670 return $self->master->name_sep;
675 Set the schema object for all existing storages
681 foreach my $source ($self->all_storages) {
682 $source->set_schema(@_);
688 set a debug flag across all storages
695 foreach my $source ($self->all_storages) {
699 return $self->master->debug;
704 set a debug object across all storages
711 foreach my $source ($self->all_storages) {
712 $source->debugobj(@_);
715 return $self->master->debugobj;
720 set a debugfh object across all storages
727 foreach my $source ($self->all_storages) {
728 $source->debugfh(@_);
731 return $self->master->debugfh;
736 set a debug callback across all storages
743 foreach my $source ($self->all_storages) {
744 $source->debugcb(@_);
747 return $self->master->debugcb;
752 disconnect everything
758 foreach my $source ($self->all_storages) {
759 $source->disconnect(@_);
765 set cursor class on all storages, or return master's
770 my ($self, $cursor_class) = @_;
773 $_->cursor_class($cursor_class) for $self->all_storages;
775 $self->master->cursor_class;
780 Due to the fact that replicants can lag behind a master, you must take care to
781 make sure you use one of the methods to force read queries to a master should
782 you need realtime data integrity. For example, if you insert a row, and then
783 immediately re-read it from the database (say, by doing $row->discard_changes)
784 or you insert a row and then immediately build a query that expects that row
785 to be an item, you should force the master to handle reads. Otherwise, due to
786 the lag, there is no certainty your data will be in the expected state.
788 For data integrity, all transactions automatically use the master storage for
789 all read and write queries. Using a transaction is the preferred and recommended
790 method to force the master to handle all read queries.
792 Otherwise, you can force a single query to use the master with the 'force_pool'
795 my $row = $resultset->search(undef, {force_pool=>'master'})->find($pk);
797 This attribute will safely be ignore by non replicated storages, so you can use
798 the same code for both types of systems.
800 Lastly, you can use the L</execute_reliably> method, which works very much like
803 For debugging, you can turn replication on/off with the methods L</set_reliable_storage>
804 and L</set_balanced_storage>, however this operates at a global level and is not
805 suitable if you have a shared Schema object being used by multiple processes,
806 such as on a web application server. You can get around this limitation by
807 using the Schema clone method.
809 my $new_schema = $schema->clone;
810 $new_schema->set_reliable_storage;
812 ## $new_schema will use only the Master storage for all reads/writes while
813 ## the $schema object will use replicated storage.
817 John Napiorkowski <john.napiorkowski@takkle.com>
819 Based on code originated by:
821 Norbert Csongrádi <bert@cpan.org>
822 Peter Siklósi <einon@einon.hu>
826 You may distribute this code under the same terms as Perl itself.
830 __PACKAGE__->meta->make_immutable;