Add mutex to protect @connections : Set

This commit is contained in:
Brian J. Cardiff 2021-03-12 13:57:39 -03:00
parent eaddae7d71
commit 1d08caa8a5

View file

@ -7,6 +7,7 @@ module DB
class PoolPreparedStatement < PoolStatement class PoolPreparedStatement < PoolStatement
# connections where the statement was prepared # connections where the statement was prepared
@connections = Set(WeakRef(Connection)).new @connections = Set(WeakRef(Connection)).new
@mutex = Mutex.new
def initialize(db : Database, query : String) def initialize(db : Database, query : String)
super super
@ -25,21 +26,27 @@ module DB
# WHAT-IF the connection is busy? Should each statement be able to # WHAT-IF the connection is busy? Should each statement be able to
# deallocate itself when the connection is free. # deallocate itself when the connection is free.
@connections.clear @mutex.synchronize do
@connections.clear
end
end end
# builds a statement over a real connection # builds a statement over a real connection
# the connection is registered in `@connections` # the connection is registered in `@connections`
private def build_statement : Statement private def build_statement : Statement
clean_connections clean_connections
conn, existing = @db.checkout_some(@connections) conn = uninitialized Connection
existing = false
@mutex.synchronize do
conn, existing = @db.checkout_some(@connections)
end
begin begin
stmt = conn.prepared.build(@query) stmt = conn.prepared.build(@query)
rescue ex rescue ex
conn.release conn.release
raise ex raise ex
end end
@connections << WeakRef.new(conn) unless existing @mutex.synchronize { @connections << WeakRef.new(conn) } unless existing
stmt stmt
end end