Skip to content

A platform for community discussion. Free, open, simple.

DEV: Patch ActiveRecord's postgresql adapter `.new_client` (#33820)

Alan Guo Xiang Tana406316dde89
diff --git a/config/initializers/000-pg-connection-debug.rb b/config/initializers/000-pg-connection-debug.rb
deleted file mode 100644
index c26f1e59ab9..00000000000
--- a/config/initializers/000-pg-connection-debug.rb
+++ /dev/null
@@ -1,23 +0,0 @@
-# frozen_string_literal: true
-
-class ActiveRecord::ConnectionAdapters::PostgreSQLAdapter
- def self.new_client(conn_params)
- start = Time.now()
- PG.connect(**conn_params)
- rescue ::PG::Error => error
- if conn_params && conn_params[:dbname] == "postgres"
- raise ActiveRecord::ConnectionNotEstablished, error.message
- elsif conn_params && conn_params[:dbname] && error.message.include?(conn_params[:dbname])
- Rails.logger.error(
- "DebuggingNoDatabaseError: #{error.message} after #{Time.now() - start}s\n#{error.backtrace.join("\n")}",
- )
- raise ActiveRecord::NoDatabaseError.db_error(conn_params[:dbname])
- elsif conn_params && conn_params[:user] && error.message.include?(conn_params[:user])
- raise ActiveRecord::DatabaseConnectionError.username_error(conn_params[:user])
- elsif conn_params && conn_params[:host] && error.message.include?(conn_params[:host])
- raise ActiveRecord::DatabaseConnectionError.hostname_error(conn_params[:host])
- else
- raise ActiveRecord::ConnectionNotEstablished, error.message
- end
- end
-end
diff --git a/config/initializers/000-pg_connection_patch.rb b/config/initializers/000-pg_connection_patch.rb
new file mode 100644
index 00000000000..bde7c786d15
--- /dev/null
+++ b/config/initializers/000-pg_connection_patch.rb
@@ -0,0 +1,39 @@
+# frozen_string_literal: true
+
+class ActiveRecord::ConnectionAdapters::PostgreSQLAdapter
+ def self.new_client(conn_params)
+ start = Time.now()
+ PG.connect(**conn_params)
+ rescue ::PG::Error => error
+ if conn_params && conn_params[:dbname] == "postgres"
+ raise ActiveRecord::ConnectionNotEstablished, error.message
+ # === PATCH START ===
+ # PostgreSQL's error message for a missing database looks something like this `FATAL: database "<databasename>" does not exist`.
+ # This patch updates the following conditional to be stricter and not match on other error messages that may contain the database name.
+ # For example, `<database>-some-host" (<some IP>), port 5432 failed: timeout expired after 11.30376464s` should not be considered
+ # a missing database error.
+ #
+ # Ideally, we want to include more of the missing database error message but we are unsure if the error message
+ # will change based on a user's locale and whether the locale is even selectable. The workaround now is already much better
+ # than the existing conditional.
+ elsif conn_params && conn_params[:dbname] &&
+ error.message.include?("\"#{conn_params[:dbname]}\"")
+ raise ActiveRecord::NoDatabaseError.db_error(conn_params[:dbname])
+ # === PATCH END ===
+ elsif conn_params && conn_params[:user] && error.message.include?(conn_params[:user])
+ # === PATCH START ===
+ error_message =
+ ActiveRecord::DatabaseConnectionError.username_error(conn_params[:user]).message
+ raise ActiveRecord::DatabaseConnectionError.new("#{error_message}\n#{error.message}")
+ # === PATCH END ===
+ elsif conn_params && conn_params[:host] && error.message.include?(conn_params[:host])
+ # === PATCH START ===
+ error_message =
+ ActiveRecord::DatabaseConnectionError.hostname_error(conn_params[:host]).message
+ raise ActiveRecord::DatabaseConnectionError.new("#{error_message}\n#{error.message}")
+ # === PATCH END ===
+ else
+ raise ActiveRecord::ConnectionNotEstablished, error.message
+ end
+ end
+end
diff --git a/spec/initializers/000_pg_connection_patch_spec.rb b/spec/initializers/000_pg_connection_patch_spec.rb
new file mode 100644
index 00000000000..9aa86305c4e
--- /dev/null
+++ b/spec/initializers/000_pg_connection_patch_spec.rb
@@ -0,0 +1,43 @@
+# 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