Disable prepared statement cache

This commit is contained in:
Brian J. Cardiff 2023-03-28 11:20:52 -03:00
parent 76eba76dec
commit 0897477044
2 changed files with 2 additions and 42 deletions

View File

@ -25,7 +25,6 @@ module DB
# :nodoc: # :nodoc:
getter context getter context
@statements_cache = StringKeyCache(Statement).new
@transaction = false @transaction = false
getter? prepared_statements : Bool getter? prepared_statements : Bool
# :nodoc: # :nodoc:
@ -37,7 +36,7 @@ module DB
# :nodoc: # :nodoc:
def fetch_or_build_prepared_statement(query) : Statement def fetch_or_build_prepared_statement(query) : Statement
@statements_cache.fetch(query) { build_prepared_statement(query) } build_prepared_statement(query)
end end
# :nodoc: # :nodoc:
@ -57,8 +56,6 @@ module DB
end end
protected def do_close protected def do_close
@statements_cache.each_value &.close
@statements_cache.clear
@context.discard self @context.discard self
end end

View File

@ -5,61 +5,24 @@ module DB
# #
# See `PoolStatement` # See `PoolStatement`
class PoolPreparedStatement < PoolStatement class PoolPreparedStatement < PoolStatement
# connections where the statement was prepared
@connections = Set(WeakRef(Connection)).new
@mutex = Mutex.new
def initialize(db : Database, query : String) def initialize(db : Database, query : String)
super super
# Prepares a statement on some connection
# otherwise the preparation is delayed until the first execution.
# After the first initialization the connection must be released
# it will be checked out when executing it.
statement_with_retry &.release_connection
# TODO use a round-robin selection in the pool so multiple sequentially
# initialized statements are assigned to different connections.
end end
protected def do_close protected def do_close
@mutex.synchronize do
# TODO close all statements on all connections.
# currently statements are closed when the connection is closed.
# WHAT-IF the connection is busy? Should each statement be able to
# deallocate itself when the connection is free.
@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 conn = @db.checkout
conn, existing = @db.checkout_some(@connections)
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
unless existing
@mutex.synchronize do
@connections << WeakRef.new(conn)
end
end
stmt stmt
end end
private def clean_connections
@mutex.synchronize do
# remove disposed or closed connections
@connections.each do |ref|
conn = ref.value
if !conn || conn.closed?
@connections.delete ref
end
end
end
end
end end
end end