From 34ae9d5775e8aee8b2c24429660511029410b8b6 Mon Sep 17 00:00:00 2001 From: "Brian J. Cardiff" Date: Thu, 23 Jun 2016 22:07:59 -0300 Subject: [PATCH] avoid messing with finalize cycle in Disposable. ensure statements are closed when connection is closed --- spec/result_set_spec.cr | 27 +++++++++++++++++++++++++++ spec/statement_spec.cr | 9 +++++++++ src/db/connection.cr | 3 +++ src/db/disposable.cr | 5 ----- 4 files changed, 39 insertions(+), 5 deletions(-) diff --git a/spec/result_set_spec.cr b/spec/result_set_spec.cr index 64a7d58..f1cc306 100644 --- a/spec/result_set_spec.cr +++ b/spec/result_set_spec.cr @@ -1,5 +1,8 @@ require "./spec_helper" +class DummyException < Exception +end + describe DB::ResultSet do it "should enumerate records using each" do nums = [] of Int32 @@ -15,4 +18,28 @@ describe DB::ResultSet do nums.should eq([3, 4, 1, 2]) end + + it "should close ResultSet after query" do + with_dummy do |db| + the_rs = uninitialized DB::ResultSet + db.query "3,4 1,2" do |rs| + the_rs = rs + end + the_rs.closed?.should be_true + end + end + + it "should close ResultSet after query even with exception" do + with_dummy do |db| + the_rs = uninitialized DB::ResultSet + begin + db.query "3,4 1,2" do |rs| + the_rs = rs + raise DummyException.new + end + rescue DummyException + end + the_rs.closed?.should be_true + end + end end diff --git a/spec/statement_spec.cr b/spec/statement_spec.cr index d362ebf..9621ed5 100644 --- a/spec/statement_spec.cr +++ b/spec/statement_spec.cr @@ -65,6 +65,15 @@ describe DB::Statement do end end + it "closing connection should close statement" do + stmt = uninitialized DB::Statement + with_dummy do |db| + stmt = db.prepare "3,4 1,2" + stmt.query + end + stmt.closed?.should be_true + end + it "query with block should not close statement" do with_dummy do |db| stmt = db.prepare "3,4 1,2" diff --git a/src/db/connection.cr b/src/db/connection.cr index 469f62d..9924ec7 100644 --- a/src/db/connection.cr +++ b/src/db/connection.cr @@ -40,6 +40,9 @@ module DB abstract def build_statement(query) : Statement protected def do_close + @statements_cache.each do |_, stmt| + stmt.close + end @statements_cache.clear end end diff --git a/src/db/disposable.cr b/src/db/disposable.cr index 301df9d..4d52dc6 100644 --- a/src/db/disposable.cr +++ b/src/db/disposable.cr @@ -17,11 +17,6 @@ module DB @closed end - # :nodoc: - def finalize - close - end - # Implementors overrides this method to perform resource cleanup protected abstract def do_close end