Delegate options parsing to driver

DRY parsing connection options for database
This commit is contained in:
Brian J. Cardiff 2023-05-28 23:07:09 -03:00
parent bc0200e178
commit 36f0a11d07
4 changed files with 13 additions and 6 deletions

View file

@ -49,7 +49,7 @@ class FooDriver < DB::Driver
def connection_builder(uri : URI) : Proc(DB::Connection)
params = HTTP::Params.parse(uri.query || "")
options = DB::Connection::Options.from_http_params(params)
options = connection_options(params)
->{ FooConnection.new(options).as(DB::Connection) }
end
@ -114,7 +114,7 @@ class BarDriver < DB::Driver
def connection_builder(uri : URI) : Proc(DB::Connection)
params = HTTP::Params.parse(uri.query || "")
options = DB::Connection::Options.from_http_params(params)
options = connection_options(params)
->{ BarConnection.new(options).as(DB::Connection) }
end

View file

@ -4,7 +4,7 @@ require "../src/db"
class DummyDriver < DB::Driver
def connection_builder(uri : URI) : Proc(DB::Connection)
params = HTTP::Params.parse(uri.query || "")
options = DB::Connection::Options.from_http_params(params)
options = connection_options(params)
->{ DummyConnection.new(options).as(DB::Connection) }
end

View file

@ -39,8 +39,7 @@ module DB
# Returns the uri with the connection settings to the database
getter uri : URI
getter? prepared_statements : Bool
@connection_options : Connection::Options
@pool : Pool(Connection)
@setup_connection : Connection -> Nil
@statements_cache = StringKeyCache(PoolPreparedStatement).new
@ -48,7 +47,7 @@ module DB
# :nodoc:
def initialize(@driver : Driver, @uri : URI)
params = HTTP::Params.parse(uri.query || "")
@prepared_statements = DB.fetch_bool(params, "prepared_statements", true)
@connection_options = @driver.connection_options(params)
pool_options = @driver.connection_pool_options(params)
@setup_connection = ->(conn : Connection) {}
@ -63,6 +62,10 @@ module DB
}
end
def prepared_statements? : Bool
@connection_options.prepared_statements
end
# Run the specified block every time a new connection is established, yielding the new connection
# to the block.
#

View file

@ -32,6 +32,10 @@ module DB
# are sound a factory Proc is returned.
abstract def connection_builder(uri : URI) : Proc(Connection)
def connection_options(params : HTTP::Params) : Connection::Options
Connection::Options.from_http_params(params)
end
def connection_pool_options(params : HTTP::Params)
{
initial_pool_size: params.fetch("initial_pool_size", 1).to_i,