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::Types' => '0.21',
12 'namespace::clean' => '0.11',
13 'Hash::Merge' => '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 qw/BalancerClassNamePart DBICSchema DBICStorageDBI/;
33 use MooseX::Types::Moose qw/ClassName HashRef Object/;
34 use Scalar::Util 'reftype';
35 use Hash::Merge 'merge';
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 You should set the 'storage_type attribute to a replicated type. You should
50 also define your arguments, such as which balancer you want and any arguments
51 that the Pool object should get.
53 my $schema = Schema::Class->clone;
54 $schema->storage_type( ['::DBI::Replicated', {balancer=>'::Random'}] );
55 $schema->connection(...);
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.
61 $schema->storage->connect_replicants(
62 [$dsn1, $user, $pass, \%opts],
63 [$dsn2, $user, $pass, \%opts],
64 [$dsn3, $user, $pass, \%opts],
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.
70 $schema->resultset('Source')->search({name=>'etc'});
72 You can force a given query to use a particular storage using the search
73 attribute 'force_pool'. For example:
75 my $RS = $schema->resultset('Source')->search(undef, {force_pool=>'master'});
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.
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.
87 See L<DBIx::Class::Storage::DBI::Replicated::Instructions> for more help and
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.
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.
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>.
109 Read traffic is spread across the replicants (slaves) occuring to a user
110 selected algorithm. The default algorithm is random weighted.
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.
121 Replicated Storage has additional requirements not currently part of L<DBIx::Class>
124 MooseX::Types => '0.21',
125 namespace::clean => '0.11',
126 Hash::Merge => '0.11'
128 You will need to install these modules manually via CPAN or make them part of the
129 Makefile for your distribution.
133 This class defines the following attributes.
137 The underlying L<DBIx::Class::Schema> object this storage is attaching
150 Contains the classname which will instantiate the L</pool> object. Defaults
151 to: L<DBIx::Class::Storage::DBI::Replicated::Pool>.
158 default=>'DBIx::Class::Storage::DBI::Replicated::Pool',
160 'create_pool' => 'new',
166 Contains a hashref of initialized information to pass to the Balancer object.
167 See L<DBIx::Class::Storage::DBI::Replicated::Pool> for available arguments.
181 The replication pool requires a balance class to provider the methods for
182 choose how to spread the query load across each replicant in the pool.
186 has 'balancer_type' => (
188 isa=>BalancerClassNamePart,
191 default=> 'DBIx::Class::Storage::DBI::Replicated::Balancer::First',
193 'create_balancer' => 'new',
199 Contains a hashref of initialized information to pass to the Balancer object.
200 See L<DBIx::Class::Storage::DBI::Replicated::Balancer> for available arguments.
204 has 'balancer_args' => (
214 Is a <DBIx::Class::Storage::DBI::Replicated::Pool> or derived class. This is a
215 container class for one or more replicated databases.
221 isa=>'DBIx::Class::Storage::DBI::Replicated::Pool',
232 Is a <DBIx::Class::Storage::DBI::Replicated::Balancer> or derived class. This
233 is a class that takes a pool (<DBIx::Class::Storage::DBI::Replicated::Pool>)
239 isa=>'DBIx::Class::Storage::DBI::Replicated::Balancer',
241 handles=>[qw/auto_validate_every/],
246 The master defines the canonical state for a pool of connected databases. All
247 the replicants are expected to match this databases state. Thus, in a classic
248 Master / Slaves distributed system, all the slaves are expected to replicate
249 the Master's state as quick as possible. This is the only database in the
250 pool of databases that is allowed to handle write traffic.
260 =head1 ATTRIBUTES IMPLEMENTING THE DBIx::Storage::DBI INTERFACE
262 The following methods are delegated all the methods required for the
263 L<DBIx::Class::Storage::DBI> interface.
267 Defines an object that implements the read side of L<BIx::Class::Storage::DBI>.
271 has 'read_handler' => (
284 Defines an object that implements the write side of L<BIx::Class::Storage::DBI>.
288 has 'write_handler' => (
300 deployment_statements
303 build_datetime_parser
317 with_deferred_fk_checks
320 with_deferred_fk_checks
334 has _master_connect_info_opts =>
335 (is => 'rw', isa => HashRef, default => sub { {} });
337 =head2 around: connect_info
339 Preserve master's C<connect_info> options (for merging with replicants.)
340 Also set any Replicated related options from connect_info, such as
341 C<pool_type>, C<pool_args>, C<balancer_type> and C<balancer_args>.
345 around connect_info => sub {
346 my ($next, $self, $info, @extra) = @_;
348 my $wantarray = wantarray;
351 for my $arg (@$info) {
352 next unless (reftype($arg)||'') eq 'HASH';
353 %opts = %{ merge($arg, \%opts) };
357 if (@opts{qw/pool_type pool_args/}) {
358 $self->pool_type(delete $opts{pool_type})
362 merge((delete $opts{pool_args} || {}), $self->pool_args)
365 $self->pool($self->_build_pool)
369 if (@opts{qw/balancer_type balancer_args/}) {
370 $self->balancer_type(delete $opts{balancer_type})
371 if $opts{balancer_type};
373 $self->balancer_args(
374 merge((delete $opts{balancer_args} || {}), $self->balancer_args)
377 $self->balancer($self->_build_balancer)
381 $self->_master_connect_info_opts(\%opts);
385 @res = $self->$next($info, @extra);
387 $res = $self->$next($info, @extra);
390 # Make sure master is blessed into the correct class and apply role to it.
391 my $master = $self->master;
392 $master->_determine_driver;
393 Moose::Meta::Class->initialize(ref $master);
395 DBIx::Class::Storage::DBI::Replicated::WithDSN->meta->apply($master);
397 # link pool back to master
398 $self->pool->master($master);
400 $wantarray ? @res : $res;
405 This class defines the following methods.
409 L<DBIx::Class::Schema> when instantiating its storage passed itself as the
410 first argument. So we need to massage the arguments a bit so that all the
411 bits get put into the correct places.
416 my ($class, $schema, $storage_type_args, @args) = @_;
427 Lazy builder for the L</master> attribute.
433 my $master = DBIx::Class::Storage::DBI->new($self->schema);
439 Lazy builder for the L</pool> attribute.
445 $self->create_pool(%{$self->pool_args});
448 =head2 _build_balancer
450 Lazy builder for the L</balancer> attribute. This takes a Pool object so that
451 the balancer knows which pool it's balancing.
455 sub _build_balancer {
457 $self->create_balancer(
459 master=>$self->master,
460 %{$self->balancer_args},
464 =head2 _build_write_handler
466 Lazy builder for the L</write_handler> attribute. The default is to set this to
471 sub _build_write_handler {
472 return shift->master;
475 =head2 _build_read_handler
477 Lazy builder for the L</read_handler> attribute. The default is to set this to
482 sub _build_read_handler {
483 return shift->balancer;
486 =head2 around: connect_replicants
488 All calls to connect_replicants needs to have an existing $schema tacked onto
489 top of the args, since L<DBIx::Storage::DBI> needs it, and any C<connect_info>
490 options merged with the master, with replicant opts having higher priority.
494 around connect_replicants => sub {
495 my ($next, $self, @args) = @_;
498 $r = [ $r ] unless reftype $r eq 'ARRAY';
500 $self->throw_exception('coderef replicant connect_info not supported')
501 if ref $r->[0] && reftype $r->[0] eq 'CODE';
503 # any connect_info options?
505 $i++ while $i < @$r && (reftype($r->[$i])||'') ne 'HASH';
508 $r->[$i] = {} unless $r->[$i];
510 # merge if two hashes
511 my @hashes = @$r[$i .. $#{$r}];
513 $self->throw_exception('invalid connect_info options')
514 if (grep { reftype($_) eq 'HASH' } @hashes) != @hashes;
516 $self->throw_exception('too many hashrefs in connect_info')
519 my %opts = %{ merge(reverse @hashes) };
522 splice @$r, $i+1, ($#{$r} - $i), ();
524 # make sure master/replicants opts don't clash
525 my %master_opts = %{ $self->_master_connect_info_opts };
526 if (exists $opts{dbh_maker}) {
527 delete @master_opts{qw/dsn user password/};
529 delete $master_opts{dbh_maker};
532 %opts = %{ merge(\%opts, \%master_opts) };
538 $self->$next($self->schema, @args);
543 Returns an array of of all the connected storage backends. The first element
544 in the returned array is the master, and the remainings are each of the
551 return grep {defined $_ && blessed $_} (
553 values %{ $self->replicants },
557 =head2 execute_reliably ($coderef, ?@args)
559 Given a coderef, saves the current state of the L</read_handler>, forces it to
560 use reliable storage (ie sets it to the master), executes a coderef and then
561 restores the original state.
567 $schema->resultset('User')->create({name=>$name});
568 my $user_rs = $schema->resultset('User')->find({name=>$name});
572 my $user_rs = $schema->storage->execute_reliably($reliably, 'John');
574 Use this when you must be certain of your database state, such as when you just
575 inserted something and need to get a resultset including it, etc.
579 sub execute_reliably {
580 my ($self, $coderef, @args) = @_;
582 unless( ref $coderef eq 'CODE') {
583 $self->throw_exception('Second argument must be a coderef');
586 ##Get copy of master storage
587 my $master = $self->master;
589 ##Get whatever the current read hander is
590 my $current = $self->read_handler;
592 ##Set the read handler to master
593 $self->read_handler($master);
595 ## do whatever the caller needs
597 my $want_array = wantarray;
601 @result = $coderef->(@args);
602 } elsif(defined $want_array) {
603 ($result[0]) = ($coderef->(@args));
609 ##Reset to the original state
610 $self->read_handler($current);
612 ##Exception testing has to come last, otherwise you might leave the
613 ##read_handler set to master.
616 $self->throw_exception("coderef returned an error: $@");
618 return $want_array ? @result : $result[0];
622 =head2 set_reliable_storage
624 Sets the current $schema to be 'reliable', that is all queries, both read and
625 write are sent to the master
629 sub set_reliable_storage {
631 my $schema = $self->schema;
632 my $write_handler = $self->schema->storage->write_handler;
634 $schema->storage->read_handler($write_handler);
637 =head2 set_balanced_storage
639 Sets the current $schema to be use the </balancer> for all reads, while all
640 writea are sent to the master only
644 sub set_balanced_storage {
646 my $schema = $self->schema;
647 my $balanced_handler = $self->schema->storage->balancer;
649 $schema->storage->read_handler($balanced_handler);
654 Check that the master and at least one of the replicants is connected.
661 $self->master->connected &&
662 $self->pool->connected_replicants;
665 =head2 ensure_connected
667 Make sure all the storages are connected.
671 sub ensure_connected {
673 foreach my $source ($self->all_storages) {
674 $source->ensure_connected(@_);
680 Set the limit_dialect for all existing storages
686 foreach my $source ($self->all_storages) {
687 $source->limit_dialect(@_);
689 return $self->master->quote_char;
694 Set the quote_char for all existing storages
700 foreach my $source ($self->all_storages) {
701 $source->quote_char(@_);
703 return $self->master->quote_char;
708 Set the name_sep for all existing storages
714 foreach my $source ($self->all_storages) {
715 $source->name_sep(@_);
717 return $self->master->name_sep;
722 Set the schema object for all existing storages
728 foreach my $source ($self->all_storages) {
729 $source->set_schema(@_);
735 set a debug flag across all storages
742 foreach my $source ($self->all_storages) {
746 return $self->master->debug;
757 return $self->master->debugobj(@_);
768 return $self->master->debugfh(@_);
779 return $self->master->debugcb(@_);
784 disconnect everything
790 foreach my $source ($self->all_storages) {
791 $source->disconnect(@_);
797 set cursor class on all storages, or return master's
802 my ($self, $cursor_class) = @_;
805 $_->cursor_class($cursor_class) for $self->all_storages;
807 $self->master->cursor_class;
812 Due to the fact that replicants can lag behind a master, you must take care to
813 make sure you use one of the methods to force read queries to a master should
814 you need realtime data integrity. For example, if you insert a row, and then
815 immediately re-read it from the database (say, by doing $row->discard_changes)
816 or you insert a row and then immediately build a query that expects that row
817 to be an item, you should force the master to handle reads. Otherwise, due to
818 the lag, there is no certainty your data will be in the expected state.
820 For data integrity, all transactions automatically use the master storage for
821 all read and write queries. Using a transaction is the preferred and recommended
822 method to force the master to handle all read queries.
824 Otherwise, you can force a single query to use the master with the 'force_pool'
827 my $row = $resultset->search(undef, {force_pool=>'master'})->find($pk);
829 This attribute will safely be ignore by non replicated storages, so you can use
830 the same code for both types of systems.
832 Lastly, you can use the L</execute_reliably> method, which works very much like
835 For debugging, you can turn replication on/off with the methods L</set_reliable_storage>
836 and L</set_balanced_storage>, however this operates at a global level and is not
837 suitable if you have a shared Schema object being used by multiple processes,
838 such as on a web application server. You can get around this limitation by
839 using the Schema clone method.
841 my $new_schema = $schema->clone;
842 $new_schema->set_reliable_storage;
844 ## $new_schema will use only the Master storage for all reads/writes while
845 ## the $schema object will use replicated storage.
849 John Napiorkowski <john.napiorkowski@takkle.com>
851 Based on code originated by:
853 Norbert Csongrádi <bert@cpan.org>
854 Peter Siklósi <einon@einon.hu>
858 You may distribute this code under the same terms as Perl itself.
862 __PACKAGE__->meta->make_immutable;