From 620d9128bdbcc6070d2de6537f7e09e7934979de Mon Sep 17 00:00:00 2001 From: Alex Watt Date: Tue, 27 Feb 2024 23:00:35 -0500 Subject: [PATCH] execute_batch returns result of last statement --- lib/sqlite3/database.rb | 10 +++++----- test/test_database.rb | 10 +++++++++- 2 files changed, 14 insertions(+), 6 deletions(-) diff --git a/lib/sqlite3/database.rb b/lib/sqlite3/database.rb index e72c0ef1..4a92d022 100644 --- a/lib/sqlite3/database.rb +++ b/lib/sqlite3/database.rb @@ -251,8 +251,7 @@ def execute2(sql, *bind_vars) # in turn. The same bind parameters, if given, will be applied to each # statement. # - # This always returns +nil+, making it unsuitable for queries that return - # rows. + # This always returns the result of the last statement. # # See also #execute_batch2 for additional ways of # executing statements. @@ -279,6 +278,7 @@ def execute_batch(sql, bind_vars = [], *args) end sql = sql.strip + result = nil until sql.empty? prepare(sql) do |stmt| unless stmt.closed? @@ -287,13 +287,13 @@ def execute_batch(sql, bind_vars = [], *args) if bind_vars.length == stmt.bind_parameter_count stmt.bind_params(bind_vars) end - stmt.step + result = stmt.step end sql = stmt.remainder.strip end end - # FIXME: we should not return `nil` as a success return value - nil + + result end # Executes all SQL statements in the given string. By contrast, the other diff --git a/test/test_database.rb b/test/test_database.rb index 5c902eed..67788c17 100644 --- a/test/test_database.rb +++ b/test/test_database.rb @@ -145,13 +145,21 @@ def test_changes end def test_batch_last_comment_is_processed - # FIXME: nil as a successful return value is kinda dumb assert_nil @db.execute_batch <<-EOSQL CREATE TABLE items (id integer PRIMARY KEY AUTOINCREMENT); -- omg EOSQL end + def test_batch_last_expression_value_is_returned + batch = <<-EOSQL + CREATE TABLE items (id integer PRIMARY KEY AUTOINCREMENT); + SELECT COUNT(*) FROM items; + EOSQL + + assert_equal [0], @db.execute_batch(batch) + end + def test_execute_batch2 @db.results_as_hash = true return_value = @db.execute_batch2 <<-EOSQL