Allow statements to auto close when consumed if no cache

This commit is contained in:
Brian J. Cardiff 2023-11-10 23:00:35 -03:00
parent 340b6e4b9a
commit ad41c258c8
5 changed files with 25 additions and 3 deletions

View file

@ -55,7 +55,9 @@ module DB
if @options.prepared_statements_cache if @options.prepared_statements_cache
@statements_cache.fetch(query) { build_prepared_statement(query) } @statements_cache.fetch(query) { build_prepared_statement(query) }
else else
build_prepared_statement(query) stmt = build_prepared_statement(query)
stmt.auto_close = true
stmt
end end
end end

View file

@ -59,6 +59,10 @@ module DB
@connection_options.prepared_statements @connection_options.prepared_statements
end end
def prepared_statements_cache? : Bool
@connection_options.prepared_statements_cache
end
# Run the specified block every time a new connection is established, yielding the new connection # Run the specified block every time a new connection is established, yielding the new connection
# to the block. # to the block.
# #

View file

@ -15,7 +15,14 @@ module DB
# otherwise the preparation is delayed until the first execution. # otherwise the preparation is delayed until the first execution.
# After the first initialization the connection must be released # After the first initialization the connection must be released
# it will be checked out when executing it. # it will be checked out when executing it.
# This only happens if the db is configured to use prepared statements cache.
# Without that there is no reference to the already prepared statement we can
# take advantage of.
if db.prepared_statements_cache?
statement_with_retry &.release_connection statement_with_retry &.release_connection
end
# TODO use a round-robin selection in the pool so multiple sequentially # TODO use a round-robin selection in the pool so multiple sequentially
# initialized statements are assigned to different connections. # initialized statements are assigned to different connections.
end end

View file

@ -29,7 +29,7 @@ module DB
end end
protected def do_close protected def do_close
statement.release_connection statement.release_from_result_set
end end
# TODO add_next_result_set : Bool # TODO add_next_result_set : Bool

View file

@ -56,6 +56,15 @@ module DB
def initialize(@connection : Connection, @command : String) def initialize(@connection : Connection, @command : String)
end end
# :nodoc:
property auto_close : Bool = false
# :nodoc:
def release_from_result_set
self.close if @auto_close
self.release_connection
end
def release_connection def release_connection
@connection.release_from_statement @connection.release_from_statement
end end