Question

I want to be able to switch between different DB schemas in a Rails 4 app.

The plan is to add a new middleware in the very beginning of the stack that will do that for me.

The only way to do it is by setting ActiveRecord::Base.connection.schema_search_path = '"$user",my_schema'.

The problem I have with this is that this connection will go to the pool and all the following requests will use the schema that was set in the first one (basically leaking it through).

So the solution I see is to always reset the search path to what it was before and always set it on each request.

But I don't want to do this because:

  • 99% of the requests will go to the default (public) schema, executing set search_path to '$user$,my_schema' would be additional query that could have been avoided
  • higher risk of leaking (other middleware may establish the connection earlier, or some changes to Rails or gems outside of my control)

All that especially applies to threaded servers, like Puma.

So are there any better alternatives to my solution with a middleware?

Thanks.

Était-ce utile?

La solution

When you return connections to the pool, you must ensure the pool runs DISCARD ALL; to reset the connection state.

That will clear any SET ROLE, SET SESSION AUTHORIZATION, session variables, search_path setting, etc.

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top