active_record_replica 2.0.1
Sign up to get free protection for your applications and to get access to all the features.
- checksums.yaml +7 -0
- data/LICENSE.txt +201 -0
- data/README.md +10 -0
- data/Rakefile +31 -0
- data/lib/active_record_replica.rb +11 -0
- data/lib/active_record_replica/active_record_replica.rb +139 -0
- data/lib/active_record_replica/errors.rb +5 -0
- data/lib/active_record_replica/extensions.rb +65 -0
- data/lib/active_record_replica/railtie.rb +24 -0
- data/lib/active_record_replica/replica.rb +12 -0
- data/lib/active_record_replica/version.rb +3 -0
- data/test/active_record_replica_test.rb +150 -0
- data/test/database.yml +12 -0
- data/test/test.sqlite3 +0 -0
- data/test/test_helper.rb +6 -0
- data/test/test_replica.sqlite3 +0 -0
- metadata +84 -0
checksums.yaml
ADDED
@@ -0,0 +1,7 @@
|
|
1
|
+
---
|
2
|
+
SHA256:
|
3
|
+
metadata.gz: 5cc978d66d3457173ce9e9c7f90a7fab59429853f52504d478f4f5abd2c9d885
|
4
|
+
data.tar.gz: 44c3ec2886dc9877b972869ba74b22b6dcdc72b00d5f50183b02246d5d3fc99a
|
5
|
+
SHA512:
|
6
|
+
metadata.gz: a620d2745c2b29212a3e1ba45eef5594ec25604286def24f623cdf5a6b473471462ed33632f4b93ad7f1f65575e75b6f70ad1e2b7554d058bf976b1327bbd4b5
|
7
|
+
data.tar.gz: f4a086eb1ce2d4a737a2b46336b20cbcb5038a5123a0d68ed0f6545cc4a9c4de0988c3e55289b185b0e12a72296dfce38120a04fbbc77166f5278dfca4ee3a00
|
data/LICENSE.txt
ADDED
@@ -0,0 +1,201 @@
|
|
1
|
+
Apache License
|
2
|
+
Version 2.0, January 2004
|
3
|
+
http://www.apache.org/licenses/
|
4
|
+
|
5
|
+
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
6
|
+
|
7
|
+
1. Definitions.
|
8
|
+
|
9
|
+
"License" shall mean the terms and conditions for use, reproduction,
|
10
|
+
and distribution as defined by Sections 1 through 9 of this document.
|
11
|
+
|
12
|
+
"Licensor" shall mean the copyright owner or entity authorized by
|
13
|
+
the copyright owner that is granting the License.
|
14
|
+
|
15
|
+
"Legal Entity" shall mean the union of the acting entity and all
|
16
|
+
other entities that control, are controlled by, or are under common
|
17
|
+
control with that entity. For the purposes of this definition,
|
18
|
+
"control" means (i) the power, direct or indirect, to cause the
|
19
|
+
direction or management of such entity, whether by contract or
|
20
|
+
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
21
|
+
outstanding shares, or (iii) beneficial ownership of such entity.
|
22
|
+
|
23
|
+
"You" (or "Your") shall mean an individual or Legal Entity
|
24
|
+
exercising permissions granted by this License.
|
25
|
+
|
26
|
+
"Source" form shall mean the preferred form for making modifications,
|
27
|
+
including but not limited to software source code, documentation
|
28
|
+
source, and configuration files.
|
29
|
+
|
30
|
+
"Object" form shall mean any form resulting from mechanical
|
31
|
+
transformation or translation of a Source form, including but
|
32
|
+
not limited to compiled object code, generated documentation,
|
33
|
+
and conversions to other media types.
|
34
|
+
|
35
|
+
"Work" shall mean the work of authorship, whether in Source or
|
36
|
+
Object form, made available under the License, as indicated by a
|
37
|
+
copyright notice that is included in or attached to the work
|
38
|
+
(an example is provided in the Appendix below).
|
39
|
+
|
40
|
+
"Derivative Works" shall mean any work, whether in Source or Object
|
41
|
+
form, that is based on (or derived from) the Work and for which the
|
42
|
+
editorial revisions, annotations, elaborations, or other modifications
|
43
|
+
represent, as a whole, an original work of authorship. For the purposes
|
44
|
+
of this License, Derivative Works shall not include works that remain
|
45
|
+
separable from, or merely link (or bind by name) to the interfaces of,
|
46
|
+
the Work and Derivative Works thereof.
|
47
|
+
|
48
|
+
"Contribution" shall mean any work of authorship, including
|
49
|
+
the original version of the Work and any modifications or additions
|
50
|
+
to that Work or Derivative Works thereof, that is intentionally
|
51
|
+
submitted to Licensor for inclusion in the Work by the copyright owner
|
52
|
+
or by an individual or Legal Entity authorized to submit on behalf of
|
53
|
+
the copyright owner. For the purposes of this definition, "submitted"
|
54
|
+
means any form of electronic, verbal, or written communication sent
|
55
|
+
to the Licensor or its representatives, including but not limited to
|
56
|
+
communication on electronic mailing lists, source code control systems,
|
57
|
+
and issue tracking systems that are managed by, or on behalf of, the
|
58
|
+
Licensor for the purpose of discussing and improving the Work, but
|
59
|
+
excluding communication that is conspicuously marked or otherwise
|
60
|
+
designated in writing by the copyright owner as "Not a Contribution."
|
61
|
+
|
62
|
+
"Contributor" shall mean Licensor and any individual or Legal Entity
|
63
|
+
on behalf of whom a Contribution has been received by Licensor and
|
64
|
+
subsequently incorporated within the Work.
|
65
|
+
|
66
|
+
2. Grant of Copyright License. Subject to the terms and conditions of
|
67
|
+
this License, each Contributor hereby grants to You a perpetual,
|
68
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
69
|
+
copyright license to reproduce, prepare Derivative Works of,
|
70
|
+
publicly display, publicly perform, sublicense, and distribute the
|
71
|
+
Work and such Derivative Works in Source or Object form.
|
72
|
+
|
73
|
+
3. Grant of Patent License. Subject to the terms and conditions of
|
74
|
+
this License, each Contributor hereby grants to You a perpetual,
|
75
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
76
|
+
(except as stated in this section) patent license to make, have made,
|
77
|
+
use, offer to sell, sell, import, and otherwise transfer the Work,
|
78
|
+
where such license applies only to those patent claims licensable
|
79
|
+
by such Contributor that are necessarily infringed by their
|
80
|
+
Contribution(s) alone or by combination of their Contribution(s)
|
81
|
+
with the Work to which such Contribution(s) was submitted. If You
|
82
|
+
institute patent litigation against any entity (including a
|
83
|
+
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
84
|
+
or a Contribution incorporated within the Work constitutes direct
|
85
|
+
or contributory patent infringement, then any patent licenses
|
86
|
+
granted to You under this License for that Work shall terminate
|
87
|
+
as of the date such litigation is filed.
|
88
|
+
|
89
|
+
4. Redistribution. You may reproduce and distribute copies of the
|
90
|
+
Work or Derivative Works thereof in any medium, with or without
|
91
|
+
modifications, and in Source or Object form, provided that You
|
92
|
+
meet the following conditions:
|
93
|
+
|
94
|
+
(a) You must give any other recipients of the Work or
|
95
|
+
Derivative Works a copy of this License; and
|
96
|
+
|
97
|
+
(b) You must cause any modified files to carry prominent notices
|
98
|
+
stating that You changed the files; and
|
99
|
+
|
100
|
+
(c) You must retain, in the Source form of any Derivative Works
|
101
|
+
that You distribute, all copyright, patent, trademark, and
|
102
|
+
attribution notices from the Source form of the Work,
|
103
|
+
excluding those notices that do not pertain to any part of
|
104
|
+
the Derivative Works; and
|
105
|
+
|
106
|
+
(d) If the Work includes a "NOTICE" text file as part of its
|
107
|
+
distribution, then any Derivative Works that You distribute must
|
108
|
+
include a readable copy of the attribution notices contained
|
109
|
+
within such NOTICE file, excluding those notices that do not
|
110
|
+
pertain to any part of the Derivative Works, in at least one
|
111
|
+
of the following places: within a NOTICE text file distributed
|
112
|
+
as part of the Derivative Works; within the Source form or
|
113
|
+
documentation, if provided along with the Derivative Works; or,
|
114
|
+
within a display generated by the Derivative Works, if and
|
115
|
+
wherever such third-party notices normally appear. The contents
|
116
|
+
of the NOTICE file are for informational purposes only and
|
117
|
+
do not modify the License. You may add Your own attribution
|
118
|
+
notices within Derivative Works that You distribute, alongside
|
119
|
+
or as an addendum to the NOTICE text from the Work, provided
|
120
|
+
that such additional attribution notices cannot be construed
|
121
|
+
as modifying the License.
|
122
|
+
|
123
|
+
You may add Your own copyright statement to Your modifications and
|
124
|
+
may provide additional or different license terms and conditions
|
125
|
+
for use, reproduction, or distribution of Your modifications, or
|
126
|
+
for any such Derivative Works as a whole, provided Your use,
|
127
|
+
reproduction, and distribution of the Work otherwise complies with
|
128
|
+
the conditions stated in this License.
|
129
|
+
|
130
|
+
5. Submission of Contributions. Unless You explicitly state otherwise,
|
131
|
+
any Contribution intentionally submitted for inclusion in the Work
|
132
|
+
by You to the Licensor shall be under the terms and conditions of
|
133
|
+
this License, without any additional terms or conditions.
|
134
|
+
Notwithstanding the above, nothing herein shall supersede or modify
|
135
|
+
the terms of any separate license agreement you may have executed
|
136
|
+
with Licensor regarding such Contributions.
|
137
|
+
|
138
|
+
6. Trademarks. This License does not grant permission to use the trade
|
139
|
+
names, trademarks, service marks, or product names of the Licensor,
|
140
|
+
except as required for reasonable and customary use in describing the
|
141
|
+
origin of the Work and reproducing the content of the NOTICE file.
|
142
|
+
|
143
|
+
7. Disclaimer of Warranty. Unless required by applicable law or
|
144
|
+
agreed to in writing, Licensor provides the Work (and each
|
145
|
+
Contributor provides its Contributions) on an "AS IS" BASIS,
|
146
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
147
|
+
implied, including, without limitation, any warranties or conditions
|
148
|
+
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
149
|
+
PARTICULAR PURPOSE. You are solely responsible for determining the
|
150
|
+
appropriateness of using or redistributing the Work and assume any
|
151
|
+
risks associated with Your exercise of permissions under this License.
|
152
|
+
|
153
|
+
8. Limitation of Liability. In no event and under no legal theory,
|
154
|
+
whether in tort (including negligence), contract, or otherwise,
|
155
|
+
unless required by applicable law (such as deliberate and grossly
|
156
|
+
negligent acts) or agreed to in writing, shall any Contributor be
|
157
|
+
liable to You for damages, including any direct, indirect, special,
|
158
|
+
incidental, or consequential damages of any character arising as a
|
159
|
+
result of this License or out of the use or inability to use the
|
160
|
+
Work (including but not limited to damages for loss of goodwill,
|
161
|
+
work stoppage, computer failure or malfunction, or any and all
|
162
|
+
other commercial damages or losses), even if such Contributor
|
163
|
+
has been advised of the possibility of such damages.
|
164
|
+
|
165
|
+
9. Accepting Warranty or Additional Liability. While redistributing
|
166
|
+
the Work or Derivative Works thereof, You may choose to offer,
|
167
|
+
and charge a fee for, acceptance of support, warranty, indemnity,
|
168
|
+
or other liability obligations and/or rights consistent with this
|
169
|
+
License. However, in accepting such obligations, You may act only
|
170
|
+
on Your own behalf and on Your sole responsibility, not on behalf
|
171
|
+
of any other Contributor, and only if You agree to indemnify,
|
172
|
+
defend, and hold each Contributor harmless for any liability
|
173
|
+
incurred by, or claims asserted against, such Contributor by reason
|
174
|
+
of your accepting any such warranty or additional liability.
|
175
|
+
|
176
|
+
END OF TERMS AND CONDITIONS
|
177
|
+
|
178
|
+
APPENDIX: How to apply the Apache License to your work.
|
179
|
+
|
180
|
+
To apply the Apache License to your work, attach the following
|
181
|
+
boilerplate notice, with the fields enclosed by brackets "[]"
|
182
|
+
replaced with your own identifying information. (Don't include
|
183
|
+
the brackets!) The text should be enclosed in the appropriate
|
184
|
+
comment syntax for the file format. We also recommend that a
|
185
|
+
file or class name and description of purpose be included on the
|
186
|
+
same "printed page" as the copyright notice for easier
|
187
|
+
identification within third-party archives.
|
188
|
+
|
189
|
+
Copyright 2012, 2013, 2014 Reid Morrison
|
190
|
+
|
191
|
+
Licensed under the Apache License, Version 2.0 (the "License");
|
192
|
+
you may not use this file except in compliance with the License.
|
193
|
+
You may obtain a copy of the License at
|
194
|
+
|
195
|
+
http://www.apache.org/licenses/LICENSE-2.0
|
196
|
+
|
197
|
+
Unless required by applicable law or agreed to in writing, software
|
198
|
+
distributed under the License is distributed on an "AS IS" BASIS,
|
199
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
200
|
+
See the License for the specific language governing permissions and
|
201
|
+
limitations under the License.
|
data/README.md
ADDED
@@ -0,0 +1,10 @@
|
|
1
|
+
# Active Record Replica
|
2
|
+
![](https://img.shields.io/badge/status-DEPRECATED-red.svg) [![Gem Version](https://img.shields.io/gem/v/active_record_replica.svg)](https://rubygems.org/gems/active_record_replica) [![Build Status](https://travis-ci.org/rocketjob/active_record_replica.svg?branch=master)](https://travis-ci.org/rocketjob/active_record_replica) [![Downloads](https://img.shields.io/gem/dt/active_record_replica.svg)](https://rubygems.org/gems/active_record_replica) [![License](https://img.shields.io/badge/license-Apache%202.0-brightgreen.svg)](http://opensource.org/licenses/Apache-2.0)
|
3
|
+
|
4
|
+
Redirect ActiveRecord (Rails) reads to replica databases while ensuring all writes go to the primary database.
|
5
|
+
|
6
|
+
## Status
|
7
|
+
|
8
|
+
All of the capabilities of this gem are now included in Rails 6 :tada:
|
9
|
+
|
10
|
+
_This gem is now archived and no longer maintained._
|
data/Rakefile
ADDED
@@ -0,0 +1,31 @@
|
|
1
|
+
# Setup bundler to avoid having to run bundle exec all the time.
|
2
|
+
require 'rubygems'
|
3
|
+
require 'bundler/setup'
|
4
|
+
|
5
|
+
require 'rake/testtask'
|
6
|
+
require_relative 'lib/active_record_replica/version'
|
7
|
+
|
8
|
+
task :gem do
|
9
|
+
system "gem build active_record_replica.gemspec"
|
10
|
+
end
|
11
|
+
|
12
|
+
task :publish => :gem do
|
13
|
+
system "git tag -a v#{ActiveRecordReplica::VERSION} -m 'Tagging #{ActiveRecordReplica::VERSION}'"
|
14
|
+
system "git push --tags"
|
15
|
+
system "gem push active_record_replica-#{ActiveRecordReplica::VERSION}.gem"
|
16
|
+
system "rm active_record_replica-#{ActiveRecordReplica::VERSION}.gem"
|
17
|
+
end
|
18
|
+
|
19
|
+
Rake::TestTask.new(:test) do |t|
|
20
|
+
t.pattern = 'test/**/*_test.rb'
|
21
|
+
t.verbose = true
|
22
|
+
t.warning = false
|
23
|
+
end
|
24
|
+
|
25
|
+
# By default run tests against all appraisals
|
26
|
+
if !ENV["APPRAISAL_INITIALIZED"] && !ENV["TRAVIS"]
|
27
|
+
require 'appraisal'
|
28
|
+
task default: :appraisal
|
29
|
+
else
|
30
|
+
task default: :test
|
31
|
+
end
|
@@ -0,0 +1,11 @@
|
|
1
|
+
require 'active_record'
|
2
|
+
require 'active_record/base'
|
3
|
+
require 'active_record_replica/version'
|
4
|
+
require 'active_record_replica/errors'
|
5
|
+
require 'active_record_replica/replica'
|
6
|
+
require 'active_record_replica/active_record_replica'
|
7
|
+
require 'active_record_replica/extensions'
|
8
|
+
|
9
|
+
if defined?(Rails)
|
10
|
+
require 'active_record_replica/railtie'
|
11
|
+
end
|
@@ -0,0 +1,139 @@
|
|
1
|
+
#
|
2
|
+
# ActiveRecord read from a replica
|
3
|
+
#
|
4
|
+
module ActiveRecordReplica
|
5
|
+
# Select Methods
|
6
|
+
SELECT_METHODS = [:select, :select_all, :select_one, :select_rows, :select_value, :select_values]
|
7
|
+
|
8
|
+
# In case in the future we are forced to intercept connection#execute if the
|
9
|
+
# above select methods are not sufficient
|
10
|
+
# SQL_READS = /\A\s*(SELECT|WITH|SHOW|CALL|EXPLAIN|DESCRIBE)/i
|
11
|
+
|
12
|
+
# Install ActiveRecord::Replica into ActiveRecord to redirect reads to the replica
|
13
|
+
# Parameters:
|
14
|
+
# adapter_class:
|
15
|
+
# By default, only the default Database adapter (ActiveRecord::Base.connection.class)
|
16
|
+
# is extended with replica read capabilities
|
17
|
+
#
|
18
|
+
# environment:
|
19
|
+
# In a non-Rails environment, supply the environment such as
|
20
|
+
# 'development', 'production'
|
21
|
+
def self.install!(adapter_class = nil, environment = nil)
|
22
|
+
replica_config =
|
23
|
+
if ActiveRecord::Base.connection.respond_to?(:config)
|
24
|
+
ActiveRecord::Base.connection.config[:replica]
|
25
|
+
else
|
26
|
+
ActiveRecord::Base.configurations[environment || Rails.env]['replica']
|
27
|
+
end
|
28
|
+
if replica_config
|
29
|
+
ActiveRecord::Base.logger.info "ActiveRecordReplica.install! v#{ActiveRecordReplica::VERSION} Establishing connection to replica database"
|
30
|
+
Replica.establish_connection(replica_config)
|
31
|
+
|
32
|
+
# Inject a new #select method into the ActiveRecord Database adapter
|
33
|
+
base = adapter_class || ActiveRecord::Base.connection.class
|
34
|
+
base.include(Extensions)
|
35
|
+
else
|
36
|
+
ActiveRecord::Base.logger.info "ActiveRecordReplica not installed since no replica database defined"
|
37
|
+
end
|
38
|
+
end
|
39
|
+
|
40
|
+
# Force reads for the supplied block to read from the primary database
|
41
|
+
# Only applies to calls made within the current thread
|
42
|
+
def self.read_from_primary
|
43
|
+
return yield if read_from_primary?
|
44
|
+
begin
|
45
|
+
previous = Thread.current.thread_variable_get(:active_record_replica)
|
46
|
+
read_from_primary!
|
47
|
+
yield
|
48
|
+
ensure
|
49
|
+
Thread.current.thread_variable_set(:active_record_replica, previous)
|
50
|
+
end
|
51
|
+
end
|
52
|
+
|
53
|
+
#
|
54
|
+
# The default behavior can also set to read/write operations against primary
|
55
|
+
# Create an initializer file config/initializer/active_record_replica.rb
|
56
|
+
# and set ActiveRecordReplica.read_from_primary! to force read from primary.
|
57
|
+
# Then use this method and supply block to read from the replica database
|
58
|
+
# Only applies to calls made within the current thread
|
59
|
+
def self.read_from_replica
|
60
|
+
return yield if read_from_replica?
|
61
|
+
begin
|
62
|
+
previous = Thread.current.thread_variable_get(:active_record_replica)
|
63
|
+
read_from_replica!
|
64
|
+
yield
|
65
|
+
ensure
|
66
|
+
Thread.current.thread_variable_set(:active_record_replica, previous)
|
67
|
+
end
|
68
|
+
end
|
69
|
+
|
70
|
+
# When only reading from a replica it is important to prevent entering any into
|
71
|
+
# a transaction since the transaction still sends traffic to the primary
|
72
|
+
# that will cause the primary database to slow down processing empty transactions.
|
73
|
+
def self.block_transactions
|
74
|
+
begin
|
75
|
+
previous = Thread.current.thread_variable_get(:active_record_replica_transaction)
|
76
|
+
Thread.current.thread_variable_set(:active_record_replica_transaction, :block)
|
77
|
+
yield
|
78
|
+
ensure
|
79
|
+
Thread.current.thread_variable_set(:active_record_replica_transaction, previous)
|
80
|
+
end
|
81
|
+
end
|
82
|
+
|
83
|
+
# During this block any attempts to start or end transactions will be ignored.
|
84
|
+
# This extreme action should only be taken when 100% certain no writes are going to be
|
85
|
+
# performed.
|
86
|
+
def self.skip_transactions
|
87
|
+
begin
|
88
|
+
previous = Thread.current.thread_variable_get(:active_record_replica_transaction)
|
89
|
+
Thread.current.thread_variable_set(:active_record_replica_transaction, :skip)
|
90
|
+
yield
|
91
|
+
ensure
|
92
|
+
Thread.current.thread_variable_set(:active_record_replica_transaction, previous)
|
93
|
+
end
|
94
|
+
end
|
95
|
+
|
96
|
+
# Whether this thread is currently forcing all reads to go against the primary database
|
97
|
+
def self.read_from_primary?
|
98
|
+
Thread.current.thread_variable_get(:active_record_replica) == :primary
|
99
|
+
end
|
100
|
+
|
101
|
+
# Whether this thread is currently forcing all reads to go against the replica database
|
102
|
+
def self.read_from_replica?
|
103
|
+
Thread.current.thread_variable_get(:active_record_replica).nil?
|
104
|
+
end
|
105
|
+
|
106
|
+
# Force all subsequent reads on this thread and any fibers called by this thread to go the primary
|
107
|
+
def self.read_from_primary!
|
108
|
+
Thread.current.thread_variable_set(:active_record_replica, :primary)
|
109
|
+
end
|
110
|
+
|
111
|
+
# Subsequent reads on this thread and any fibers called by this thread can go to a replica
|
112
|
+
def self.read_from_replica!
|
113
|
+
Thread.current.thread_variable_set(:active_record_replica, nil)
|
114
|
+
end
|
115
|
+
|
116
|
+
# Whether any attempt to start a transaction should result in an exception
|
117
|
+
def self.block_transactions?
|
118
|
+
Thread.current.thread_variable_get(:active_record_replica_transaction) == :block
|
119
|
+
end
|
120
|
+
|
121
|
+
# Whether any attempt to start a transaction should be skipped.
|
122
|
+
def self.skip_transactions?
|
123
|
+
Thread.current.thread_variable_get(:active_record_replica_transaction) == :skip
|
124
|
+
end
|
125
|
+
|
126
|
+
# Returns whether replica reads are ignoring transactions
|
127
|
+
def self.ignore_transactions?
|
128
|
+
@ignore_transactions
|
129
|
+
end
|
130
|
+
|
131
|
+
# Set whether replica reads should ignore transactions
|
132
|
+
def self.ignore_transactions=(ignore_transactions)
|
133
|
+
@ignore_transactions = ignore_transactions
|
134
|
+
end
|
135
|
+
|
136
|
+
private
|
137
|
+
|
138
|
+
@ignore_transactions = false
|
139
|
+
end
|
@@ -0,0 +1,65 @@
|
|
1
|
+
require 'active_support/concern'
|
2
|
+
module ActiveRecordReplica
|
3
|
+
module Extensions
|
4
|
+
extend ActiveSupport::Concern
|
5
|
+
|
6
|
+
ActiveRecordReplica::SELECT_METHODS.each do |select_method|
|
7
|
+
class_eval <<-RUBY, __FILE__, __LINE__ + 1
|
8
|
+
def #{select_method}(sql, name = nil, *args)
|
9
|
+
return super if active_record_replica_read_from_primary?
|
10
|
+
|
11
|
+
ActiveRecordReplica.read_from_primary do
|
12
|
+
reader_connection.#{select_method}(sql, "Replica: \#{name || 'SQL'}", *args)
|
13
|
+
end
|
14
|
+
end
|
15
|
+
RUBY
|
16
|
+
end
|
17
|
+
|
18
|
+
def reader_connection
|
19
|
+
Replica.connection
|
20
|
+
end
|
21
|
+
|
22
|
+
def begin_db_transaction
|
23
|
+
return if ActiveRecordReplica.skip_transactions?
|
24
|
+
return super unless ActiveRecordReplica.block_transactions?
|
25
|
+
|
26
|
+
raise(TransactionAttempted, 'Attempting to begin a transaction during a read-only database connection.')
|
27
|
+
end
|
28
|
+
|
29
|
+
def commit_db_transaction
|
30
|
+
return if ActiveRecordReplica.skip_transactions?
|
31
|
+
return super unless ActiveRecordReplica.block_transactions?
|
32
|
+
|
33
|
+
raise(TransactionAttempted, 'Attempting to commit a transaction during a read-only database connection.')
|
34
|
+
end
|
35
|
+
|
36
|
+
def create_savepoint(name = current_savepoint_name(true))
|
37
|
+
return if ActiveRecordReplica.skip_transactions?
|
38
|
+
return super unless ActiveRecordReplica.block_transactions?
|
39
|
+
|
40
|
+
raise(TransactionAttempted, 'Attempting to create a savepoint during a read-only database connection.')
|
41
|
+
end
|
42
|
+
|
43
|
+
def rollback_to_savepoint(name = current_savepoint_name(true))
|
44
|
+
return if ActiveRecordReplica.skip_transactions?
|
45
|
+
return super unless ActiveRecordReplica.block_transactions?
|
46
|
+
|
47
|
+
raise(TransactionAttempted, 'Attempting to rollback a savepoint during a read-only database connection.')
|
48
|
+
end
|
49
|
+
|
50
|
+
def release_savepoint(name = current_savepoint_name(true))
|
51
|
+
return if ActiveRecordReplica.skip_transactions?
|
52
|
+
return super unless ActiveRecordReplica.block_transactions?
|
53
|
+
|
54
|
+
raise(TransactionAttempted, 'Attempting to release a savepoint during a read-only database connection.')
|
55
|
+
end
|
56
|
+
|
57
|
+
# Returns whether to read from the primary database
|
58
|
+
def active_record_replica_read_from_primary?
|
59
|
+
# Read from primary when forced by thread variable, or
|
60
|
+
# in a transaction and not ignoring transactions
|
61
|
+
ActiveRecordReplica.read_from_primary? ||
|
62
|
+
(open_transactions > 0) && !ActiveRecordReplica.ignore_transactions?
|
63
|
+
end
|
64
|
+
end
|
65
|
+
end
|
@@ -0,0 +1,24 @@
|
|
1
|
+
module ActiveRecordReplica
|
2
|
+
class Railtie < Rails::Railtie
|
3
|
+
# Make the ActiveRecordReplica configuration available in the Rails application config
|
4
|
+
#
|
5
|
+
# Example: For this application ignore the current transactions since the application
|
6
|
+
# has been coded to use ActiveRecordReplica.read_from_primary whenever
|
7
|
+
# the current transaction must be visible to reads.
|
8
|
+
# In file config/application.rb
|
9
|
+
#
|
10
|
+
# Rails::Application.configure do
|
11
|
+
# # Read from replica even when in an active transaction
|
12
|
+
# # The application will use ActiveRecordReplica.read_from_primary to make
|
13
|
+
# # changes in the current transaction visible to reads
|
14
|
+
# config.active_record_replica.ignore_transactions = true
|
15
|
+
# end
|
16
|
+
config.active_record_replica = ::ActiveRecordReplica
|
17
|
+
|
18
|
+
# Initialize ActiveRecordReplica
|
19
|
+
initializer "load active_record_replica", after: "active_record.initialize_database" do
|
20
|
+
ActiveRecordReplica.install!
|
21
|
+
end
|
22
|
+
|
23
|
+
end
|
24
|
+
end
|
@@ -0,0 +1,12 @@
|
|
1
|
+
module ActiveRecordReplica
|
2
|
+
# Class to hold replica connection pool
|
3
|
+
class Replica < ActiveRecord::Base
|
4
|
+
# Prevent Rails from trying to create an instance of this model
|
5
|
+
self.abstract_class = true
|
6
|
+
|
7
|
+
# Since this is an abstract class so it has no columns
|
8
|
+
def self.columns
|
9
|
+
[]
|
10
|
+
end
|
11
|
+
end
|
12
|
+
end
|
@@ -0,0 +1,150 @@
|
|
1
|
+
require File.join(File.dirname(__FILE__), 'test_helper')
|
2
|
+
require 'logger'
|
3
|
+
require 'erb'
|
4
|
+
|
5
|
+
l = Logger.new('test.log')
|
6
|
+
l.level = ::Logger::DEBUG
|
7
|
+
ActiveRecord::Base.logger = l
|
8
|
+
ActiveRecord::Base.configurations = YAML::load(ERB.new(IO.read('test/database.yml')).result)
|
9
|
+
|
10
|
+
# Define Schema in second database (replica)
|
11
|
+
# Note: This is not be required when the primary database is being replicated to the replica db
|
12
|
+
ActiveRecord::Base.establish_connection(ActiveRecord::Base.configurations['test']['replica'])
|
13
|
+
|
14
|
+
# Create table users in database active_record_replica_test
|
15
|
+
ActiveRecord::Schema.define :version => 0 do
|
16
|
+
create_table :users, :force => true do |t|
|
17
|
+
t.string :name
|
18
|
+
t.string :address
|
19
|
+
end
|
20
|
+
end
|
21
|
+
|
22
|
+
# Define Schema in primary database
|
23
|
+
ActiveRecord::Base.establish_connection(:test)
|
24
|
+
|
25
|
+
# Create table users in database active_record_replica_test
|
26
|
+
ActiveRecord::Schema.define :version => 0 do
|
27
|
+
create_table :users, :force => true do |t|
|
28
|
+
t.string :name
|
29
|
+
t.string :address
|
30
|
+
end
|
31
|
+
end
|
32
|
+
|
33
|
+
# AR Model
|
34
|
+
class User < ActiveRecord::Base
|
35
|
+
end
|
36
|
+
|
37
|
+
# Install ActiveRecord replica. Done automatically by railtie in a Rails environment
|
38
|
+
# Also tell it to use the test environment since Rails.env is not available
|
39
|
+
ActiveRecordReplica.install!(nil, 'test')
|
40
|
+
|
41
|
+
#
|
42
|
+
# Unit Test for active_record_replica
|
43
|
+
#
|
44
|
+
# Since their is no database replication in this test environment, it will
|
45
|
+
# use 2 separate databases. Writes go to the first database and reads to the second.
|
46
|
+
# As a result any writes to the first database will not be visible when trying to read from
|
47
|
+
# the second test database.
|
48
|
+
class ActiveRecordReplicaTest < Minitest::Test
|
49
|
+
describe 'the active_record_replica gem' do
|
50
|
+
|
51
|
+
before do
|
52
|
+
ActiveRecordReplica.ignore_transactions = false
|
53
|
+
|
54
|
+
User.delete_all
|
55
|
+
|
56
|
+
@name = "Joe Bloggs"
|
57
|
+
@address = "Somewhere"
|
58
|
+
@user = User.new(
|
59
|
+
:name => @name,
|
60
|
+
:address => @address
|
61
|
+
)
|
62
|
+
end
|
63
|
+
|
64
|
+
after do
|
65
|
+
User.delete_all
|
66
|
+
end
|
67
|
+
|
68
|
+
it 'saves to primary' do
|
69
|
+
assert_equal true, @user.save!
|
70
|
+
end
|
71
|
+
|
72
|
+
#
|
73
|
+
# NOTE:
|
74
|
+
#
|
75
|
+
# There is no automated replication between the SQL lite databases
|
76
|
+
# so the tests will be verifying that reads going to the "replica" (second)
|
77
|
+
# database do not find data written to the primary.
|
78
|
+
#
|
79
|
+
it 'saves to primary, read from replica' do
|
80
|
+
# Read from replica
|
81
|
+
assert_equal 0, User.where(:name => @name, :address => @address).count
|
82
|
+
|
83
|
+
# Write to primary
|
84
|
+
assert_equal true, @user.save!
|
85
|
+
|
86
|
+
# Read from replica
|
87
|
+
assert_equal 0, User.where(:name => @name, :address => @address).count
|
88
|
+
end
|
89
|
+
|
90
|
+
it 'save to primary, read from primary when in a transaction' do
|
91
|
+
assert_equal false, ActiveRecordReplica.ignore_transactions?
|
92
|
+
|
93
|
+
User.transaction do
|
94
|
+
# The delete_all in setup should have cleared the table
|
95
|
+
assert_equal 0, User.count
|
96
|
+
|
97
|
+
# Read from Primary
|
98
|
+
assert_equal 0, User.where(:name => @name, :address => @address).count
|
99
|
+
|
100
|
+
# Write to primary
|
101
|
+
assert_equal true, @user.save!
|
102
|
+
|
103
|
+
# Read from Primary
|
104
|
+
assert_equal 1, User.where(:name => @name, :address => @address).count
|
105
|
+
end
|
106
|
+
|
107
|
+
# Read from Non-replicated replica
|
108
|
+
assert_equal 0, User.where(:name => @name, :address => @address).count
|
109
|
+
end
|
110
|
+
|
111
|
+
it 'save to primary, read from replica when ignoring transactions' do
|
112
|
+
ActiveRecordReplica.ignore_transactions = true
|
113
|
+
assert_equal true, ActiveRecordReplica.ignore_transactions?
|
114
|
+
|
115
|
+
User.transaction do
|
116
|
+
# The delete_all in setup should have cleared the table
|
117
|
+
assert_equal 0, User.count
|
118
|
+
|
119
|
+
# Read from Primary
|
120
|
+
assert_equal 0, User.where(:name => @name, :address => @address).count
|
121
|
+
|
122
|
+
# Write to primary
|
123
|
+
assert_equal true, @user.save!
|
124
|
+
|
125
|
+
# Read from Non-replicated replica
|
126
|
+
assert_equal 0, User.where(:name => @name, :address => @address).count
|
127
|
+
end
|
128
|
+
|
129
|
+
# Read from Non-replicated replica
|
130
|
+
assert_equal 0, User.where(:name => @name, :address => @address).count
|
131
|
+
end
|
132
|
+
|
133
|
+
it 'saves to primary, force a read from primary even when _not_ in a transaction' do
|
134
|
+
# Read from replica
|
135
|
+
assert_equal 0, User.where(:name => @name, :address => @address).count
|
136
|
+
|
137
|
+
# Write to primary
|
138
|
+
assert_equal true, @user.save!
|
139
|
+
|
140
|
+
# Read from replica
|
141
|
+
assert_equal 0, User.where(:name => @name, :address => @address).count
|
142
|
+
|
143
|
+
# Read from Primary
|
144
|
+
ActiveRecordReplica.read_from_primary do
|
145
|
+
assert_equal 1, User.where(:name => @name, :address => @address).count
|
146
|
+
end
|
147
|
+
end
|
148
|
+
|
149
|
+
end
|
150
|
+
end
|
data/test/database.yml
ADDED
@@ -0,0 +1,12 @@
|
|
1
|
+
test:
|
2
|
+
adapter: sqlite3
|
3
|
+
database: test/test.sqlite3
|
4
|
+
pool: 5
|
5
|
+
timeout: 5000
|
6
|
+
# Make the replica a separate database that is not replicad to ensure reads
|
7
|
+
# and writes go to the appropriate databases
|
8
|
+
replica:
|
9
|
+
adapter: sqlite3
|
10
|
+
database: test/test_replica.sqlite3
|
11
|
+
pool: 5
|
12
|
+
timeout: 5000
|
data/test/test.sqlite3
ADDED
Binary file
|
data/test/test_helper.rb
ADDED
Binary file
|
metadata
ADDED
@@ -0,0 +1,84 @@
|
|
1
|
+
--- !ruby/object:Gem::Specification
|
2
|
+
name: active_record_replica
|
3
|
+
version: !ruby/object:Gem::Version
|
4
|
+
version: 2.0.1
|
5
|
+
platform: ruby
|
6
|
+
authors:
|
7
|
+
- Reid Morrison
|
8
|
+
autorequire:
|
9
|
+
bindir: bin
|
10
|
+
cert_chain: []
|
11
|
+
date: 2020-06-14 00:00:00.000000000 Z
|
12
|
+
dependencies:
|
13
|
+
- !ruby/object:Gem::Dependency
|
14
|
+
name: activerecord
|
15
|
+
requirement: !ruby/object:Gem::Requirement
|
16
|
+
requirements:
|
17
|
+
- - ">="
|
18
|
+
- !ruby/object:Gem::Version
|
19
|
+
version: '3.0'
|
20
|
+
- - "<"
|
21
|
+
- !ruby/object:Gem::Version
|
22
|
+
version: 6.0.0
|
23
|
+
type: :runtime
|
24
|
+
prerelease: false
|
25
|
+
version_requirements: !ruby/object:Gem::Requirement
|
26
|
+
requirements:
|
27
|
+
- - ">="
|
28
|
+
- !ruby/object:Gem::Version
|
29
|
+
version: '3.0'
|
30
|
+
- - "<"
|
31
|
+
- !ruby/object:Gem::Version
|
32
|
+
version: 6.0.0
|
33
|
+
description:
|
34
|
+
email:
|
35
|
+
- reidmo@gmail.com
|
36
|
+
executables: []
|
37
|
+
extensions: []
|
38
|
+
extra_rdoc_files: []
|
39
|
+
files:
|
40
|
+
- LICENSE.txt
|
41
|
+
- README.md
|
42
|
+
- Rakefile
|
43
|
+
- lib/active_record_replica.rb
|
44
|
+
- lib/active_record_replica/active_record_replica.rb
|
45
|
+
- lib/active_record_replica/errors.rb
|
46
|
+
- lib/active_record_replica/extensions.rb
|
47
|
+
- lib/active_record_replica/railtie.rb
|
48
|
+
- lib/active_record_replica/replica.rb
|
49
|
+
- lib/active_record_replica/version.rb
|
50
|
+
- test/active_record_replica_test.rb
|
51
|
+
- test/database.yml
|
52
|
+
- test/test.sqlite3
|
53
|
+
- test/test_helper.rb
|
54
|
+
- test/test_replica.sqlite3
|
55
|
+
homepage: https://github.com/rocketjob/active_record_replica
|
56
|
+
licenses:
|
57
|
+
- Apache-2.0
|
58
|
+
metadata: {}
|
59
|
+
post_install_message:
|
60
|
+
rdoc_options: []
|
61
|
+
require_paths:
|
62
|
+
- lib
|
63
|
+
required_ruby_version: !ruby/object:Gem::Requirement
|
64
|
+
requirements:
|
65
|
+
- - ">="
|
66
|
+
- !ruby/object:Gem::Version
|
67
|
+
version: '2.0'
|
68
|
+
required_rubygems_version: !ruby/object:Gem::Requirement
|
69
|
+
requirements:
|
70
|
+
- - ">="
|
71
|
+
- !ruby/object:Gem::Version
|
72
|
+
version: '0'
|
73
|
+
requirements: []
|
74
|
+
rubygems_version: 3.0.3
|
75
|
+
signing_key:
|
76
|
+
specification_version: 4
|
77
|
+
summary: Redirect ActiveRecord (Rails) reads to replica databases while ensuring all
|
78
|
+
writes go to the primary database.
|
79
|
+
test_files:
|
80
|
+
- test/database.yml
|
81
|
+
- test/test_helper.rb
|
82
|
+
- test/test.sqlite3
|
83
|
+
- test/active_record_replica_test.rb
|
84
|
+
- test/test_replica.sqlite3
|