Skip to content

Commit

Permalink
Merge pull request rails#53400 from wata727/translate_no_connection_t…
Browse files Browse the repository at this point in the history
…o_not_established

Translate `no connection to the server` to ConnectionNotEstablished
  • Loading branch information
byroot authored Oct 24, 2024
2 parents df282d0 + d0edda3 commit 7fac5d1
Show file tree
Hide file tree
Showing 3 changed files with 21 additions and 1 deletion.
3 changes: 3 additions & 0 deletions activerecord/CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,2 +1,5 @@
* `PG::UnableToSend: no connection to the server` is now retryable as a connection-related exception

*Kazuma Watanabe*

Please check [8-0-stable](https://github.com/rails/rails/blob/8-0-stable/activerecord/CHANGELOG.md) for previous changes.
Original file line number Diff line number Diff line change
Expand Up @@ -798,7 +798,7 @@ def translate_exception(exception, message:, sql:, binds:)

case exception.result.try(:error_field, PG::PG_DIAG_SQLSTATE)
when nil
if exception.message.match?(/connection is closed/i)
if exception.message.match?(/connection is closed/i) || exception.message.match?(/no connection to the server/i)
ConnectionNotEstablished.new(exception, connection_pool: @pool)
elsif exception.is_a?(PG::ConnectionBad)
# libpq message style always ends with a newline; the pg gem's internal
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -474,6 +474,23 @@ def test_raise_error_when_cannot_translate_exception
end
end

def test_translate_no_connection_exception_to_not_established
pid = @connection.execute("SELECT pg_backend_pid()").to_a[0]["pg_backend_pid"]
@connection.pool.checkout.execute("SELECT pg_terminate_backend(#{pid})")
# If you run `@connection.execute` after the backend process has been terminated,
# you will get the "server closed the connection unexpectedly" rather than "no connection to the server".
# Because what we want to test here is an error that occurs during `send_query`,
# which is called internally by `@connection.execute`, we will call it explicitly.
# The `send_query` changes the internal `PG::Connection#status` to `CONNECTION_BAD`,
# so any subsequent queries will get the "no connection to the server" error.
# https://github.com/postgres/postgres/blob/REL_17_0/src/interfaces/libpq/fe-exec.c#L1686-L1691
@connection.instance_variable_get(:@raw_connection).send_query("SELECT 1")

assert_raise ActiveRecord::ConnectionNotEstablished do
@connection.execute("SELECT 1")
end
end

def test_reload_type_map_for_newly_defined_types
@connection.create_enum "feeling", ["good", "bad"]

Expand Down

0 comments on commit 7fac5d1

Please sign in to comment.