influitive / apartment

Database multi-tenancy for Rack (and Rails) applications
2.67k stars 463 forks source link

Allow a list of schemas when switching using schemas #568

Open ryanbrunner opened 5 years ago

ryanbrunner commented 5 years ago

This PR adds the ability to switch to a list of tenants rather than a single tenant.

The reason you may want to do this is to support a partial schema. If you create a schema that contains some of the tables present in a customer schema, you can use Apartment to prefer the partial schema when retrieving or modifying data, but falling back to the "main" customer schema when a table isn't present.

For example, if Schema A contained the following tables:

foo
bar

and Schema B contained the following tables:

foo
bar
baz

then calls to Foo and Bar would access Schema A, while calls to Baz would access Schema B:

Apartment::Tenant.switch(['foo', 'bar']) do
  Foo.all # from Schema A
  Bar.all # from Schema A
  Baz.all # from Schema B
end

We use this to create a "context" where some tables can be updated while other tables continue to utilize the main tables. This can simulate the effect of a transaction by allowing a table to be populated in a staging schema prior to it being committed to the main schema.