Skip to content

Commit 7fac5d1

Browse files
authored
Merge pull request rails#53400 from wata727/translate_no_connection_to_not_established
Translate `no connection to the server` to ConnectionNotEstablished
2 parents df282d0 + d0edda3 commit 7fac5d1

File tree

3 files changed

+21
-1
lines changed

3 files changed

+21
-1
lines changed

activerecord/CHANGELOG.md

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,2 +1,5 @@
1+
* `PG::UnableToSend: no connection to the server` is now retryable as a connection-related exception
2+
3+
*Kazuma Watanabe*
14

25
Please check [8-0-stable](https://github.com/rails/rails/blob/8-0-stable/activerecord/CHANGELOG.md) for previous changes.

activerecord/lib/active_record/connection_adapters/postgresql_adapter.rb

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -798,7 +798,7 @@ def translate_exception(exception, message:, sql:, binds:)
798798

799799
case exception.result.try(:error_field, PG::PG_DIAG_SQLSTATE)
800800
when nil
801-
if exception.message.match?(/connection is closed/i)
801+
if exception.message.match?(/connection is closed/i) || exception.message.match?(/no connection to the server/i)
802802
ConnectionNotEstablished.new(exception, connection_pool: @pool)
803803
elsif exception.is_a?(PG::ConnectionBad)
804804
# libpq message style always ends with a newline; the pg gem's internal

activerecord/test/cases/adapters/postgresql/postgresql_adapter_test.rb

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -474,6 +474,23 @@ def test_raise_error_when_cannot_translate_exception
474474
end
475475
end
476476

477+
def test_translate_no_connection_exception_to_not_established
478+
pid = @connection.execute("SELECT pg_backend_pid()").to_a[0]["pg_backend_pid"]
479+
@connection.pool.checkout.execute("SELECT pg_terminate_backend(#{pid})")
480+
# If you run `@connection.execute` after the backend process has been terminated,
481+
# you will get the "server closed the connection unexpectedly" rather than "no connection to the server".
482+
# Because what we want to test here is an error that occurs during `send_query`,
483+
# which is called internally by `@connection.execute`, we will call it explicitly.
484+
# The `send_query` changes the internal `PG::Connection#status` to `CONNECTION_BAD`,
485+
# so any subsequent queries will get the "no connection to the server" error.
486+
# https://github.com/postgres/postgres/blob/REL_17_0/src/interfaces/libpq/fe-exec.c#L1686-L1691
487+
@connection.instance_variable_get(:@raw_connection).send_query("SELECT 1")
488+
489+
assert_raise ActiveRecord::ConnectionNotEstablished do
490+
@connection.execute("SELECT 1")
491+
end
492+
end
493+
477494
def test_reload_type_map_for_newly_defined_types
478495
@connection.create_enum "feeling", ["good", "bad"]
479496

0 commit comments

Comments
 (0)