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.

Move exception to MySQL2 adapter.
  • Loading branch information
ruyrocha committed Jan 30, 2024
1 parent 9b4fd90 commit 556ecae
Show file tree
Hide file tree
Showing 3 changed files with 28 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 @@ -20,6 +20,17 @@ class Mysql2Adapter < AbstractMysqlAdapter

include Mysql2::DatabaseStatements

# Raised when a connection could not be obtained to the server running
# on localhost because it attempts to connect through a socket.
CannotConnectThroughSocketOnLocalhost = Class.new(ConnectionNotEstablished) do
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

class << self
def new_client(config)
::Mysql2::Client.new(config)
Expand Down Expand Up @@ -140,7 +151,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.match?(/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
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::ConnectionAdapters::Mysql2Adapter::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 556ecae

Please sign in to comment.