expose database in connection

get/return from pool while result set is been used. still single connection pool
This commit is contained in:
Brian J. Cardiff 2016-02-03 19:30:51 -03:00
parent fa111fd698
commit d45427dfdd
8 changed files with 59 additions and 31 deletions

View file

@ -17,8 +17,14 @@ module DB
abstract class Connection
include Disposable
include QueryMethods
# :nodoc:
getter database
@statements_cache = {} of String => Statement
def initialize(@database : Database)
end
# :nodoc:
def prepare(query) : Statement
stmt = @statements_cache.fetch(query, nil)

View file

@ -8,30 +8,37 @@ module DB
# Refer to `QueryMethods` for documentation about querying the database.
class Database
# :nodoc:
getter driver_class
getter driver
# Connection configuration to the database.
# Returns the uri with the connection settings to the database
getter uri
# :nodoc:
def initialize(@driver_class, @uri)
@driver = @driver_class.new(@uri)
@connection = @driver.build_connection
def initialize(@driver, @uri)
@in_pool = true
@connection = @driver.build_connection(self)
end
# Closes all connection to the database.
def close
@connection.close
end
# :nodoc:
def connection
@connection
@connection.try &.close
end
# :nodoc:
def prepare(query)
connection.prepare(query)
get_from_pool.prepare(query)
end
# :nodoc:
def get_from_pool
raise "DB Pool Exhausted" unless @in_pool
@in_pool = false
@connection.not_nil!
end
# :nodoc:
def return_to_pool(connection)
@in_pool = true
end
include QueryMethods

View file

@ -105,7 +105,7 @@ module DB
end
private def self.build_database(uri : URI)
Database.new(driver_class(uri.scheme), uri)
Database.new(driver_class(uri.scheme).new, uri)
end
end

View file

@ -7,8 +7,8 @@ module DB
# require "db"
#
# class FakeDriver < Driver
# def build_connection
# FakeConnection.new uri
# def build_connection(db)
# FakeConnection.new db
# end
# end
#
@ -18,7 +18,7 @@ module DB
# Access to this fake datbase will be available with
#
# ```
# DB.open "fake", "..." do |db|
# DB.open "fake://..." do |db|
# # ... use db ...
# end
# ```
@ -26,11 +26,9 @@ module DB
# Refer to `Connection`, `Statement` and `ResultSet` for further
# driver implementation instructions.
abstract class Driver
getter uri
def initialize(@uri : URI)
def initialize
end
abstract def build_connection : Connection
abstract def build_connection(db : Database) : Connection
end
end

View file

@ -21,6 +21,11 @@ module DB
def initialize(@statement : Statement)
end
protected def do_close
cnn = statement.connection
cnn.database.return_to_pool(cnn)
end
# TODO add_next_result_set : Bool
# Iterates over all the rows

View file

@ -18,6 +18,9 @@ module DB
def initialize(@connection)
end
protected def do_close
end
# See `QueryMethods#exec`
def exec
perform_exec(Slice(Any).new(0)) # no overload matches ... with types Slice(NoReturn)