2016-01-29 19:13:01 +00:00
|
|
|
module DB
|
|
|
|
# Acts as an entry point for database access.
|
2016-01-30 22:46:43 +00:00
|
|
|
# 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`.
|
2016-01-29 19:13:01 +00:00
|
|
|
class Database
|
|
|
|
getter driver_class
|
|
|
|
getter options
|
|
|
|
|
|
|
|
def initialize(@driver_class, @options)
|
|
|
|
@driver = @driver_class.new(@options)
|
2016-01-30 22:46:43 +00:00
|
|
|
@connection = @driver.build_connection
|
2016-01-29 19:13:01 +00:00
|
|
|
end
|
|
|
|
|
2016-01-30 22:46:43 +00:00
|
|
|
# Closes all connection to the database
|
|
|
|
def close
|
|
|
|
@connection.close
|
|
|
|
end
|
|
|
|
|
|
|
|
# Returns a `Connection` to the database
|
|
|
|
def connection
|
|
|
|
@connection
|
|
|
|
end
|
|
|
|
|
|
|
|
# Prepares a `Statement`. The Statement must be closed explicitly
|
|
|
|
# after is not longer in use.
|
|
|
|
#
|
|
|
|
# Usually `#exec`, `#query` or `#scalar` should be used.
|
2016-01-29 19:13:01 +00:00
|
|
|
def prepare(query)
|
2016-01-30 22:46:43 +00:00
|
|
|
connection.prepare(query)
|
|
|
|
end
|
|
|
|
|
|
|
|
def query(query, *args)
|
|
|
|
prepare(query).query(*args)
|
|
|
|
end
|
|
|
|
|
|
|
|
def query(query, *args)
|
|
|
|
# CHECK prepare(query).query(*args, &block)
|
|
|
|
query(query, *args).tap do |rs|
|
|
|
|
begin
|
|
|
|
yield rs
|
|
|
|
ensure
|
|
|
|
rs.close
|
|
|
|
end
|
|
|
|
end
|
2016-01-29 19:13:01 +00:00
|
|
|
end
|
|
|
|
|
|
|
|
def exec(query, *args)
|
|
|
|
prepare(query).exec(*args)
|
|
|
|
end
|
2016-01-30 00:57:00 +00:00
|
|
|
|
2016-01-30 22:46:43 +00:00
|
|
|
def scalar(query, *args)
|
|
|
|
prepare(query).scalar(*args)
|
2016-01-30 00:57:00 +00:00
|
|
|
end
|
|
|
|
|
2016-01-30 22:46:43 +00:00
|
|
|
def scalar(t, query, *args)
|
|
|
|
prepare(query).scalar(t, *args)
|
2016-01-30 00:57:00 +00:00
|
|
|
end
|
|
|
|
|
2016-01-30 22:46:43 +00:00
|
|
|
def scalar?(query, *args)
|
|
|
|
prepare(query).scalar?(*args)
|
|
|
|
end
|
|
|
|
|
|
|
|
def scalar?(t, query, *args)
|
|
|
|
prepare(query).scalar?(t, *args)
|
2016-01-30 00:57:00 +00:00
|
|
|
end
|
2016-01-29 19:13:01 +00:00
|
|
|
end
|
|
|
|
end
|