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 Moose::Util::TypeConstraints => '0.54',
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;
34 DBIx::Class::Storage::DBI::Replicated - BETA Replicated database support
38 The Following example shows how to change an existing $schema to a replicated
39 storage type, add some replicated (readonly) databases, and perform reporting
42 ## Change storage_type in your schema class
43 $schema->storage_type( ['::DBI::Replicated', {balancer=>'::Random'}] );
45 ## Add some slaves. Basically this is an array of arrayrefs, where each
46 ## arrayref is database connect information
48 $schema->storage->connect_replicants(
49 [$dsn1, $user, $pass, \%opts],
50 [$dsn2, $user, $pass, \%opts],
51 [$dsn3, $user, $pass, \%opts],
54 ## Now, just use the $schema as normal
55 $schema->resultset('Source')->search({name=>'etc'});
57 ## You can force a given query to use a particular storage using the search
58 ### attribute 'force_pool'. For example:
60 my $RS = $schema->resultset('Source')->search(undef, {force_pool=>'master'});
62 ## Now $RS will force everything (both reads and writes) to use whatever was
63 ## setup as the master storage. 'master' is hardcoded to always point to the
64 ## Master, but you can also use any Replicant name. Please see:
65 ## L<DBIx::Class::Storage::Replicated::Pool> and the replicants attribute for
66 ## More. Also see transactions and L</execute_reliably> for alternative ways
67 ## to force read traffic to the master.
71 Warning: This class is marked BETA. This has been running a production
72 website using MySQL native replication as its backend and we have some decent
73 test coverage but the code hasn't yet been stressed by a variety of databases.
74 Individual DB's may have quirks we are not aware of. Please use this in first
75 development and pass along your experiences/bug fixes.
77 This class implements replicated data store for DBI. Currently you can define
78 one master and numerous slave database connections. All write-type queries
79 (INSERT, UPDATE, DELETE and even LAST_INSERT_ID) are routed to master
80 database, all read-type queries (SELECTs) go to the slave database.
82 Basically, any method request that L<DBIx::Class::Storage::DBI> would normally
83 handle gets delegated to one of the two attributes: L</read_handler> or to
84 L</write_handler>. Additionally, some methods need to be distributed
85 to all existing storages. This way our storage class is a drop in replacement
86 for L<DBIx::Class::Storage::DBI>.
88 Read traffic is spread across the replicants (slaves) occuring to a user
89 selected algorithm. The default algorithm is random weighted.
93 The consistancy betweeen master and replicants is database specific. The Pool
94 gives you a method to validate it's replicants, removing and replacing them
95 when they fail/pass predefined criteria. Please make careful use of the ways
96 to force a query to run against Master when needed.
100 Replicated Storage has additional requirements not currently part of L<DBIx::Class>
103 MooseX::AttributeHelpers => 0.12
104 Moose::Util::TypeConstraints => 0.54
107 You will need to install these modules manually via CPAN or make them part of the
108 Makefile for your distribution.
112 This class defines the following attributes.
116 The underlying L<DBIx::Class::Schema> object this storage is attaching
122 isa=>'DBIx::Class::Schema',
129 Contains the classname which will instantiate the L</pool> object. Defaults
130 to: L<DBIx::Class::Storage::DBI::Replicated::Pool>.
138 default=>'DBIx::Class::Storage::DBI::Replicated::Pool',
140 'create_pool' => 'new',
146 Contains a hashref of initialized information to pass to the Balancer object.
147 See L<DBIx::Class::Storage::Replicated::Pool> for available arguments.
162 The replication pool requires a balance class to provider the methods for
163 choose how to spread the query load across each replicant in the pool.
167 subtype 'DBIx::Class::Storage::DBI::Replicated::BalancerClassNamePart',
170 coerce 'DBIx::Class::Storage::DBI::Replicated::BalancerClassNamePart',
175 $type = 'DBIx::Class::Storage::DBI::Replicated::Balancer'.$type;
177 Class::MOP::load_class($type);
181 has 'balancer_type' => (
183 isa=>'DBIx::Class::Storage::DBI::Replicated::BalancerClassNamePart',
186 default=> 'DBIx::Class::Storage::DBI::Replicated::Balancer::First',
188 'create_balancer' => 'new',
194 Contains a hashref of initialized information to pass to the Balancer object.
195 See L<DBIx::Class::Storage::Replicated::Balancer> for available arguments.
199 has 'balancer_args' => (
209 Is a <DBIx::Class::Storage::DBI::Replicated::Pool> or derived class. This is a
210 container class for one or more replicated databases.
216 isa=>'DBIx::Class::Storage::DBI::Replicated::Pool',
227 Is a <DBIx::Class::Storage::DBI::Replicated::Balancer> or derived class. This
228 is a class that takes a pool (<DBIx::Class::Storage::DBI::Replicated::Pool>)
234 isa=>'DBIx::Class::Storage::DBI::Replicated::Balancer',
236 handles=>[qw/auto_validate_every/],
241 The master defines the canonical state for a pool of connected databases. All
242 the replicants are expected to match this databases state. Thus, in a classic
243 Master / Slaves distributed system, all the slaves are expected to replicate
244 the Master's state as quick as possible. This is the only database in the
245 pool of databases that is allowed to handle write traffic.
251 isa=>'DBIx::Class::Storage::DBI',
255 =head1 ATTRIBUTES IMPLEMENTING THE DBIx::Storage::DBI INTERFACE
257 The following methods are delegated all the methods required for the
258 L<DBIx::Class::Storage::DBI> interface.
262 Defines an object that implements the read side of L<BIx::Class::Storage::DBI>.
266 has 'read_handler' => (
279 Defines an object that implements the write side of L<BIx::Class::Storage::DBI>.
283 has 'write_handler' => (
296 deployment_statements
312 with_deferred_fk_checks
322 This class defines the following methods.
326 L<DBIx::Class::Schema> when instantiating it's storage passed itself as the
327 first argument. So we need to massage the arguments a bit so that all the
328 bits get put into the correct places.
333 my ($class, $schema, $storage_type_args, @args) = @_;
344 Lazy builder for the L</master> attribute.
350 DBIx::Class::Storage::DBI->new($self->schema);
355 Lazy builder for the L</pool> attribute.
361 $self->create_pool(%{$self->pool_args});
364 =head2 _build_balancer
366 Lazy builder for the L</balancer> attribute. This takes a Pool object so that
367 the balancer knows which pool it's balancing.
371 sub _build_balancer {
373 $self->create_balancer(
375 master=>$self->master,
376 %{$self->balancer_args},
380 =head2 _build_write_handler
382 Lazy builder for the L</write_handler> attribute. The default is to set this to
387 sub _build_write_handler {
388 return shift->master;
391 =head2 _build_read_handler
393 Lazy builder for the L</read_handler> attribute. The default is to set this to
398 sub _build_read_handler {
399 return shift->balancer;
402 =head2 around: connect_replicants
404 All calls to connect_replicants needs to have an existing $schema tacked onto
405 top of the args, since L<DBIx::Storage::DBI> needs it.
409 around 'connect_replicants' => sub {
410 my ($method, $self, @args) = @_;
411 $self->$method($self->schema, @args);
416 Returns an array of of all the connected storage backends. The first element
417 in the returned array is the master, and the remainings are each of the
424 return grep {defined $_ && blessed $_} (
430 =head2 execute_reliably ($coderef, ?@args)
432 Given a coderef, saves the current state of the L</read_handler>, forces it to
433 use reliable storage (ie sets it to the master), executes a coderef and then
434 restores the original state.
440 $schema->resultset('User')->create({name=>$name});
441 my $user_rs = $schema->resultset('User')->find({name=>$name});
445 my $user_rs = $schema->storage->execute_reliably($reliably, 'John');
447 Use this when you must be certain of your database state, such as when you just
448 inserted something and need to get a resultset including it, etc.
452 sub execute_reliably {
453 my ($self, $coderef, @args) = @_;
455 unless( ref $coderef eq 'CODE') {
456 $self->throw_exception('Second argument must be a coderef');
459 ##Get copy of master storage
460 my $master = $self->master;
462 ##Get whatever the current read hander is
463 my $current = $self->read_handler;
465 ##Set the read handler to master
466 $self->read_handler($master);
468 ## do whatever the caller needs
470 my $want_array = wantarray;
474 @result = $coderef->(@args);
475 } elsif(defined $want_array) {
476 ($result[0]) = ($coderef->(@args));
482 ##Reset to the original state
483 $self->read_handler($current);
485 ##Exception testing has to come last, otherwise you might leave the
486 ##read_handler set to master.
489 $self->throw_exception("coderef returned an error: $@");
491 return $want_array ? @result : $result[0];
495 =head2 set_reliable_storage
497 Sets the current $schema to be 'reliable', that is all queries, both read and
498 write are sent to the master
502 sub set_reliable_storage {
504 my $schema = $self->schema;
505 my $write_handler = $self->schema->storage->write_handler;
507 $schema->storage->read_handler($write_handler);
510 =head2 set_balanced_storage
512 Sets the current $schema to be use the </balancer> for all reads, while all
513 writea are sent to the master only
517 sub set_balanced_storage {
519 my $schema = $self->schema;
520 my $write_handler = $self->schema->storage->balancer;
522 $schema->storage->read_handler($write_handler);
525 =head2 around: txn_do ($coderef)
527 Overload to the txn_do method, which is delegated to whatever the
528 L<write_handler> is set to. We overload this in order to wrap in inside a
529 L</execute_reliably> method.
533 around 'txn_do' => sub {
534 my($txn_do, $self, $coderef, @args) = @_;
535 $self->execute_reliably(sub {$self->$txn_do($coderef, @args)});
540 Check that the master and at least one of the replicants is connected.
547 $self->master->connected &&
548 $self->pool->connected_replicants;
551 =head2 ensure_connected
553 Make sure all the storages are connected.
557 sub ensure_connected {
559 foreach my $source ($self->all_storages) {
560 $source->ensure_connected(@_);
566 Set the limit_dialect for all existing storages
572 foreach my $source ($self->all_storages) {
573 $source->limit_dialect(@_);
575 return $self->master->quote_char;
580 Set the quote_char for all existing storages
586 foreach my $source ($self->all_storages) {
587 $source->quote_char(@_);
589 return $self->master->quote_char;
594 Set the name_sep for all existing storages
600 foreach my $source ($self->all_storages) {
601 $source->name_sep(@_);
603 return $self->master->name_sep;
608 Set the schema object for all existing storages
614 foreach my $source ($self->all_storages) {
615 $source->set_schema(@_);
621 set a debug flag across all storages
628 foreach my $source ($self->all_storages) {
632 return $self->master->debug;
637 set a debug object across all storages
644 foreach my $source ($self->all_storages) {
645 $source->debugobj(@_);
648 return $self->master->debugobj;
653 set a debugfh object across all storages
660 foreach my $source ($self->all_storages) {
661 $source->debugfh(@_);
664 return $self->master->debugfh;
669 set a debug callback across all storages
676 foreach my $source ($self->all_storages) {
677 $source->debugcb(@_);
680 return $self->master->debugcb;
685 disconnect everything
691 foreach my $source ($self->all_storages) {
692 $source->disconnect(@_);
698 Due to the fact that replicants can lag behind a master, you must take care to
699 make sure you use one of the methods to force read queries to a master should
700 you need realtime data integrity. For example, if you insert a row, and then
701 immediately re-read it from the database (say, by doing $row->discard_changes)
702 or you insert a row and then immediately build a query that expects that row
703 to be an item, you should force the master to handle reads. Otherwise, due to
704 the lag, there is no certainty your data will be in the expected state.
706 For data integrity, all transactions automatically use the master storage for
707 all read and write queries. Using a transaction is the preferred and recommended
708 method to force the master to handle all read queries.
710 Otherwise, you can force a single query to use the master with the 'force_pool'
713 my $row = $resultset->search(undef, {force_pool=>'master'})->find($pk);
715 This attribute will safely be ignore by non replicated storages, so you can use
716 the same code for both types of systems.
718 Lastly, you can use the L</execute_reliably> method, which works very much like
721 For debugging, you can turn replication on/off with the methods L</set_reliable_storage>
722 and L</set_balanced_storage>, however this operates at a global level and is not
723 suitable if you have a shared Schema object being used by multiple processes,
724 such as on a web application server. You can get around this limitation by
725 using the Schema clone method.
727 my $new_schema = $schema->clone;
728 $new_schema->set_reliable_storage;
730 ## $new_schema will use only the Master storage for all reads/writes while
731 ## the $schema object will use replicated storage.
735 John Napiorkowski <john.napiorkowski@takkle.com>
737 Based on code originated by:
739 Norbert Csongrádi <bert@cpan.org>
740 Peter Siklósi <einon@einon.hu>
744 You may distribute this code under the same terms as Perl itself.
748 __PACKAGE__->meta->make_immutable;