1 package DBIx::Class::Storage::DBI::Replicated;
5 die('The following modules are required for Replication ' . DBIx::Class::Optional::Dependencies->req_missing_for ('replicated') . "\n" )
6 unless DBIx::Class::Optional::Dependencies->req_ok_for ('replicated');
10 use DBIx::Class::Storage::DBI;
11 use DBIx::Class::Storage::DBI::Replicated::Pool;
12 use DBIx::Class::Storage::DBI::Replicated::Balancer;
13 use DBIx::Class::Storage::DBI::Replicated::Types qw/BalancerClassNamePart DBICSchema DBICStorageDBI/;
14 use MooseX::Types::Moose qw/ClassName HashRef Object/;
15 use Scalar::Util 'reftype';
17 use List::Util qw/min max reduce/;
18 use Context::Preserve 'preserve_context';
21 use namespace::clean -except => 'meta';
25 DBIx::Class::Storage::DBI::Replicated - BETA Replicated database support
29 The Following example shows how to change an existing $schema to a replicated
30 storage type, add some replicated (read-only) databases, and perform reporting
33 You should set the 'storage_type attribute to a replicated type. You should
34 also define your arguments, such as which balancer you want and any arguments
35 that the Pool object should get.
37 my $schema = Schema::Class->clone;
38 $schema->storage_type( ['::DBI::Replicated', {balancer=>'::Random'}] );
39 $schema->connection(...);
41 Next, you need to add in the Replicants. Basically this is an array of
42 arrayrefs, where each arrayref is database connect information. Think of these
43 arguments as what you'd pass to the 'normal' $schema->connect method.
45 $schema->storage->connect_replicants(
46 [$dsn1, $user, $pass, \%opts],
47 [$dsn2, $user, $pass, \%opts],
48 [$dsn3, $user, $pass, \%opts],
51 Now, just use the $schema as you normally would. Automatically all reads will
52 be delegated to the replicants, while writes to the master.
54 $schema->resultset('Source')->search({name=>'etc'});
56 You can force a given query to use a particular storage using the search
57 attribute 'force_pool'. For example:
59 my $rs = $schema->resultset('Source')->search(undef, {force_pool=>'master'});
61 Now $rs will force everything (both reads and writes) to use whatever was setup
62 as the master storage. 'master' is hardcoded to always point to the Master,
63 but you can also use any Replicant name. Please see:
64 L<DBIx::Class::Storage::DBI::Replicated::Pool> and the replicants attribute for more.
66 Also see transactions and L</execute_reliably> for alternative ways to
67 force read traffic to the master. In general, you should wrap your statements
68 in a transaction when you are reading and writing to the same tables at the
69 same time, since your replicants will often lag a bit behind the master.
71 If you have a multi-statement read only transaction you can force it to select
72 a random server in the pool by:
74 my $rs = $schema->resultset('Source')->search( undef,
75 { force_pool => $db->storage->read_handler->next_storage }
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 DBs 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) occurring to a user
98 selected algorithm. The default algorithm is random weighted.
102 The consistency between master and replicants is database specific. The Pool
103 gives you a method to validate its 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
110 L<DBIx::Class>. See L<DBIx::Class::Optional::Dependencies> for more details.
114 This class defines the following attributes.
118 The underlying L<DBIx::Class::Schema> object this storage is attaching
131 Contains the classname which will instantiate the L</pool> object. Defaults
132 to: L<DBIx::Class::Storage::DBI::Replicated::Pool>.
139 default=>'DBIx::Class::Storage::DBI::Replicated::Pool',
141 'create_pool' => 'new',
147 Contains a hashref of initialized information to pass to the Balancer object.
148 See L<DBIx::Class::Storage::DBI::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 has 'balancer_type' => (
169 isa=>BalancerClassNamePart,
172 default=> 'DBIx::Class::Storage::DBI::Replicated::Balancer::First',
174 'create_balancer' => 'new',
180 Contains a hashref of initialized information to pass to the Balancer object.
181 See L<DBIx::Class::Storage::DBI::Replicated::Balancer> for available arguments.
185 has 'balancer_args' => (
195 Is a L<DBIx::Class::Storage::DBI::Replicated::Pool> or derived class. This is a
196 container class for one or more replicated databases.
202 isa=>'DBIx::Class::Storage::DBI::Replicated::Pool',
213 Is a L<DBIx::Class::Storage::DBI::Replicated::Balancer> or derived class. This
214 is a class that takes a pool (L<DBIx::Class::Storage::DBI::Replicated::Pool>)
220 isa=>'DBIx::Class::Storage::DBI::Replicated::Balancer',
222 handles=>[qw/auto_validate_every/],
227 The master defines the canonical state for a pool of connected databases. All
228 the replicants are expected to match this databases state. Thus, in a classic
229 Master / Slaves distributed system, all the slaves are expected to replicate
230 the Master's state as quick as possible. This is the only database in the
231 pool of databases that is allowed to handle write traffic.
241 =head1 ATTRIBUTES IMPLEMENTING THE DBIx::Storage::DBI INTERFACE
243 The following methods are delegated all the methods required for the
244 L<DBIx::Class::Storage::DBI> interface.
248 my $method_dispatch = {
260 deployment_statements
263 build_datetime_parser
279 with_deferred_fk_checks
287 relname_to_table_alias
289 _default_dbi_connect_attributes
291 _dbic_connect_attributes
297 bind_attribute_by_data_type
301 _dbh_execute_for_fetch
303 _dbh_execute_inserts_with_no_binds
304 _select_args_to_query
307 _normalize_connect_info
321 /, Class::MOP::Class->initialize('DBIx::Class::Storage::DBIHacks')->get_method_list ],
326 _dbh_columns_info_for
329 unimplemented => [qw/
330 _arm_global_destructor
333 source_bind_attributes
335 get_use_dbms_capability
336 set_use_dbms_capability
347 _perform_autoinc_retrieval
348 _autoinc_supplied_for_op
359 # the capability framework
360 # not sure if CMOP->initialize does evil things to DBIC::S::DBI, fix if a problem
362 { $_ =~ /^ _ (?: use | supports | determine_supports ) _ /x }
363 ( Class::MOP::Class->initialize('DBIx::Class::Storage::DBI')->get_all_method_names )
367 if (DBIx::Class::_ENV_::DBICTEST) {
370 for my $type (keys %$method_dispatch) {
371 for (@{$method_dispatch->{$type}}) {
372 push @{$seen->{$_}}, $type;
376 if (my @dupes = grep { @{$seen->{$_}} > 1 } keys %$seen) {
378 'The following methods show up multiple times in ::Storage::DBI::Replicated handlers:',
379 (map { "$_: " . (join ', ', @{$seen->{$_}}) } sort @dupes),
384 if (my @cant = grep { ! DBIx::Class::Storage::DBI->can($_) } keys %$seen) {
386 '::Storage::DBI::Replicated specifies handling of the following *NON EXISTING* ::Storage::DBI methods:',
393 for my $method (@{$method_dispatch->{unimplemented}}) {
394 __PACKAGE__->meta->add_method($method, sub {
396 $self->throw_exception("$method must not be called on ".(blessed $self).' objects');
402 Defines an object that implements the read side of L<BIx::Class::Storage::DBI>.
406 has 'read_handler' => (
410 handles=>$method_dispatch->{reader},
415 Defines an object that implements the write side of L<BIx::Class::Storage::DBI>,
416 as well as methods that don't write or read that can be called on only one
417 storage, methods that return a C<$dbh>, and any methods that don't make sense to
422 has 'write_handler' => (
426 handles=>$method_dispatch->{writer},
431 has _master_connect_info_opts =>
432 (is => 'rw', isa => HashRef, default => sub { {} });
434 =head2 around: connect_info
436 Preserves master's C<connect_info> options (for merging with replicants.)
437 Also sets any Replicated-related options from connect_info, such as
438 C<pool_type>, C<pool_args>, C<balancer_type> and C<balancer_args>.
442 around connect_info => sub {
443 my ($next, $self, $info, @extra) = @_;
445 my $merge = Hash::Merge->new('LEFT_PRECEDENT');
448 for my $arg (@$info) {
449 next unless (reftype($arg)||'') eq 'HASH';
450 %opts = %{ $merge->merge($arg, \%opts) };
454 if (@opts{qw/pool_type pool_args/}) {
455 $self->pool_type(delete $opts{pool_type})
459 $merge->merge((delete $opts{pool_args} || {}), $self->pool_args)
462 ## Since we possibly changed the pool_args, we need to clear the current
463 ## pool object so that next time it is used it will be rebuilt.
467 if (@opts{qw/balancer_type balancer_args/}) {
468 $self->balancer_type(delete $opts{balancer_type})
469 if $opts{balancer_type};
471 $self->balancer_args(
472 $merge->merge((delete $opts{balancer_args} || {}), $self->balancer_args)
475 $self->balancer($self->_build_balancer)
479 $self->_master_connect_info_opts(\%opts);
481 return preserve_context {
482 $self->$next($info, @extra);
484 # Make sure master is blessed into the correct class and apply role to it.
485 my $master = $self->master;
486 $master->_determine_driver;
487 Moose::Meta::Class->initialize(ref $master);
489 DBIx::Class::Storage::DBI::Replicated::WithDSN->meta->apply($master);
491 # link pool back to master
492 $self->pool->master($master);
498 This class defines the following methods.
502 L<DBIx::Class::Schema> when instantiating its storage passed itself as the
503 first argument. So we need to massage the arguments a bit so that all the
504 bits get put into the correct places.
509 my ($class, $schema, $storage_type_args, @args) = @_;
520 Lazy builder for the L</master> attribute.
526 my $master = DBIx::Class::Storage::DBI->new($self->schema);
532 Lazy builder for the L</pool> attribute.
538 $self->create_pool(%{$self->pool_args});
541 =head2 _build_balancer
543 Lazy builder for the L</balancer> attribute. This takes a Pool object so that
544 the balancer knows which pool it's balancing.
548 sub _build_balancer {
550 $self->create_balancer(
552 master=>$self->master,
553 %{$self->balancer_args},
557 =head2 _build_write_handler
559 Lazy builder for the L</write_handler> attribute. The default is to set this to
564 sub _build_write_handler {
565 return shift->master;
568 =head2 _build_read_handler
570 Lazy builder for the L</read_handler> attribute. The default is to set this to
575 sub _build_read_handler {
576 return shift->balancer;
579 =head2 around: connect_replicants
581 All calls to connect_replicants needs to have an existing $schema tacked onto
582 top of the args, since L<DBIx::Storage::DBI> needs it, and any C<connect_info>
583 options merged with the master, with replicant opts having higher priority.
587 around connect_replicants => sub {
588 my ($next, $self, @args) = @_;
591 $r = [ $r ] unless reftype $r eq 'ARRAY';
593 $self->throw_exception('coderef replicant connect_info not supported')
594 if ref $r->[0] && reftype $r->[0] eq 'CODE';
596 # any connect_info options?
598 $i++ while $i < @$r && (reftype($r->[$i])||'') ne 'HASH';
601 $r->[$i] = {} unless $r->[$i];
603 # merge if two hashes
604 my @hashes = @$r[$i .. $#{$r}];
606 $self->throw_exception('invalid connect_info options')
607 if (grep { reftype($_) eq 'HASH' } @hashes) != @hashes;
609 $self->throw_exception('too many hashrefs in connect_info')
612 my $merge = Hash::Merge->new('LEFT_PRECEDENT');
613 my %opts = %{ $merge->merge(reverse @hashes) };
616 splice @$r, $i+1, ($#{$r} - $i), ();
618 # make sure master/replicants opts don't clash
619 my %master_opts = %{ $self->_master_connect_info_opts };
620 if (exists $opts{dbh_maker}) {
621 delete @master_opts{qw/dsn user password/};
623 delete $master_opts{dbh_maker};
626 %opts = %{ $merge->merge(\%opts, \%master_opts) };
632 $self->$next($self->schema, @args);
637 Returns an array of of all the connected storage backends. The first element
638 in the returned array is the master, and the remainings are each of the
645 return grep {defined $_ && blessed $_} (
647 values %{ $self->replicants },
651 =head2 execute_reliably ($coderef, ?@args)
653 Given a coderef, saves the current state of the L</read_handler>, forces it to
654 use reliable storage (e.g. sets it to the master), executes a coderef and then
655 restores the original state.
661 $schema->resultset('User')->create({name=>$name});
662 my $user_rs = $schema->resultset('User')->find({name=>$name});
666 my $user_rs = $schema->storage->execute_reliably($reliably, 'John');
668 Use this when you must be certain of your database state, such as when you just
669 inserted something and need to get a resultset including it, etc.
673 sub execute_reliably {
677 unless( ref $coderef eq 'CODE') {
678 $self->throw_exception('Second argument must be a coderef');
681 ## replace the current read handler for the remainder of the scope
682 local $self->{read_handler} = $self->master;
688 $self->throw_exception("coderef returned an error: $_");
692 =head2 set_reliable_storage
694 Sets the current $schema to be 'reliable', that is all queries, both read and
695 write are sent to the master
699 sub set_reliable_storage {
701 my $schema = $self->schema;
702 my $write_handler = $self->schema->storage->write_handler;
704 $schema->storage->read_handler($write_handler);
707 =head2 set_balanced_storage
709 Sets the current $schema to be use the </balancer> for all reads, while all
710 writes are sent to the master only
714 sub set_balanced_storage {
716 my $schema = $self->schema;
717 my $balanced_handler = $self->schema->storage->balancer;
719 $schema->storage->read_handler($balanced_handler);
724 Check that the master and at least one of the replicants is connected.
731 $self->master->connected &&
732 $self->pool->connected_replicants;
735 =head2 ensure_connected
737 Make sure all the storages are connected.
741 sub ensure_connected {
743 foreach my $source ($self->all_storages) {
744 $source->ensure_connected(@_);
750 Set the limit_dialect for all existing storages
756 foreach my $source ($self->all_storages) {
757 $source->limit_dialect(@_);
759 return $self->master->limit_dialect;
764 Set the quote_char for all existing storages
770 foreach my $source ($self->all_storages) {
771 $source->quote_char(@_);
773 return $self->master->quote_char;
778 Set the name_sep for all existing storages
784 foreach my $source ($self->all_storages) {
785 $source->name_sep(@_);
787 return $self->master->name_sep;
792 Set the schema object for all existing storages
798 foreach my $source ($self->all_storages) {
799 $source->set_schema(@_);
805 set a debug flag across all storages
812 foreach my $source ($self->all_storages) {
816 return $self->master->debug;
827 return $self->master->debugobj(@_);
838 return $self->master->debugfh(@_);
849 return $self->master->debugcb(@_);
854 disconnect everything
860 foreach my $source ($self->all_storages) {
861 $source->disconnect(@_);
867 set cursor class on all storages, or return master's
872 my ($self, $cursor_class) = @_;
875 $_->cursor_class($cursor_class) for $self->all_storages;
877 $self->master->cursor_class;
882 set cursor class on all storages, or return master's, alias for L</cursor_class>
888 my ($self, $cursor_class) = @_;
891 $_->cursor($cursor_class) for $self->all_storages;
893 $self->master->cursor;
898 sets the L<DBIx::Class::Storage::DBI/unsafe> option on all storages or returns
899 master's current setting
907 $_->unsafe(@_) for $self->all_storages;
910 return $self->master->unsafe;
913 =head2 disable_sth_caching
915 sets the L<DBIx::Class::Storage::DBI/disable_sth_caching> option on all storages
916 or returns master's current setting
920 sub disable_sth_caching {
924 $_->disable_sth_caching(@_) for $self->all_storages;
927 return $self->master->disable_sth_caching;
930 =head2 lag_behind_master
932 returns the highest Replicant L<DBIx::Class::Storage::DBI/lag_behind_master>
937 sub lag_behind_master {
940 return max map $_->lag_behind_master, $self->replicants;
943 =head2 is_replicating
945 returns true if all replicants return true for
946 L<DBIx::Class::Storage::DBI/is_replicating>
953 return (grep $_->is_replicating, $self->replicants) == ($self->replicants);
956 =head2 connect_call_datetime_setup
958 calls L<DBIx::Class::Storage::DBI/connect_call_datetime_setup> for all storages
962 sub connect_call_datetime_setup {
964 $_->connect_call_datetime_setup for $self->all_storages;
969 $_->_populate_dbh for $self->all_storages;
974 $_->_connect for $self->all_storages;
979 $_->_rebless for $self->all_storages;
982 sub _determine_driver {
984 $_->_determine_driver for $self->all_storages;
987 sub _driver_determined {
991 $_->_driver_determined(@_) for $self->all_storages;
994 return $self->master->_driver_determined;
1000 $_->_init for $self->all_storages;
1003 sub _run_connection_actions {
1006 $_->_run_connection_actions for $self->all_storages;
1009 sub _do_connection_actions {
1013 $_->_do_connection_actions(@_) for $self->all_storages;
1017 sub connect_call_do_sql {
1019 $_->connect_call_do_sql(@_) for $self->all_storages;
1022 sub disconnect_call_do_sql {
1024 $_->disconnect_call_do_sql(@_) for $self->all_storages;
1027 sub _seems_connected {
1030 return min map $_->_seems_connected, $self->all_storages;
1036 return min map $_->_ping, $self->all_storages;
1039 # not using the normalized_version, because we want to preserve
1040 # version numbers much longer than the conventional xxx.yyyzzz
1041 my $numify_ver = sub {
1043 my @numparts = split /\D+/, $ver;
1044 my $format = '%d.' . (join '', ('%06d') x (@numparts - 1));
1046 return sprintf $format, @numparts;
1051 if (not $self->_dbh_details->{info}) {
1052 $self->_dbh_details->{info} = (
1053 reduce { $a->[0] < $b->[0] ? $a : $b }
1054 map [ $numify_ver->($_->{dbms_version}), $_ ],
1055 map $_->_server_info, $self->all_storages
1059 return $self->next::method;
1062 sub _get_server_version {
1065 return $self->_server_info->{dbms_version};
1070 Due to the fact that replicants can lag behind a master, you must take care to
1071 make sure you use one of the methods to force read queries to a master should
1072 you need realtime data integrity. For example, if you insert a row, and then
1073 immediately re-read it from the database (say, by doing $row->discard_changes)
1074 or you insert a row and then immediately build a query that expects that row
1075 to be an item, you should force the master to handle reads. Otherwise, due to
1076 the lag, there is no certainty your data will be in the expected state.
1078 For data integrity, all transactions automatically use the master storage for
1079 all read and write queries. Using a transaction is the preferred and recommended
1080 method to force the master to handle all read queries.
1082 Otherwise, you can force a single query to use the master with the 'force_pool'
1085 my $row = $resultset->search(undef, {force_pool=>'master'})->find($pk);
1087 This attribute will safely be ignore by non replicated storages, so you can use
1088 the same code for both types of systems.
1090 Lastly, you can use the L</execute_reliably> method, which works very much like
1093 For debugging, you can turn replication on/off with the methods L</set_reliable_storage>
1094 and L</set_balanced_storage>, however this operates at a global level and is not
1095 suitable if you have a shared Schema object being used by multiple processes,
1096 such as on a web application server. You can get around this limitation by
1097 using the Schema clone method.
1099 my $new_schema = $schema->clone;
1100 $new_schema->set_reliable_storage;
1102 ## $new_schema will use only the Master storage for all reads/writes while
1103 ## the $schema object will use replicated storage.
1107 John Napiorkowski <john.napiorkowski@takkle.com>
1109 Based on code originated by:
1111 Norbert Csongrádi <bert@cpan.org>
1112 Peter Siklósi <einon@einon.hu>
1116 You may distribute this code under the same terms as Perl itself.
1120 __PACKAGE__->meta->make_immutable;