@@ -99,6 +99,7 @@ def initialize(options = {}, &block)
9999 @available = TimedStack . new ( @size , &block )
100100 @key = :"pool-#{ @available . object_id } "
101101 @key_count = :"pool-#{ @available . object_id } -count"
102+ @discard_key = :"pool-#{ @available . object_id } -discard"
102103 INSTANCES [ self ] = self if @auto_reload_after_fork && INSTANCES
103104 end
104105
@@ -116,6 +117,32 @@ def with(options = {})
116117 end
117118 alias_method :then , :with
118119
120+ ##
121+ # Marks the current thread's checked-out connection for discard.
122+ #
123+ # When a connection is marked for discard, it will not be returned to the pool
124+ # when checked in. Instead, the connection will be discarded.
125+ # This is useful when a connection has become invalid or corrupted
126+ # and should not be reused.
127+ #
128+ # Note: This only affects the connection currently checked out by the calling thread.
129+ # The connection will be discarded when +checkin+ is called.
130+ #
131+ # @return [void]
132+ #
133+ # @example
134+ # pool.with do |conn|
135+ # begin
136+ # conn.execute("SELECT 1")
137+ # rescue SomeConnectionError
138+ # pool.discard_current_connection # Mark connection as bad
139+ # raise
140+ # end
141+ # end
142+ def discard_current_connection
143+ ::Thread . current [ @discard_key ] = true
144+ end
145+
119146 def checkout ( options = { } )
120147 if ::Thread . current [ @key ]
121148 ::Thread . current [ @key_count ] += 1
@@ -129,7 +156,12 @@ def checkout(options = {})
129156 def checkin ( force : false )
130157 if ::Thread . current [ @key ]
131158 if ::Thread . current [ @key_count ] == 1 || force
132- @available . push ( ::Thread . current [ @key ] )
159+ if ::Thread . current [ @discard_key ]
160+ @available . decrement_created
161+ ::Thread . current [ @discard_key ] = nil
162+ else
163+ @available . push ( ::Thread . current [ @key ] )
164+ end
133165 ::Thread . current [ @key ] = nil
134166 ::Thread . current [ @key_count ] = nil
135167 else
0 commit comments