Uploaded image for project: 'Mongoid'
  1. Mongoid
  2. MONGOID-5138

Assign persistence context to Mongoid::Criteria

    • Type: Icon: Improvement Improvement
    • Resolution: Unresolved
    • Priority: Icon: Unknown Unknown
    • None
    • Affects Version/s: None
    • Component/s: None
    • Labels:
      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.

            Assignee:
            Unassigned Unassigned
            Reporter:
            shields@tablecheck.com Johnny Shields
            Votes:
            0 Vote for this issue
            Watchers:
            2 Start watching this issue

              Created:
              Updated: