Switch the ::Sybase family to _determine_connector_driver (same as 75d3bdb2)
[dbsrgits/DBIx-Class.git] / lib / DBIx / Class / Storage / DBI / Replicated.pm
CommitLineData
2156bbdd 1package DBIx::Class::Storage::DBI::Replicated;
f5d3a5de 2
c96bf2bc 3use warnings;
4use strict;
5
ecb65397 6BEGIN {
c96bf2bc 7 require DBIx::Class::Optional::Dependencies;
8 if ( my $missing = DBIx::Class::Optional::Dependencies->req_missing_for('replicated') ) {
9 die "The following modules are required for Replicated storage support: $missing\n";
10 }
ecb65397 11}
12
b2e4d522 13use Moose;
26ab719a 14use DBIx::Class::Storage::DBI;
2bf79155 15use DBIx::Class::Storage::DBI::Replicated::Pool;
26ab719a 16use DBIx::Class::Storage::DBI::Replicated::Balancer;
6a151f58 17use DBIx::Class::Storage::DBI::Replicated::Types qw/BalancerClassNamePart DBICSchema DBICStorageDBI/;
41916570 18use MooseX::Types::Moose qw/ClassName HashRef Object/;
b2e4d522 19use Scalar::Util 'reftype';
e666c5fd 20use Hash::Merge;
7da56142 21use List::Util qw/min max reduce/;
1abccf54 22use Context::Preserve 'preserve_context';
ed7ab0f4 23use Try::Tiny;
9901aad7 24
25use namespace::clean -except => 'meta';
2bf79155 26
27=head1 NAME
28
ecb65397 29DBIx::Class::Storage::DBI::Replicated - BETA Replicated database support
2bf79155 30
31=head1 SYNOPSIS
32
33The Following example shows how to change an existing $schema to a replicated
48580715 34storage type, add some replicated (read-only) databases, and perform reporting
955a6df6 35tasks.
2bf79155 36
3da4f736 37You should set the 'storage_type attribute to a replicated type. You should
d4daee7b 38also define your arguments, such as which balancer you want and any arguments
3da4f736 39that the Pool object should get.
40
ce854fd3 41 my $schema = Schema::Class->clone;
592fa86f 42 $schema->storage_type(['::DBI::Replicated', { balancer_type => '::Random' }]);
ce854fd3 43 $schema->connection(...);
d4daee7b 44
fd323bf1 45Next, you need to add in the Replicants. Basically this is an array of
3da4f736 46arrayrefs, where each arrayref is database connect information. Think of these
47arguments as what you'd pass to the 'normal' $schema->connect method.
d4daee7b 48
64cdad22 49 $schema->storage->connect_replicants(
50 [$dsn1, $user, $pass, \%opts],
51 [$dsn2, $user, $pass, \%opts],
52 [$dsn3, $user, $pass, \%opts],
53 );
d4daee7b 54
3da4f736 55Now, just use the $schema as you normally would. Automatically all reads will
56be delegated to the replicants, while writes to the master.
57
7e38d850 58 $schema->resultset('Source')->search({name=>'etc'});
d4daee7b 59
3da4f736 60You can force a given query to use a particular storage using the search
61attribute 'force_pool'. For example:
d4daee7b 62
d7c37d66 63 my $rs = $schema->resultset('Source')->search(undef, {force_pool=>'master'});
3da4f736 64
d7c37d66 65Now $rs will force everything (both reads and writes) to use whatever was setup
fd323bf1 66as the master storage. 'master' is hardcoded to always point to the Master,
3da4f736 67but you can also use any Replicant name. Please see:
212cc5c2 68L<DBIx::Class::Storage::DBI::Replicated::Pool> and the replicants attribute for more.
3da4f736 69
70Also see transactions and L</execute_reliably> for alternative ways to
71force read traffic to the master. In general, you should wrap your statements
72in a transaction when you are reading and writing to the same tables at the
73same time, since your replicants will often lag a bit behind the master.
212cc5c2 74
d7c37d66 75If you have a multi-statement read only transaction you can force it to select
76a random server in the pool by:
77
78 my $rs = $schema->resultset('Source')->search( undef,
79 { force_pool => $db->storage->read_handler->next_storage }
80 );
d4daee7b 81
2bf79155 82=head1 DESCRIPTION
83
7e38d850 84Warning: This class is marked BETA. This has been running a production
ccb3b897 85website using MySQL native replication as its backend and we have some decent
7e38d850 86test coverage but the code hasn't yet been stressed by a variety of databases.
48580715 87Individual DBs may have quirks we are not aware of. Please use this in first
7e38d850 88development and pass along your experiences/bug fixes.
2bf79155 89
90This class implements replicated data store for DBI. Currently you can define
91one master and numerous slave database connections. All write-type queries
92(INSERT, UPDATE, DELETE and even LAST_INSERT_ID) are routed to master
93database, all read-type queries (SELECTs) go to the slave database.
94
95Basically, any method request that L<DBIx::Class::Storage::DBI> would normally
bca099a3 96handle gets delegated to one of the two attributes: L</read_handler> or to
97L</write_handler>. Additionally, some methods need to be distributed
2bf79155 98to all existing storages. This way our storage class is a drop in replacement
99for L<DBIx::Class::Storage::DBI>.
100
48580715 101Read traffic is spread across the replicants (slaves) occurring to a user
2bf79155 102selected algorithm. The default algorithm is random weighted.
103
bca099a3 104=head1 NOTES
105
48580715 106The consistency between master and replicants is database specific. The Pool
faaba25f 107gives you a method to validate its replicants, removing and replacing them
7e38d850 108when they fail/pass predefined criteria. Please make careful use of the ways
ecb65397 109to force a query to run against Master when needed.
110
111=head1 REQUIREMENTS
112
a34b0c89 113Replicated Storage has additional requirements not currently part of
aa8b2277 114L<DBIx::Class>. See L<DBIx::Class::Optional::Dependencies> for more details.
2bf79155 115
116=head1 ATTRIBUTES
117
118This class defines the following attributes.
119
2ce6e9a6 120=head2 schema
121
122The underlying L<DBIx::Class::Schema> object this storage is attaching
123
124=cut
125
126has 'schema' => (
127 is=>'rw',
6a151f58 128 isa=>DBICSchema,
2ce6e9a6 129 weak_ref=>1,
130 required=>1,
131);
132
26ab719a 133=head2 pool_type
2bf79155 134
fd323bf1 135Contains the classname which will instantiate the L</pool> object. Defaults
26ab719a 136to: L<DBIx::Class::Storage::DBI::Replicated::Pool>.
2bf79155 137
138=cut
139
26ab719a 140has 'pool_type' => (
dcdf7b2c 141 is=>'rw',
41916570 142 isa=>ClassName,
2ce6e9a6 143 default=>'DBIx::Class::Storage::DBI::Replicated::Pool',
64cdad22 144 handles=>{
145 'create_pool' => 'new',
146 },
2bf79155 147);
148
f068a139 149=head2 pool_args
150
151Contains a hashref of initialized information to pass to the Balancer object.
212cc5c2 152See L<DBIx::Class::Storage::DBI::Replicated::Pool> for available arguments.
f068a139 153
154=cut
155
156has 'pool_args' => (
dcdf7b2c 157 is=>'rw',
41916570 158 isa=>HashRef,
64cdad22 159 lazy=>1,
64cdad22 160 default=>sub { {} },
f068a139 161);
162
163
26ab719a 164=head2 balancer_type
2bf79155 165
166The replication pool requires a balance class to provider the methods for
167choose how to spread the query load across each replicant in the pool.
168
169=cut
170
26ab719a 171has 'balancer_type' => (
dcdf7b2c 172 is=>'rw',
9901aad7 173 isa=>BalancerClassNamePart,
2ce6e9a6 174 coerce=>1,
175 required=>1,
176 default=> 'DBIx::Class::Storage::DBI::Replicated::Balancer::First',
64cdad22 177 handles=>{
178 'create_balancer' => 'new',
179 },
2bf79155 180);
181
17b05c13 182=head2 balancer_args
183
184Contains a hashref of initialized information to pass to the Balancer object.
212cc5c2 185See L<DBIx::Class::Storage::DBI::Replicated::Balancer> for available arguments.
17b05c13 186
187=cut
188
189has 'balancer_args' => (
dcdf7b2c 190 is=>'rw',
41916570 191 isa=>HashRef,
64cdad22 192 lazy=>1,
193 required=>1,
194 default=>sub { {} },
17b05c13 195);
196
26ab719a 197=head2 pool
2bf79155 198
370f78d4 199Is a L<DBIx::Class::Storage::DBI::Replicated::Pool> or derived class. This is a
26ab719a 200container class for one or more replicated databases.
2bf79155 201
202=cut
203
26ab719a 204has 'pool' => (
64cdad22 205 is=>'ro',
206 isa=>'DBIx::Class::Storage::DBI::Replicated::Pool',
207 lazy_build=>1,
208 handles=>[qw/
6f7344b8 209 connect_replicants
64cdad22 210 replicants
211 has_replicants
212 /],
2bf79155 213);
214
26ab719a 215=head2 balancer
2bf79155 216
370f78d4 217Is a L<DBIx::Class::Storage::DBI::Replicated::Balancer> or derived class. This
218is a class that takes a pool (L<DBIx::Class::Storage::DBI::Replicated::Pool>)
2bf79155 219
26ab719a 220=cut
2bf79155 221
26ab719a 222has 'balancer' => (
dcdf7b2c 223 is=>'rw',
64cdad22 224 isa=>'DBIx::Class::Storage::DBI::Replicated::Balancer',
225 lazy_build=>1,
226 handles=>[qw/auto_validate_every/],
26ab719a 227);
2bf79155 228
cb6ec758 229=head2 master
230
231The master defines the canonical state for a pool of connected databases. All
232the replicants are expected to match this databases state. Thus, in a classic
233Master / Slaves distributed system, all the slaves are expected to replicate
234the Master's state as quick as possible. This is the only database in the
235pool of databases that is allowed to handle write traffic.
236
237=cut
238
239has 'master' => (
64cdad22 240 is=> 'ro',
6a151f58 241 isa=>DBICStorageDBI,
64cdad22 242 lazy_build=>1,
cb6ec758 243);
244
cb6ec758 245=head1 ATTRIBUTES IMPLEMENTING THE DBIx::Storage::DBI INTERFACE
246
fd323bf1 247The following methods are delegated all the methods required for the
cb6ec758 248L<DBIx::Class::Storage::DBI> interface.
249
cb6ec758 250=cut
251
4bea1fe7 252my $method_dispatch = {
253 writer => [qw/
64cdad22 254 on_connect_do
6f7344b8 255 on_disconnect_do
3244fdcc 256 on_connect_call
257 on_disconnect_call
64cdad22 258 connect_info
3244fdcc 259 _connect_info
64cdad22 260 throw_exception
261 sql_maker
262 sqlt_type
263 create_ddl_dir
264 deployment_statements
265 datetime_parser
6f7344b8 266 datetime_parser_type
267 build_datetime_parser
64cdad22 268 last_insert_id
269 insert
64cdad22 270 update
271 delete
272 dbh
2ce6e9a6 273 txn_begin
64cdad22 274 txn_do
275 txn_commit
276 txn_rollback
2ce6e9a6 277 txn_scope_guard
90d7422f 278 _exec_txn_rollback
279 _exec_txn_begin
280 _exec_txn_commit
64cdad22 281 deploy
0180bef9 282 with_deferred_fk_checks
6f7344b8 283 dbh_do
2ce6e9a6 284 _prep_for_execute
6f7344b8 285 is_datatype_numeric
286 _count_select
6f7344b8 287 svp_rollback
288 svp_begin
289 svp_release
e398f77e 290 relname_to_table_alias
3244fdcc 291 _dbh_last_insert_id
3244fdcc 292 _default_dbi_connect_attributes
293 _dbi_connect_info
b9ca4ff1 294 _dbic_connect_attributes
3244fdcc 295 auto_savepoint
0e773352 296 _query_start
3244fdcc 297 _query_end
0e773352 298 _format_for_trace
299 _dbi_attrs_for_bind
3244fdcc 300 bind_attribute_by_data_type
301 transaction_depth
302 _dbh
303 _select_args
52cef7e3 304 _dbh_execute_for_fetch
3244fdcc 305 _sql_maker
3244fdcc 306 _dbh_execute_inserts_with_no_binds
307 _select_args_to_query
5e782048 308 _gen_sql_bind
3244fdcc 309 _svp_generate_name
3244fdcc 310 _normalize_connect_info
311 _parse_connect_do
3244fdcc 312 savepoints
3244fdcc 313 _sql_maker_opts
7d6c28b7 314 _use_multicolumn_in
3244fdcc 315 _conn_pid
3244fdcc 316 _dbh_autocommit
317 _native_data_type
318 _get_dbh
319 sql_maker_class
2a6dda4b 320 insert_bulk
321 _insert_bulk
3244fdcc 322 _execute
323 _do_query
3244fdcc 324 _dbh_execute
5b4f3fd0 325 /, Class::MOP::Class->initialize('DBIx::Class::Storage::DBIHacks')->get_method_list ],
4bea1fe7 326 reader => [qw/
327 select
328 select_single
329 columns_info_for
330 _dbh_columns_info_for
331 _select
332 /],
333 unimplemented => [qw/
334 _arm_global_destructor
335 _verify_pid
336
337 get_use_dbms_capability
338 set_use_dbms_capability
339 get_dbms_capability
340 set_dbms_capability
341 _dbh_details
342 _dbh_get_info
b0c42bbc 343 _get_rdbms_name
4bea1fe7 344
75d3bdb2 345 _determine_connector_driver
37b5ab51 346 _extract_driver_from_connect_info
75d3bdb2 347 _describe_connection
348 _warn_undetermined_driver
349
4bea1fe7 350 sql_limit_dialect
351 sql_quote_char
352 sql_name_sep
353
4bea1fe7 354 _prefetch_autovalues
fabbd5cc 355 _perform_autoinc_retrieval
356 _autoinc_supplied_for_op
4bea1fe7 357
eec07bca 358 _resolve_bindattrs
359
4bea1fe7 360 _max_column_bytesize
361 _is_lob_type
362 _is_binary_lob_type
5efba7fc 363 _is_binary_type
4bea1fe7 364 _is_text_lob_type
402ac1c9 365
9930caaf 366 _prepare_sth
367 _bind_sth_params
4bea1fe7 368 /,(
369 # the capability framework
370 # not sure if CMOP->initialize does evil things to DBIC::S::DBI, fix if a problem
371 grep
7d6c28b7 372 { $_ =~ /^ _ (?: use | supports | determine_supports ) _ /x and $_ ne '_use_multicolumn_in' }
4bea1fe7 373 ( Class::MOP::Class->initialize('DBIx::Class::Storage::DBI')->get_all_method_names )
374 )],
375};
376
377if (DBIx::Class::_ENV_::DBICTEST) {
378
379 my $seen;
380 for my $type (keys %$method_dispatch) {
381 for (@{$method_dispatch->{$type}}) {
382 push @{$seen->{$_}}, $type;
383 }
384 }
cb6ec758 385
4bea1fe7 386 if (my @dupes = grep { @{$seen->{$_}} > 1 } keys %$seen) {
387 die(join "\n", '',
388 'The following methods show up multiple times in ::Storage::DBI::Replicated handlers:',
389 (map { "$_: " . (join ', ', @{$seen->{$_}}) } sort @dupes),
390 '',
391 );
392 }
bbdda281 393
4bea1fe7 394 if (my @cant = grep { ! DBIx::Class::Storage::DBI->can($_) } keys %$seen) {
395 die(join "\n", '',
396 '::Storage::DBI::Replicated specifies handling of the following *NON EXISTING* ::Storage::DBI methods:',
397 @cant,
398 '',
399 );
400 }
401}
bbdda281 402
4bea1fe7 403for my $method (@{$method_dispatch->{unimplemented}}) {
404 __PACKAGE__->meta->add_method($method, sub {
70c28808 405 my $self = shift;
e705f529 406 $self->throw_exception("$method() must not be called on ".(blessed $self).' objects');
4bea1fe7 407 });
408}
31a8aaaf 409
4bea1fe7 410=head2 read_handler
584ea6e4 411
5529838f 412Defines an object that implements the read side of L<DBIx::Class::Storage::DBI>.
584ea6e4 413
4bea1fe7 414=cut
415
416has 'read_handler' => (
417 is=>'rw',
418 isa=>Object,
419 lazy_build=>1,
420 handles=>$method_dispatch->{reader},
e471ab87 421);
422
4bea1fe7 423=head2 write_handler
424
5529838f 425Defines an object that implements the write side of L<DBIx::Class::Storage::DBI>,
4bea1fe7 426as well as methods that don't write or read that can be called on only one
427storage, methods that return a C<$dbh>, and any methods that don't make sense to
428run on a replicant.
429
430=cut
431
432has 'write_handler' => (
433 is=>'ro',
434 isa=>Object,
435 lazy_build=>1,
436 handles=>$method_dispatch->{writer},
7f4433eb 437);
438
4bea1fe7 439
6d766626 440
b2e4d522 441has _master_connect_info_opts =>
442 (is => 'rw', isa => HashRef, default => sub { {} });
443
444=head2 around: connect_info
445
48580715 446Preserves master's C<connect_info> options (for merging with replicants.)
447Also sets any Replicated-related options from connect_info, such as
dcdf7b2c 448C<pool_type>, C<pool_args>, C<balancer_type> and C<balancer_args>.
b2e4d522 449
450=cut
451
452around connect_info => sub {
453 my ($next, $self, $info, @extra) = @_;
454
1fccee7b 455 $self->throw_exception(
456 'connect_info can not be retrieved from a replicated storage - '
457 . 'accessor must be called on a specific pool instance'
458 ) unless defined $info;
459
282a9a4f 460 my $merge = Hash::Merge->new('LEFT_PRECEDENT');
e666c5fd 461
b2e4d522 462 my %opts;
463 for my $arg (@$info) {
464 next unless (reftype($arg)||'') eq 'HASH';
e666c5fd 465 %opts = %{ $merge->merge($arg, \%opts) };
b2e4d522 466 }
b2e4d522 467 delete $opts{dsn};
468
dcdf7b2c 469 if (@opts{qw/pool_type pool_args/}) {
470 $self->pool_type(delete $opts{pool_type})
471 if $opts{pool_type};
472
b88b85e7 473 $self->pool_args(
e666c5fd 474 $merge->merge((delete $opts{pool_args} || {}), $self->pool_args)
b88b85e7 475 );
dcdf7b2c 476
64ae1667 477 ## Since we possibly changed the pool_args, we need to clear the current
478 ## pool object so that next time it is used it will be rebuilt.
479 $self->clear_pool;
dcdf7b2c 480 }
481
482 if (@opts{qw/balancer_type balancer_args/}) {
483 $self->balancer_type(delete $opts{balancer_type})
484 if $opts{balancer_type};
485
b88b85e7 486 $self->balancer_args(
e666c5fd 487 $merge->merge((delete $opts{balancer_args} || {}), $self->balancer_args)
b88b85e7 488 );
dcdf7b2c 489
67c43863 490 $self->balancer($self->_build_balancer)
6f7344b8 491 if $self->balancer;
dcdf7b2c 492 }
493
b2e4d522 494 $self->_master_connect_info_opts(\%opts);
495
1abccf54 496 return preserve_context {
497 $self->$next($info, @extra);
498 } after => sub {
499 # Make sure master is blessed into the correct class and apply role to it.
500 my $master = $self->master;
501 $master->_determine_driver;
502 Moose::Meta::Class->initialize(ref $master);
cea43436 503
1abccf54 504 DBIx::Class::Storage::DBI::Replicated::WithDSN->meta->apply($master);
0ce2d0d5 505
1abccf54 506 # link pool back to master
507 $self->pool->master($master);
508 };
b2e4d522 509};
510
26ab719a 511=head1 METHODS
2bf79155 512
26ab719a 513This class defines the following methods.
2bf79155 514
c354902c 515=head2 BUILDARGS
2bf79155 516
faaba25f 517L<DBIx::Class::Schema> when instantiating its storage passed itself as the
2ce6e9a6 518first argument. So we need to massage the arguments a bit so that all the
519bits get put into the correct places.
2bf79155 520
521=cut
522
c354902c 523sub BUILDARGS {
fd323bf1 524 my ($class, $schema, $storage_type_args, @args) = @_;
d4daee7b 525
c354902c 526 return {
6f7344b8 527 schema=>$schema,
528 %$storage_type_args,
529 @args
c354902c 530 }
531}
2bf79155 532
cb6ec758 533=head2 _build_master
2bf79155 534
cb6ec758 535Lazy builder for the L</master> attribute.
2bf79155 536
537=cut
538
cb6ec758 539sub _build_master {
2ce6e9a6 540 my $self = shift @_;
ee356d00 541 my $master = DBIx::Class::Storage::DBI->new($self->schema);
ee356d00 542 $master
106d5f3b 543}
544
26ab719a 545=head2 _build_pool
2bf79155 546
26ab719a 547Lazy builder for the L</pool> attribute.
2bf79155 548
549=cut
550
26ab719a 551sub _build_pool {
64cdad22 552 my $self = shift @_;
553 $self->create_pool(%{$self->pool_args});
2bf79155 554}
555
26ab719a 556=head2 _build_balancer
2bf79155 557
cb6ec758 558Lazy builder for the L</balancer> attribute. This takes a Pool object so that
559the balancer knows which pool it's balancing.
2bf79155 560
561=cut
562
26ab719a 563sub _build_balancer {
64cdad22 564 my $self = shift @_;
565 $self->create_balancer(
6f7344b8 566 pool=>$self->pool,
64cdad22 567 master=>$self->master,
568 %{$self->balancer_args},
569 );
2bf79155 570}
571
cb6ec758 572=head2 _build_write_handler
2bf79155 573
cb6ec758 574Lazy builder for the L</write_handler> attribute. The default is to set this to
575the L</master>.
50336325 576
577=cut
578
cb6ec758 579sub _build_write_handler {
64cdad22 580 return shift->master;
cb6ec758 581}
50336325 582
cb6ec758 583=head2 _build_read_handler
2bf79155 584
cb6ec758 585Lazy builder for the L</read_handler> attribute. The default is to set this to
586the L</balancer>.
2bf79155 587
588=cut
589
cb6ec758 590sub _build_read_handler {
64cdad22 591 return shift->balancer;
cb6ec758 592}
50336325 593
cb6ec758 594=head2 around: connect_replicants
2bf79155 595
cb6ec758 596All calls to connect_replicants needs to have an existing $schema tacked onto
5529838f 597top of the args, since L<DBIx::Class::Storage::DBI> needs it, and any
598L<connect_info|DBIx::Class::Storage::DBI/connect_info>
b2e4d522 599options merged with the master, with replicant opts having higher priority.
955a6df6 600
cb6ec758 601=cut
955a6df6 602
b2e4d522 603around connect_replicants => sub {
604 my ($next, $self, @args) = @_;
605
606 for my $r (@args) {
607 $r = [ $r ] unless reftype $r eq 'ARRAY';
608
1a58752c 609 $self->throw_exception('coderef replicant connect_info not supported')
b2e4d522 610 if ref $r->[0] && reftype $r->[0] eq 'CODE';
611
612# any connect_info options?
613 my $i = 0;
614 $i++ while $i < @$r && (reftype($r->[$i])||'') ne 'HASH';
615
6f7344b8 616# make one if none
b2e4d522 617 $r->[$i] = {} unless $r->[$i];
618
619# merge if two hashes
b88b85e7 620 my @hashes = @$r[$i .. $#{$r}];
621
1a58752c 622 $self->throw_exception('invalid connect_info options')
b88b85e7 623 if (grep { reftype($_) eq 'HASH' } @hashes) != @hashes;
624
1a58752c 625 $self->throw_exception('too many hashrefs in connect_info')
b88b85e7 626 if @hashes > 2;
627
282a9a4f 628 my $merge = Hash::Merge->new('LEFT_PRECEDENT');
e666c5fd 629 my %opts = %{ $merge->merge(reverse @hashes) };
b88b85e7 630
631# delete them
b2e4d522 632 splice @$r, $i+1, ($#{$r} - $i), ();
633
0bd8e058 634# make sure master/replicants opts don't clash
635 my %master_opts = %{ $self->_master_connect_info_opts };
636 if (exists $opts{dbh_maker}) {
637 delete @master_opts{qw/dsn user password/};
638 }
639 delete $master_opts{dbh_maker};
640
b2e4d522 641# merge with master
e666c5fd 642 %opts = %{ $merge->merge(\%opts, \%master_opts) };
b2e4d522 643
644# update
645 $r->[$i] = \%opts;
646 }
647
648 $self->$next($self->schema, @args);
955a6df6 649};
2bf79155 650
2bf79155 651=head2 all_storages
652
4a0eed52 653Returns an array of all the connected storage backends. The first element
654in the returned array is the master, and the rest are each of the
2bf79155 655replicants.
656
657=cut
658
659sub all_storages {
64cdad22 660 my $self = shift @_;
661 return grep {defined $_ && blessed $_} (
662 $self->master,
6412a592 663 values %{ $self->replicants },
64cdad22 664 );
2bf79155 665}
666
c4d3fae2 667=head2 execute_reliably ($coderef, ?@args)
668
669Given a coderef, saves the current state of the L</read_handler>, forces it to
48580715 670use reliable storage (e.g. sets it to the master), executes a coderef and then
c4d3fae2 671restores the original state.
672
673Example:
674
64cdad22 675 my $reliably = sub {
676 my $name = shift @_;
677 $schema->resultset('User')->create({name=>$name});
fd323bf1 678 my $user_rs = $schema->resultset('User')->find({name=>$name});
64cdad22 679 return $user_rs;
680 };
c4d3fae2 681
64cdad22 682 my $user_rs = $schema->storage->execute_reliably($reliably, 'John');
c4d3fae2 683
684Use this when you must be certain of your database state, such as when you just
685inserted something and need to get a resultset including it, etc.
686
687=cut
688
689sub execute_reliably {
1abccf54 690 my $self = shift;
691 my $coderef = shift;
d4daee7b 692
64cdad22 693 unless( ref $coderef eq 'CODE') {
694 $self->throw_exception('Second argument must be a coderef');
695 }
d4daee7b 696
1abccf54 697 ## replace the current read handler for the remainder of the scope
698 local $self->{read_handler} = $self->master;
d4daee7b 699
1abccf54 700 my $args = \@_;
701 return try {
702 $coderef->(@$args);
ed7ab0f4 703 } catch {
704 $self->throw_exception("coderef returned an error: $_");
64cdad22 705 };
c4d3fae2 706}
707
cb6ec758 708=head2 set_reliable_storage
709
710Sets the current $schema to be 'reliable', that is all queries, both read and
711write are sent to the master
d4daee7b 712
cb6ec758 713=cut
714
715sub set_reliable_storage {
64cdad22 716 my $self = shift @_;
717 my $schema = $self->schema;
718 my $write_handler = $self->schema->storage->write_handler;
d4daee7b 719
64cdad22 720 $schema->storage->read_handler($write_handler);
cb6ec758 721}
722
723=head2 set_balanced_storage
724
725Sets the current $schema to be use the </balancer> for all reads, while all
48580715 726writes are sent to the master only
d4daee7b 727
cb6ec758 728=cut
729
730sub set_balanced_storage {
64cdad22 731 my $self = shift @_;
732 my $schema = $self->schema;
bd5da369 733 my $balanced_handler = $self->schema->storage->balancer;
d4daee7b 734
bd5da369 735 $schema->storage->read_handler($balanced_handler);
cb6ec758 736}
2bf79155 737
738=head2 connected
739
740Check that the master and at least one of the replicants is connected.
741
742=cut
743
744sub connected {
64cdad22 745 my $self = shift @_;
746 return
747 $self->master->connected &&
748 $self->pool->connected_replicants;
2bf79155 749}
750
2bf79155 751=head2 ensure_connected
752
753Make sure all the storages are connected.
754
755=cut
756
757sub ensure_connected {
64cdad22 758 my $self = shift @_;
759 foreach my $source ($self->all_storages) {
760 $source->ensure_connected(@_);
761 }
2bf79155 762}
763
2bf79155 764=head2 limit_dialect
765
766Set the limit_dialect for all existing storages
767
768=cut
769
770sub limit_dialect {
64cdad22 771 my $self = shift @_;
772 foreach my $source ($self->all_storages) {
773 $source->limit_dialect(@_);
774 }
f3e9f010 775 return $self->master->limit_dialect;
2bf79155 776}
777
2bf79155 778=head2 quote_char
779
780Set the quote_char for all existing storages
781
782=cut
783
784sub quote_char {
64cdad22 785 my $self = shift @_;
786 foreach my $source ($self->all_storages) {
787 $source->quote_char(@_);
788 }
3fbe08e3 789 return $self->master->quote_char;
2bf79155 790}
791
2bf79155 792=head2 name_sep
793
794Set the name_sep for all existing storages
795
796=cut
797
798sub name_sep {
64cdad22 799 my $self = shift @_;
800 foreach my $source ($self->all_storages) {
801 $source->name_sep(@_);
802 }
3fbe08e3 803 return $self->master->name_sep;
2bf79155 804}
805
2bf79155 806=head2 set_schema
807
808Set the schema object for all existing storages
809
810=cut
811
812sub set_schema {
64cdad22 813 my $self = shift @_;
814 foreach my $source ($self->all_storages) {
815 $source->set_schema(@_);
816 }
2bf79155 817}
818
2bf79155 819=head2 debug
820
821set a debug flag across all storages
822
823=cut
824
825sub debug {
64cdad22 826 my $self = shift @_;
3fbe08e3 827 if(@_) {
828 foreach my $source ($self->all_storages) {
829 $source->debug(@_);
6f7344b8 830 }
64cdad22 831 }
3fbe08e3 832 return $self->master->debug;
2bf79155 833}
834
2bf79155 835=head2 debugobj
836
cea43436 837set a debug object
2bf79155 838
839=cut
840
841sub debugobj {
64cdad22 842 my $self = shift @_;
cea43436 843 return $self->master->debugobj(@_);
2bf79155 844}
845
2bf79155 846=head2 debugfh
847
cea43436 848set a debugfh object
2bf79155 849
850=cut
851
852sub debugfh {
64cdad22 853 my $self = shift @_;
cea43436 854 return $self->master->debugfh(@_);
2bf79155 855}
856
2bf79155 857=head2 debugcb
858
cea43436 859set a debug callback
2bf79155 860
861=cut
862
863sub debugcb {
64cdad22 864 my $self = shift @_;
cea43436 865 return $self->master->debugcb(@_);
2bf79155 866}
867
2bf79155 868=head2 disconnect
869
870disconnect everything
871
872=cut
873
874sub disconnect {
64cdad22 875 my $self = shift @_;
876 foreach my $source ($self->all_storages) {
877 $source->disconnect(@_);
878 }
2bf79155 879}
880
b2e4d522 881=head2 cursor_class
882
883set cursor class on all storages, or return master's
884
885=cut
886
887sub cursor_class {
888 my ($self, $cursor_class) = @_;
889
890 if ($cursor_class) {
891 $_->cursor_class($cursor_class) for $self->all_storages;
892 }
893 $self->master->cursor_class;
894}
d4daee7b 895
3244fdcc 896=head2 cursor
897
898set cursor class on all storages, or return master's, alias for L</cursor_class>
899above.
900
901=cut
902
903sub cursor {
904 my ($self, $cursor_class) = @_;
905
906 if ($cursor_class) {
907 $_->cursor($cursor_class) for $self->all_storages;
908 }
909 $self->master->cursor;
910}
911
912=head2 unsafe
913
914sets the L<DBIx::Class::Storage::DBI/unsafe> option on all storages or returns
915master's current setting
916
917=cut
918
919sub unsafe {
920 my $self = shift;
921
922 if (@_) {
923 $_->unsafe(@_) for $self->all_storages;
924 }
925
926 return $self->master->unsafe;
927}
928
929=head2 disable_sth_caching
930
931sets the L<DBIx::Class::Storage::DBI/disable_sth_caching> option on all storages
932or returns master's current setting
933
934=cut
935
936sub disable_sth_caching {
937 my $self = shift;
938
939 if (@_) {
940 $_->disable_sth_caching(@_) for $self->all_storages;
941 }
942
943 return $self->master->disable_sth_caching;
944}
945
946=head2 lag_behind_master
947
948returns the highest Replicant L<DBIx::Class::Storage::DBI/lag_behind_master>
949setting
950
951=cut
952
953sub lag_behind_master {
954 my $self = shift;
955
956 return max map $_->lag_behind_master, $self->replicants;
fd323bf1 957}
3244fdcc 958
959=head2 is_replicating
960
961returns true if all replicants return true for
962L<DBIx::Class::Storage::DBI/is_replicating>
963
964=cut
965
966sub is_replicating {
967 my $self = shift;
968
969 return (grep $_->is_replicating, $self->replicants) == ($self->replicants);
970}
971
972=head2 connect_call_datetime_setup
973
974calls L<DBIx::Class::Storage::DBI/connect_call_datetime_setup> for all storages
975
976=cut
977
978sub connect_call_datetime_setup {
979 my $self = shift;
980 $_->connect_call_datetime_setup for $self->all_storages;
981}
982
983sub _populate_dbh {
984 my $self = shift;
985 $_->_populate_dbh for $self->all_storages;
986}
987
988sub _connect {
989 my $self = shift;
990 $_->_connect for $self->all_storages;
991}
992
993sub _rebless {
994 my $self = shift;
995 $_->_rebless for $self->all_storages;
996}
997
998sub _determine_driver {
999 my $self = shift;
1000 $_->_determine_driver for $self->all_storages;
1001}
1002
1003sub _driver_determined {
1004 my $self = shift;
fd323bf1 1005
3244fdcc 1006 if (@_) {
1007 $_->_driver_determined(@_) for $self->all_storages;
1008 }
1009
1010 return $self->master->_driver_determined;
1011}
1012
1013sub _init {
1014 my $self = shift;
fd323bf1 1015
3244fdcc 1016 $_->_init for $self->all_storages;
1017}
1018
1019sub _run_connection_actions {
1020 my $self = shift;
fd323bf1 1021
3244fdcc 1022 $_->_run_connection_actions for $self->all_storages;
1023}
1024
1025sub _do_connection_actions {
1026 my $self = shift;
fd323bf1 1027
3244fdcc 1028 if (@_) {
1029 $_->_do_connection_actions(@_) for $self->all_storages;
1030 }
1031}
1032
1033sub connect_call_do_sql {
1034 my $self = shift;
1035 $_->connect_call_do_sql(@_) for $self->all_storages;
1036}
1037
1038sub disconnect_call_do_sql {
1039 my $self = shift;
1040 $_->disconnect_call_do_sql(@_) for $self->all_storages;
1041}
1042
1043sub _seems_connected {
1044 my $self = shift;
1045
1046 return min map $_->_seems_connected, $self->all_storages;
1047}
1048
1049sub _ping {
1050 my $self = shift;
1051
1052 return min map $_->_ping, $self->all_storages;
1053}
1054
bbdda281 1055# not using the normalized_version, because we want to preserve
1056# version numbers much longer than the conventional xxx.yyyzzz
7da56142 1057my $numify_ver = sub {
1058 my $ver = shift;
1059 my @numparts = split /\D+/, $ver;
bbdda281 1060 my $format = '%d.' . (join '', ('%06d') x (@numparts - 1));
7da56142 1061
1062 return sprintf $format, @numparts;
1063};
fecb38cb 1064sub _server_info {
1065 my $self = shift;
1066
bbdda281 1067 if (not $self->_dbh_details->{info}) {
1068 $self->_dbh_details->{info} = (
fd323bf1 1069 reduce { $a->[0] < $b->[0] ? $a : $b }
7da56142 1070 map [ $numify_ver->($_->{dbms_version}), $_ ],
1071 map $_->_server_info, $self->all_storages
1072 )->[1];
fecb38cb 1073 }
1074
bbdda281 1075 return $self->next::method;
fecb38cb 1076}
1077
1078sub _get_server_version {
1079 my $self = shift;
1080
1081 return $self->_server_info->{dbms_version};
1082}
1083
7e38d850 1084=head1 GOTCHAS
1085
1086Due to the fact that replicants can lag behind a master, you must take care to
1087make sure you use one of the methods to force read queries to a master should
1088you need realtime data integrity. For example, if you insert a row, and then
3dd506b8 1089immediately re-read it from the database (say, by doing
1090L<< $result->discard_changes|DBIx::Class::Row/discard_changes >>)
7e38d850 1091or you insert a row and then immediately build a query that expects that row
1092to be an item, you should force the master to handle reads. Otherwise, due to
1093the lag, there is no certainty your data will be in the expected state.
1094
1095For data integrity, all transactions automatically use the master storage for
1096all read and write queries. Using a transaction is the preferred and recommended
1097method to force the master to handle all read queries.
1098
1099Otherwise, you can force a single query to use the master with the 'force_pool'
1100attribute:
1101
47d7b769 1102 my $result = $resultset->search(undef, {force_pool=>'master'})->find($pk);
7e38d850 1103
b1de1b06 1104This attribute will safely be ignored by non replicated storages, so you can use
7e38d850 1105the same code for both types of systems.
1106
1107Lastly, you can use the L</execute_reliably> method, which works very much like
1108a transaction.
1109
1110For debugging, you can turn replication on/off with the methods L</set_reliable_storage>
1111and L</set_balanced_storage>, however this operates at a global level and is not
1112suitable if you have a shared Schema object being used by multiple processes,
1113such as on a web application server. You can get around this limitation by
1114using the Schema clone method.
1115
1116 my $new_schema = $schema->clone;
1117 $new_schema->set_reliable_storage;
d4daee7b 1118
7e38d850 1119 ## $new_schema will use only the Master storage for all reads/writes while
1120 ## the $schema object will use replicated storage.
1121
a2bd3796 1122=head1 FURTHER QUESTIONS?
f5d3a5de 1123
a2bd3796 1124Check the list of L<additional DBIC resources|DBIx::Class/GETTING HELP/SUPPORT>.
2156bbdd 1125
a2bd3796 1126=head1 COPYRIGHT AND LICENSE
f5d3a5de 1127
a2bd3796 1128This module is free software L<copyright|DBIx::Class/COPYRIGHT AND LICENSE>
1129by the L<DBIx::Class (DBIC) authors|DBIx::Class/AUTHORS>. You can
1130redistribute it and/or modify it under the same terms as the
1131L<DBIx::Class library|DBIx::Class/COPYRIGHT AND LICENSE>.
f5d3a5de 1132
1133=cut
1134
c354902c 1135__PACKAGE__->meta->make_immutable;
1136
f5d3a5de 11371;