2
0
Fork 0
mirror of https://github.com/discourse/discourse.git synced 2025-10-04 17:32:34 +08:00
discourse/spec/initializers/000_pg_connection_patch_spec.rb
Alan Guo Xiang Tan a406316dde
DEV: Patch ActiveRecord's postgresql adapter .new_client (#33820)
This commit updates our monkey patch of
`ActiveRecord::ConnectionAdapters::PostgreSQLAdapter.new_client` to
improve two things:

1. Improve the conditional used to determine if a database does not
   exist. Just checking that the error message contains the `database`
name is not sufficient as the value of the database name may be part of
the `host` connection param which can appear in PG error messages as
well.

2. When the PG error messages includes the `user` or `host` connection
   param. We append the original PG error message on to the original
error messge so that we don't just end up with a generic error message
that doesn't help us to figure out the actual error.
2025-09-18 11:34:37 +08:00

43 lines
1.5 KiB
Ruby

# frozen_string_literal: true
RSpec.describe "Patching ActiveRecord::ConnectionAdapters::PostgreSQLAdapter#new_client" do
it "raises ActiveRecord::NoDatabaseError for a missing database" do
conn_params = { dbname: "non_existent_db" }
expect do
ActiveRecord::ConnectionAdapters::PostgreSQLAdapter.new_client(conn_params)
end.to raise_error(ActiveRecord::NoDatabaseError, /non_existent_db/)
end
it "raises ActiveRecord::DatabaseConnectionError when error message contains the `host` connection params" do
conn_params = { host: "some-host", user: "test_user" }
PG.expects(:connect).raises(
::PG::Error.new(
"connection to server at \"some-host.name\" (::1), port 6432 failed: timeout expired after 11.30376464s",
),
)
expect do
ActiveRecord::ConnectionAdapters::PostgreSQLAdapter.new_client(conn_params)
end.to raise_error(
ActiveRecord::DatabaseConnectionError,
/connection to server at "some-host.name"/,
)
end
it "raises ActiveRecord::DatabaseConnectionError when error message contains the `user` connection params" do
conn_params = { user: "test_user" }
PG.expects(:connect).raises(
::PG::Error.new("FATAL: password authentication failed for user \"test_user\""),
)
expect do
ActiveRecord::ConnectionAdapters::PostgreSQLAdapter.new_client(conn_params)
end.to raise_error(
ActiveRecord::DatabaseConnectionError,
/password authentication failed for user "test_user"/,
)
end
end