Skip to content

Commit

Permalink
Allow a list of schemas when switching using schemas
Browse files Browse the repository at this point in the history
  • Loading branch information
Ryan Brunner committed Oct 5, 2018
1 parent a4332c3 commit 65ec5c1
Show file tree
Hide file tree
Showing 3 changed files with 21 additions and 2 deletions.
8 changes: 8 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -89,6 +89,14 @@ would not allow a full new database to be created.

One can optionally use the full database creation instead if they want, though this is not recommended

When using schemas, you can also pass in a list of schemas if desired. Any tables defined in a schema earlier in the chain will be referenced first, so this is only useful if you have a schema with only some of the tables defined:

```ruby
Apartment::Tenant.switch(['tenant_1', 'tenant_2']) do
# ...
end
```

### Switching Tenants

To switch tenants using Apartment, use the following command:
Expand Down
8 changes: 6 additions & 2 deletions lib/apartment/adapters/postgresql_adapter.rb
Original file line number Diff line number Diff line change
Expand Up @@ -63,9 +63,9 @@ def drop_command(conn, tenant)
#
def connect_to_new(tenant = nil)
return reset if tenant.nil?
raise ActiveRecord::StatementInvalid.new("Could not find schema #{tenant}") unless Apartment.connection.schema_exists?(tenant.to_s)
raise ActiveRecord::StatementInvalid.new("Could not find schema #{tenant}") unless schema_exists?(tenant)

@current = tenant.to_s
@current = tenant.is_a?(Array) ? tenant.map(&:to_s) : tenant.to_s
Apartment.connection.schema_search_path = full_search_path

# When the PostgreSQL version is < 9.3,
Expand Down Expand Up @@ -100,6 +100,10 @@ def postgresql_version
# public from Rails 5.0.
Apartment.connection.send(:postgresql_version)
end

def schema_exists?(schemas)
[*schemas].all? { |schema| Apartment.connection.schema_exists?(schema.to_s) }
end
end

# Another Adapter for Postgresql when using schemas and SQL
Expand Down
7 changes: 7 additions & 0 deletions spec/examples/schema_adapter_examples.rb
Original file line number Diff line number Diff line change
Expand Up @@ -122,6 +122,13 @@

expect(connection.schema_search_path).to start_with %{"#{public_schema}"}
end

it "allows a list of schemas" do
subject.switch([schema1, schema2]) do
expect(connection.schema_search_path).to include %{"#{schema1}"}
expect(connection.schema_search_path).to include %{"#{schema2}"}
end
end
end

describe "#reset" do
Expand Down

0 comments on commit 65ec5c1

Please sign in to comment.