Skip to content

Commit 6f16513

Browse files
author
Timur Alperovich
committed
SQLite3: Always close statements.
SQLite3 adapter must make sure to close statements after queries. Fixes: #13631
1 parent 8d146c8 commit 6f16513

File tree

3 files changed

+27
-3
lines changed

3 files changed

+27
-3
lines changed

activerecord/CHANGELOG.md

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,9 @@
1+
* Ensure SQLite3 statements are closed on errors.
2+
3+
Fixes: #13631
4+
5+
*Timur Alperovich*
6+
17
* Enable partial indexes for sqlite >= 3.8.0
28

39
See http://www.sqlite.org/partialindex.html

activerecord/lib/active_record/connection_adapters/sqlite3_adapter.rb

Lines changed: 6 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -299,9 +299,12 @@ def exec_query(sql, name = nil, binds = [])
299299
# Don't cache statements if they are not prepared
300300
if without_prepared_statement?(binds)
301301
stmt = @connection.prepare(sql)
302-
cols = stmt.columns
303-
records = stmt.to_a
304-
stmt.close
302+
begin
303+
cols = stmt.columns
304+
records = stmt.to_a
305+
ensure
306+
stmt.close
307+
end
305308
stmt = records
306309
else
307310
cache = @statements[sql] ||= {

activerecord/test/cases/adapters/sqlite3/sqlite3_adapter_test.rb

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -401,6 +401,21 @@ def test_respond_to_disable_extension
401401
assert @conn.respond_to?(:disable_extension)
402402
end
403403

404+
def test_statement_closed
405+
db = SQLite3::Database.new(ActiveRecord::Base.
406+
configurations['arunit']['database'])
407+
statement = SQLite3::Statement.new(db,
408+
'CREATE TABLE statement_test (number integer not null)')
409+
statement.stubs(:step).raises(SQLite3::BusyException, 'busy')
410+
statement.stubs(:columns).once.returns([])
411+
statement.expects(:close).once
412+
SQLite3::Statement.stubs(:new).returns(statement)
413+
414+
assert_raise ActiveRecord::StatementInvalid do
415+
@conn.exec_query 'select * from statement_test'
416+
end
417+
end
418+
404419
private
405420

406421
def assert_logged logs

0 commit comments

Comments
 (0)