Add #query_each . Fixes #18

This commit is contained in:
Brian J. Cardiff 2017-04-10 12:48:48 -03:00
parent 5697bd5c58
commit 39e17f82ca
2 changed files with 36 additions and 4 deletions

View File

@ -208,6 +208,24 @@ describe DummyDriver do
end
end
describe "query each" do
it "queries" do
with_dummy do |db|
i = 0
db.query_each "3,4 1,2" do |rs|
case i
when 0
rs.read(Int64, Int64).should eq({3i64, 4i64})
when 1
rs.read(Int64, Int64).should eq({1i64, 2i64})
end
i += 1
end
i.should eq(2)
end
end
end
it "reads multiple values" do
with_dummy do |db|
db.query "3,4 1,2" do |rs|

View File

@ -166,10 +166,8 @@ module DB
# ```
def query_all(query, *args, &block : ResultSet -> U) : Array(U) forall U
ary = [] of U
query(query, *args) do |rs|
rs.each do
ary.push(yield rs)
end
query_each(query, *args) do |rs|
ary.push(yield rs)
end
ary
end
@ -198,6 +196,22 @@ module DB
end
end
# Executes a *query* and yields the `ResultSet` once per each row.
# The `ResultSet` is closed automatically.
#
# ```
# db.query_each "select name from contacts" do |rs|
# puts rs.read(String)
# end
# ```
def query_each(query, *args)
query(query, *args) do |rs|
rs.each do
yield rs
end
end
end
# Performs the `query` and returns an `ExecResult`
def exec(query, *args)
build(query).exec(*args)