leave a single scalar value returns DB::Any

This commit is contained in:
Brian J. Cardiff 2016-02-01 22:33:58 -03:00
parent d01da912f7
commit 67fe5c9aae
5 changed files with 39 additions and 84 deletions

View file

@ -40,36 +40,12 @@ module DB
prepare(query).exec(*args)
end
# Performs the `query` and returns a single scalar `Int32` value
# Performs the `query` and returns a single scalar `DB::Any` value
# puts db.scalar("SELECT MAX(name)") as String # => (a String)
def scalar(query, *args)
prepare(query).scalar(*args)
end
# TODO remove scalar? make it always nillable. raise if 0-rows raise +1-rows
# Performs the `query` and returns a single scalar value of type `t`.
# `t` must be any of the allowed `DB::Any` types.
#
# ```
# puts db.scalar(String, "SELECT MAX(name)") # => (a String)
# ```
def scalar(t, query, *args)
prepare(query).scalar(t, *args)
end
# Performs the `query` and returns a single scalar `Int32 | Nil` value
def scalar?(query, *args)
prepare(query).scalar?(*args)
end
# Performs the `query` and returns a single scalar value of type `t` or `Nil`.
# `t` must be any of the allowed `DB::Any` types.
#
# ```
# puts db.scalar?(String, "SELECT MAX(name)") # => (a String | Nil)
# ```
def scalar?(t, query, *args)
prepare(query).scalar?(t, *args)
end
# TODO add query_row
end
end

View file

@ -26,30 +26,27 @@ module DB
# See `QueryMethods#scalar`
def scalar(*args)
scalar(Int32, *args)
end
# See `QueryMethods#scalar`. `t` must be in DB::TYPES
def scalar(t, *args)
query(*args) do |rs|
rs.each do
return rs.read(t)
end
end
raise "no results"
end
# See `QueryMethods#scalar?`
def scalar?(*args)
scalar?(Int32, *args)
end
# See `QueryMethods#scalar?`. `t` must be in DB::TYPES
def scalar?(t, *args)
query(*args) do |rs|
rs.each do
return rs.read?(t)
# return case rs.read?(rs.column_type(0)) # :-( Some day...
t = rs.column_type(0)
if t == String
return rs.read?(String)
elsif t == Int32
return rs.read?(Int32)
elsif t == Int64
return rs.read?(Int64)
elsif t == Float32
return rs.read?(Float32)
elsif t == Float64
return rs.read?(Float64)
elsif t == Slice(UInt8)
return rs.read?(Slice(UInt8))
elsif t == Nil
return rs.read?(Int32)
else
raise "not implemented for #{t} type"
end
end
end