Skip to content

Commit

Permalink
Raise helpful error when role doesn't exist
Browse files Browse the repository at this point in the history
If you try to call `connected_to` with a role that doesn't have an
established connection you used to get an error that said:

```
>> ActiveRecord::Base.connected_to(role: :i_dont_exist) { Home.first }

ActiveRecord::ConnectionNotEstablished Exception: No connection pool
with 'primary' found.
```

This is confusing because the connection could be established but we
spelled the role wrong.

I've changed this to raise if the `role` used in `connected_to` doesn't
have an associated handler. Users who encounter this should either check
that the role is spelled correctly (writin -> writing), establish a
connection to that role in the model with connects_to, or use the
`database` keyword for the `role`.

I think this will provide a less confusing error message for those
starting out with multiple databases.
  • Loading branch information
eileencodes committed Dec 21, 2018
1 parent abae9d0 commit 22a1265
Show file tree
Hide file tree
Showing 3 changed files with 19 additions and 0 deletions.
4 changes: 4 additions & 0 deletions activerecord/lib/active_record/connection_handling.rb
Expand Up @@ -158,6 +158,10 @@ def lookup_connection_handler(handler_key) # :nodoc:
end

def with_handler(handler_key, &blk) # :nodoc:
unless ActiveRecord::Base.connection_handlers.keys.include?(handler_key)
raise ArgumentError, "The #{handler_key} role does not exist. Add it by establishing a connection with `connects_to` or use an existing role (#{ActiveRecord::Base.connection_handlers.keys.join(", ")})."
end

handler = lookup_connection_handler(handler_key)
swap_connection_handler(handler, &blk)
end
Expand Down
Expand Up @@ -328,6 +328,16 @@ def test_connection_handlers_swapping_connections_in_fiber
ensure
ActiveRecord::Base.connection_handlers = original_handlers
end

def test_calling_connected_to_on_a_non_existent_handler_raises
error = assert_raises ArgumentError do
ActiveRecord::Base.connected_to(role: :reading) do
yield
end
end

assert_equal "The reading role does not exist. Add it by establishing a connection with `connects_to` or use an existing role (writing).", error.message
end
end
end
end
5 changes: 5 additions & 0 deletions activerecord/test/cases/query_cache_test.rb
Expand Up @@ -56,6 +56,11 @@ def test_exceptional_middleware_clears_and_disables_cache_on_error
end

def test_query_cache_is_applied_to_connections_in_all_handlers
ActiveRecord::Base.connection_handlers = {
writing: ActiveRecord::Base.default_connection_handler,
reading: ActiveRecord::ConnectionAdapters::ConnectionHandler.new
}

ActiveRecord::Base.connected_to(role: :reading) do
ActiveRecord::Base.establish_connection(ActiveRecord::Base.configurations["arunit"])
end
Expand Down

0 comments on commit 22a1265

Please sign in to comment.