PERF: Switch ActiveRecord PG connection active check to use empty query. (#13323)

PERF: Switch ActiveRecord PG connection active check to use empty query. (#13323)

See Use an empty query instead of SELECT 1 by engwan · Pull Request #42368 · rails/rails · GitHub

The impact is not quantifiable at the time of this writing but prelimary investigation shows that SELECT 1 accounts for 0.09 of CPU time on a database. Note that Discourse runs thousands of databases so the small impact may be amplified by the large number of databases that we run.

diff --git a/lib/freedom_patches/active_record_postgresql_adapter.rb b/lib/freedom_patches/active_record_postgresql_adapter.rb
new file mode 100644
index 0000000..bf64f92
--- /dev/null
+++ b/lib/freedom_patches/active_record_postgresql_adapter.rb
@@ -0,0 +1,19 @@
+# frozen_string_literal: true
+
+# Pulls in https://github.com/rails/rails/pull/42368 early since the query is
+# definitely more efficient as it does not involved the PG planner.
+# Remove once Rails 7 has been released.
+module ActiveRecord
+  module ConnectionAdapters
+    class PostgreSQLAdapter
+      def active?
+        @lock.synchronize do
+          @connection.query ";"
+        end
+        true
+      rescue PG::Error
+        false
+      end
+    end
+  end
+end

GitHub sha: 19a92fbadc88987bc68b9168a7778a1e5af101a0

This commit appears in #13323 which was approved by CvX. It was merged by SamSaffron.