Feature request: AR namespace for schemas in queries

Hi. I was thinking in the possibility to set a namespace for tables in AR queries, so instead of setting the search path like this:

ActiveRecord::Base.connection.schema_search_path = ‘foo, public’

We specify the schema in the query:

select * from foo.bar;

so it could be a thread-safe solution and work with multi-thread environments and improve Rails support for real multi-tenant apps using Postgres schemas. What do you guys think?

This is achievable by setting the table in the model Bar to foo.bar, is that what you meant?

Can I do this dinamically and is it thread-safe?

I guess you want to implement some kind of multi-tenant application using PG separate schemas for each tenant.

In that case, if your application uses a single thread per request you should be able to achieve that by using an around filter to set the search path.

I think this is the easiest way to achieve what you want if I guessed it correctly.

Yes. Actually I’m using a before filter and setting it per requisition. I think it will work because I’m using Unicorn. But I’m curious why are you suggesting an around filter, what should I do after the action? I think I’m missing something.

For ActiveRecord it's okay to use a before filter rather than an around one. But for Sequel you'd probably need to call "with_connection {|c| ...}".

Since ActiveRecord will reserve the connection for the full request cycle, you're okay with using a before filter as long as you don't spawn new threads using the database in your request main thread.

Even if you're not using a multi-process server (like Unicorn) it should just work fine in the conditions stated above.

Cheers.

Also, there's another catch. Some people implementing this pattern prefer to rollback the value for the search_path to the previous value once the request is completed. In that case you'd want to use an around filter with a begin-finally block.

But if you always set the search_path for all requests, then this is not absolutely required for AR.

Got it. Your answers were very helpful, thanks a lot!