From a17d339a1dce5e9a66bd608cdcc85bc9f191b168 Mon Sep 17 00:00:00 2001 From: Fabrizio Monti Date: Mon, 19 Jan 2026 11:24:11 +0100 Subject: [PATCH] Reset connection when database_url changes Allows ruby-pg-extras to work with applications using multiple databases (e.g. Rails sharding) by closing and clearing the existing connection when database_url= is called. --- lib/ruby-pg-extras.rb | 2 ++ spec/smoke_spec.rb | 12 ++++++++++++ 2 files changed, 14 insertions(+) diff --git a/lib/ruby-pg-extras.rb b/lib/ruby-pg-extras.rb index f3a151b..17fa80a 100644 --- a/lib/ruby-pg-extras.rb +++ b/lib/ruby-pg-extras.rb @@ -247,6 +247,8 @@ def self.connection end def self.database_url=(value) + @_connection&.close + @_connection = nil @@database_url = value end diff --git a/spec/smoke_spec.rb b/spec/smoke_spec.rb index a0599ff..2f8853f 100644 --- a/spec/smoke_spec.rb +++ b/spec/smoke_spec.rb @@ -65,5 +65,17 @@ RubyPgExtras.bloat(in_format: :hash) end.not_to raise_error end + + it "resets the connection when setting database URL" do + old_connection = RubyPgExtras.connection + expect(old_connection).not_to be_finished + + RubyPgExtras.database_url = ENV.fetch("DATABASE_URL") + + expect(old_connection).to be_finished + new_connection = RubyPgExtras.connection + expect(new_connection).not_to eq(old_connection) + expect(new_connection).not_to be_finished + end end end