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")
28 use DBIx::Class::Storage::DBI;
29 use DBIx::Class::Storage::DBI::Replicated::Pool;
30 use DBIx::Class::Storage::DBI::Replicated::Balancer;
31 use DBIx::Class::Storage::DBI::Replicated::Types 'BalancerClassNamePart';
33 use namespace::clean -except => 'meta';
37 DBIx::Class::Storage::DBI::Replicated - BETA Replicated database support
41 The Following example shows how to change an existing $schema to a replicated
42 storage type, add some replicated (readonly) databases, and perform reporting
45 ## Change storage_type in your schema class
46 $schema->storage_type( ['::DBI::Replicated', {balancer=>'::Random'}] );
48 ## Add some slaves. Basically this is an array of arrayrefs, where each
49 ## arrayref is database connect information
51 $schema->storage->connect_replicants(
52 [$dsn1, $user, $pass, \%opts],
53 [$dsn2, $user, $pass, \%opts],
54 [$dsn3, $user, $pass, \%opts],
57 ## Now, just use the $schema as normal
58 $schema->resultset('Source')->search({name=>'etc'});
60 ## You can force a given query to use a particular storage using the search
61 ### attribute 'force_pool'. For example:
63 my $RS = $schema->resultset('Source')->search(undef, {force_pool=>'master'});
65 ## Now $RS will force everything (both reads and writes) to use whatever was
66 ## setup as the master storage. 'master' is hardcoded to always point to the
67 ## Master, but you can also use any Replicant name. Please see:
68 ## L<DBIx::Class::Storage::Replicated::Pool> and the replicants attribute for
69 ## More. Also see transactions and L</execute_reliably> for alternative ways
70 ## to force read traffic to the master.
74 Warning: This class is marked BETA. This has been running a production
75 website using MySQL native replication as its backend and we have some decent
76 test coverage but the code hasn't yet been stressed by a variety of databases.
77 Individual DB's may have quirks we are not aware of. Please use this in first
78 development and pass along your experiences/bug fixes.
80 This class implements replicated data store for DBI. Currently you can define
81 one master and numerous slave database connections. All write-type queries
82 (INSERT, UPDATE, DELETE and even LAST_INSERT_ID) are routed to master
83 database, all read-type queries (SELECTs) go to the slave database.
85 Basically, any method request that L<DBIx::Class::Storage::DBI> would normally
86 handle gets delegated to one of the two attributes: L</read_handler> or to
87 L</write_handler>. Additionally, some methods need to be distributed
88 to all existing storages. This way our storage class is a drop in replacement
89 for L<DBIx::Class::Storage::DBI>.
91 Read traffic is spread across the replicants (slaves) occuring to a user
92 selected algorithm. The default algorithm is random weighted.
96 The consistancy betweeen master and replicants is database specific. The Pool
97 gives you a method to validate it's replicants, removing and replacing them
98 when they fail/pass predefined criteria. Please make careful use of the ways
99 to force a query to run against Master when needed.
103 Replicated Storage has additional requirements not currently part of L<DBIx::Class>
106 MooseX::AttributeHelpers => 0.12
107 MooseX::Types => 0.10
108 namespace::clean => 0.11
110 You will need to install these modules manually via CPAN or make them part of the
111 Makefile for your distribution.
115 This class defines the following attributes.
119 The underlying L<DBIx::Class::Schema> object this storage is attaching
125 isa=>'DBIx::Class::Schema',
132 Contains the classname which will instantiate the L</pool> object. Defaults
133 to: L<DBIx::Class::Storage::DBI::Replicated::Pool>.
141 default=>'DBIx::Class::Storage::DBI::Replicated::Pool',
143 'create_pool' => 'new',
149 Contains a hashref of initialized information to pass to the Balancer object.
150 See L<DBIx::Class::Storage::Replicated::Pool> for available arguments.
165 The replication pool requires a balance class to provider the methods for
166 choose how to spread the query load across each replicant in the pool.
170 has 'balancer_type' => (
172 isa=>BalancerClassNamePart,
175 default=> 'DBIx::Class::Storage::DBI::Replicated::Balancer::First',
177 'create_balancer' => 'new',
183 Contains a hashref of initialized information to pass to the Balancer object.
184 See L<DBIx::Class::Storage::Replicated::Balancer> for available arguments.
188 has 'balancer_args' => (
198 Is a <DBIx::Class::Storage::DBI::Replicated::Pool> or derived class. This is a
199 container class for one or more replicated databases.
205 isa=>'DBIx::Class::Storage::DBI::Replicated::Pool',
216 Is a <DBIx::Class::Storage::DBI::Replicated::Balancer> or derived class. This
217 is a class that takes a pool (<DBIx::Class::Storage::DBI::Replicated::Pool>)
223 isa=>'DBIx::Class::Storage::DBI::Replicated::Balancer',
225 handles=>[qw/auto_validate_every/],
230 The master defines the canonical state for a pool of connected databases. All
231 the replicants are expected to match this databases state. Thus, in a classic
232 Master / Slaves distributed system, all the slaves are expected to replicate
233 the Master's state as quick as possible. This is the only database in the
234 pool of databases that is allowed to handle write traffic.
240 isa=>'DBIx::Class::Storage::DBI',
244 =head1 ATTRIBUTES IMPLEMENTING THE DBIx::Storage::DBI INTERFACE
246 The following methods are delegated all the methods required for the
247 L<DBIx::Class::Storage::DBI> interface.
251 Defines an object that implements the read side of L<BIx::Class::Storage::DBI>.
255 has 'read_handler' => (
268 Defines an object that implements the write side of L<BIx::Class::Storage::DBI>.
272 has 'write_handler' => (
285 deployment_statements
301 with_deferred_fk_checks
311 This class defines the following methods.
315 L<DBIx::Class::Schema> when instantiating it's storage passed itself as the
316 first argument. So we need to massage the arguments a bit so that all the
317 bits get put into the correct places.
322 my ($class, $schema, $storage_type_args, @args) = @_;
333 Lazy builder for the L</master> attribute.
339 DBIx::Class::Storage::DBI->new($self->schema);
344 Lazy builder for the L</pool> attribute.
350 $self->create_pool(%{$self->pool_args});
353 =head2 _build_balancer
355 Lazy builder for the L</balancer> attribute. This takes a Pool object so that
356 the balancer knows which pool it's balancing.
360 sub _build_balancer {
362 $self->create_balancer(
364 master=>$self->master,
365 %{$self->balancer_args},
369 =head2 _build_write_handler
371 Lazy builder for the L</write_handler> attribute. The default is to set this to
376 sub _build_write_handler {
377 return shift->master;
380 =head2 _build_read_handler
382 Lazy builder for the L</read_handler> attribute. The default is to set this to
387 sub _build_read_handler {
388 return shift->balancer;
391 =head2 around: connect_replicants
393 All calls to connect_replicants needs to have an existing $schema tacked onto
394 top of the args, since L<DBIx::Storage::DBI> needs it.
398 around 'connect_replicants' => sub {
399 my ($method, $self, @args) = @_;
400 $self->$method($self->schema, @args);
405 Returns an array of of all the connected storage backends. The first element
406 in the returned array is the master, and the remainings are each of the
413 return grep {defined $_ && blessed $_} (
419 =head2 execute_reliably ($coderef, ?@args)
421 Given a coderef, saves the current state of the L</read_handler>, forces it to
422 use reliable storage (ie sets it to the master), executes a coderef and then
423 restores the original state.
429 $schema->resultset('User')->create({name=>$name});
430 my $user_rs = $schema->resultset('User')->find({name=>$name});
434 my $user_rs = $schema->storage->execute_reliably($reliably, 'John');
436 Use this when you must be certain of your database state, such as when you just
437 inserted something and need to get a resultset including it, etc.
441 sub execute_reliably {
442 my ($self, $coderef, @args) = @_;
444 unless( ref $coderef eq 'CODE') {
445 $self->throw_exception('Second argument must be a coderef');
448 ##Get copy of master storage
449 my $master = $self->master;
451 ##Get whatever the current read hander is
452 my $current = $self->read_handler;
454 ##Set the read handler to master
455 $self->read_handler($master);
457 ## do whatever the caller needs
459 my $want_array = wantarray;
463 @result = $coderef->(@args);
464 } elsif(defined $want_array) {
465 ($result[0]) = ($coderef->(@args));
471 ##Reset to the original state
472 $self->read_handler($current);
474 ##Exception testing has to come last, otherwise you might leave the
475 ##read_handler set to master.
478 $self->throw_exception("coderef returned an error: $@");
480 return $want_array ? @result : $result[0];
484 =head2 set_reliable_storage
486 Sets the current $schema to be 'reliable', that is all queries, both read and
487 write are sent to the master
491 sub set_reliable_storage {
493 my $schema = $self->schema;
494 my $write_handler = $self->schema->storage->write_handler;
496 $schema->storage->read_handler($write_handler);
499 =head2 set_balanced_storage
501 Sets the current $schema to be use the </balancer> for all reads, while all
502 writea are sent to the master only
506 sub set_balanced_storage {
508 my $schema = $self->schema;
509 my $write_handler = $self->schema->storage->balancer;
511 $schema->storage->read_handler($write_handler);
514 =head2 around: txn_do ($coderef)
516 Overload to the txn_do method, which is delegated to whatever the
517 L<write_handler> is set to. We overload this in order to wrap in inside a
518 L</execute_reliably> method.
522 around 'txn_do' => sub {
523 my($txn_do, $self, $coderef, @args) = @_;
524 $self->execute_reliably(sub {$self->$txn_do($coderef, @args)});
529 Check that the master and at least one of the replicants is connected.
536 $self->master->connected &&
537 $self->pool->connected_replicants;
540 =head2 ensure_connected
542 Make sure all the storages are connected.
546 sub ensure_connected {
548 foreach my $source ($self->all_storages) {
549 $source->ensure_connected(@_);
555 Set the limit_dialect for all existing storages
561 foreach my $source ($self->all_storages) {
562 $source->limit_dialect(@_);
564 return $self->master->quote_char;
569 Set the quote_char for all existing storages
575 foreach my $source ($self->all_storages) {
576 $source->quote_char(@_);
578 return $self->master->quote_char;
583 Set the name_sep for all existing storages
589 foreach my $source ($self->all_storages) {
590 $source->name_sep(@_);
592 return $self->master->name_sep;
597 Set the schema object for all existing storages
603 foreach my $source ($self->all_storages) {
604 $source->set_schema(@_);
610 set a debug flag across all storages
617 foreach my $source ($self->all_storages) {
621 return $self->master->debug;
626 set a debug object across all storages
633 foreach my $source ($self->all_storages) {
634 $source->debugobj(@_);
637 return $self->master->debugobj;
642 set a debugfh object across all storages
649 foreach my $source ($self->all_storages) {
650 $source->debugfh(@_);
653 return $self->master->debugfh;
658 set a debug callback across all storages
665 foreach my $source ($self->all_storages) {
666 $source->debugcb(@_);
669 return $self->master->debugcb;
674 disconnect everything
680 foreach my $source ($self->all_storages) {
681 $source->disconnect(@_);
687 Due to the fact that replicants can lag behind a master, you must take care to
688 make sure you use one of the methods to force read queries to a master should
689 you need realtime data integrity. For example, if you insert a row, and then
690 immediately re-read it from the database (say, by doing $row->discard_changes)
691 or you insert a row and then immediately build a query that expects that row
692 to be an item, you should force the master to handle reads. Otherwise, due to
693 the lag, there is no certainty your data will be in the expected state.
695 For data integrity, all transactions automatically use the master storage for
696 all read and write queries. Using a transaction is the preferred and recommended
697 method to force the master to handle all read queries.
699 Otherwise, you can force a single query to use the master with the 'force_pool'
702 my $row = $resultset->search(undef, {force_pool=>'master'})->find($pk);
704 This attribute will safely be ignore by non replicated storages, so you can use
705 the same code for both types of systems.
707 Lastly, you can use the L</execute_reliably> method, which works very much like
710 For debugging, you can turn replication on/off with the methods L</set_reliable_storage>
711 and L</set_balanced_storage>, however this operates at a global level and is not
712 suitable if you have a shared Schema object being used by multiple processes,
713 such as on a web application server. You can get around this limitation by
714 using the Schema clone method.
716 my $new_schema = $schema->clone;
717 $new_schema->set_reliable_storage;
719 ## $new_schema will use only the Master storage for all reads/writes while
720 ## the $schema object will use replicated storage.
724 John Napiorkowski <john.napiorkowski@takkle.com>
726 Based on code originated by:
728 Norbert Csongrádi <bert@cpan.org>
729 Peter Siklósi <einon@einon.hu>
733 You may distribute this code under the same terms as Perl itself.
737 __PACKAGE__->meta->make_immutable;