Skip to content

Commit e26ef1e

Browse files
authored
Merge pull request rails#54713 from joshuay03/handle-libpq-server-version-0
Handle libpq db version 0 as connection failure in `PostgreSQLAdapter`
2 parents ba6f20a + 2db3645 commit e26ef1e

File tree

2 files changed

+25
-1
lines changed

2 files changed

+25
-1
lines changed

activerecord/lib/active_record/connection_adapters/postgresql_adapter.rb

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -634,7 +634,11 @@ def use_insert_returning?
634634
# Returns the version of the connected PostgreSQL server.
635635
def get_database_version # :nodoc:
636636
with_raw_connection do |conn|
637-
conn.server_version
637+
version = conn.server_version
638+
if version == 0
639+
raise ActiveRecord::ConnectionFailed, "Could not determine PostgreSQL version"
640+
end
641+
version
638642
end
639643
end
640644
alias :postgresql_version :database_version

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

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -95,6 +95,26 @@ def test_bad_connection_to_postgres_database
9595
end
9696
end
9797

98+
def test_reconnect_after_bad_connection_on_check_version
99+
db_config = ActiveRecord::Base.configurations.configs_for(env_name: "arunit", name: "primary")
100+
connection = ActiveRecord::ConnectionAdapters::PostgreSQLAdapter.new(db_config.configuration_hash.merge(connection_retries: 0))
101+
connection.connect!
102+
103+
# mimic a connection that hasn't checked and cached the server version yet i.e. without a raw_connection
104+
connection.pool.instance_variable_set(:@server_version, nil)
105+
connection.raw_connection.stub(:server_version, 0) do
106+
error = assert_raises ActiveRecord::ConnectionFailed do
107+
connection.reconnect!
108+
end
109+
assert_equal "Could not determine PostgreSQL version", error.message
110+
end
111+
112+
# can reconnect after a bad connection
113+
assert_nothing_raised do
114+
connection.reconnect!
115+
end
116+
end
117+
98118
def test_database_exists_returns_false_when_the_database_does_not_exist
99119
config = { database: "non_extant_database", adapter: "postgresql" }
100120
assert_not ActiveRecord::ConnectionAdapters::PostgreSQLAdapter.database_exists?(config),

0 commit comments

Comments
 (0)