-
Type: Improvement
-
Resolution: Unresolved
-
Priority: Unknown
-
None
-
Affects Version/s: None
-
Component/s: None
-
None
Background
To most efficiently use my DB servers in a large app serving millions of requests daily, it is important that I have fine grained control over reading from secondaries versus primaries. Because there can be several seconds of replication lag, bugs can result when I accidently read from a secondary when I meant to read from the primary. Mongoid should provide abstractions that minimize the possibility for error.
Request
Currently, Mongoid::Criteria objects created in a #with persistence block do not retain their `persistence_context` outside the block.
MyModel.with(read: {mode: :primary}) do
criteria = MyModel.all
criteria.persistence_context #=> @options={:read=>{:mode=>:primary}}
end
criteria.persistence_context #=> @options={}
Criteria are meant to be chained/lazy evaluated, so a developer is likely to make the following mistake (my team did )
def users_from_primary User.with(read: {mode: :primary}) { User.all } end users_from_primary.active.logged_in_today #=> doesn't read from primary!
I would like to propose the following:
1. Allow settings the persistence options directly on the Criteria, i.e. Criteria#persistence_options(read: {mode: :primary})
2. Add a method to reset the context i.e. Criteria#reset_persistence, which resets it to the Model.with scope in which it is called.
3. When creating new Criteria, the persistence should be initialized based on the current Model.with scope, but should stay as an instance variable on the Criteria outside the scope.
#1 and #2 would be new functionality so they would not affect existing users. #3 could be enabled by a global Mongoid setting option (opt-in for now, until the next major release.)
Please let me know if you would accept a PR for this proposal.
- is related to
-
MONGOID-5472 Save models using the overridden persistence context used for their loading
- Closed
- related to
-
MONGOID-4629 Non-block form of persistence context #with
- Backlog