shard-crystal-db/src/db/database.cr

51 lines
1.1 KiB
Crystal
Raw Normal View History

module DB
# Acts as an entry point for database access.
# Currently it creates a single connection to the database.
# Eventually a connection pool will be handled.
#
# It should be created from DB module. See `DB#open`.
#
# Refer to `QueryMethods` for documentation about querying the database.
class Database
# :nodoc:
getter driver
# Returns the uri with the connection settings to the database
2016-02-03 21:29:09 +00:00
getter uri
2016-06-16 15:14:57 +00:00
@connection : Connection?
# :nodoc:
2016-06-16 15:14:57 +00:00
def initialize(@driver : Driver, @uri : URI)
@in_pool = true
@connection = @driver.build_connection(self)
end
# Closes all connection to the database.
def close
@connection.try &.close
# prevent GC Warning: Finalization cycle involving discovered by mysql implementation
@connection = nil
end
# :nodoc:
def prepare(query)
get_from_pool.prepare(query)
end
2016-02-03 19:57:54 +00:00
# :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
end
end