Skip to content

Commit

Permalink
Add new exception when attempting to connect to MySQL running on loca…
Browse files Browse the repository at this point in the history
…lhost.

Add test to MySQL connection error on localhost via socket.

Address Rubocop warnings.

Update CHANGELOG.
  • Loading branch information
ruyrocha committed Jan 29, 2024
1 parent 4816684 commit 4ee3694
Show file tree
Hide file tree
Showing 4 changed files with 27 additions and 1 deletion.
6 changes: 6 additions & 0 deletions activerecord/CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,3 +1,9 @@
* Raise new exception when connecting to MySQL on `localhost` and it attempts to connect via a socket.

This issue does not happen with TrilogyAdapter.

*Ruy Rocha*

* Fix single quote escapes on default generated MySQL columns

MySQL 5.7.5+ supports generated columns, which can be used to create a column that is computed from an expression.
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -140,7 +140,11 @@ def text_type?(type)
def connect
@raw_connection = self.class.new_client(@connection_parameters)
rescue ConnectionNotEstablished => ex
raise ex.set_pool(@pool)
if ex.message.include?("Can't connect to local server through socket") && @connection_parameters[:host] == "localhost"
raise CannotConnectThroughSocketOnLocalhost
else
raise ex.set_pool(@pool)
end
end

def reconnect
Expand Down
10 changes: 10 additions & 0 deletions activerecord/lib/active_record/errors.rb
Original file line number Diff line number Diff line change
Expand Up @@ -88,6 +88,16 @@ def set_pool(connection_pool)
class ConnectionTimeoutError < ConnectionNotEstablished
end

# Raised when a connection could not be obtained to the server running
# on localhost because it attempts to connect through a socket.
class CannotConnectThroughSocketOnLocalhost < ConnectionNotEstablished
def initialize(message = nil, connection_pool: nil)
message = "The MySQL client library translates localhost address to a socket, so try to explicitly use the IP address (127.0.0.1) instead."

super(message, connection_pool: connection_pool)
end
end

# Raised when connection to the database could not been established because it was not
# able to connect to the host or when the authorization failed.
class DatabaseConnectionError < ConnectionNotEstablished
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,12 @@ def test_connection_error
assert_kind_of ActiveRecord::ConnectionAdapters::NullPool, error.connection_pool
end

def test_connection_error_via_socket_on_localhost
assert_raises ActiveRecord::CannotConnectThroughSocketOnLocalhost do
ActiveRecord::ConnectionAdapters::Mysql2Adapter.new(host: "localhost", prepared_statements: false).connect!
end
end

def test_reconnection_error
fake_connection = Class.new do
def query_options
Expand Down

0 comments on commit 4ee3694

Please sign in to comment.