From 603a65c6f485f5d50993309d0db6c4a2238da76b Mon Sep 17 00:00:00 2001 From: Luka Vandervelden Date: Tue, 7 Jan 2020 16:06:18 +0100 Subject: [PATCH] Fixes a possible issue with DB reopening. --- spec/test.cr | 21 ++++++++++++++++++--- src/dodb.cr | 8 ++++++-- 2 files changed, 24 insertions(+), 5 deletions(-) diff --git a/spec/test.cr b/spec/test.cr index e9808a3..3ddc086 100644 --- a/spec/test.cr +++ b/spec/test.cr @@ -30,9 +30,10 @@ class Ship # and can easily be extended. class_getter kisaragi = Ship.new("Kisaragi", "Mutsuki") + class_getter mutsuki = Ship.new("Mutsuki", "Mutsuki", tags: ["name ship"]) class_getter destroyers = [ @@kisaragi, - Ship.new("Mutsuki", "Mutsuki", tags: ["name ship"]), + @@mutsuki, Ship.new("Yayoi", "Mutsuki"), Ship.new("Uzuki", "Mutsuki"), Ship.new("Satsuki", "Mutsuki"), @@ -89,10 +90,12 @@ class PrimitiveShip end class DODB::SpecDataBase < DODB::DataBase(Ship) - def initialize(storage_ext = "") + def initialize(storage_ext = "", remove_previous_data = true) storage_dir = "test-storage#{storage_ext}" - ::FileUtils.rm_rf storage_dir + if remove_previous_data + ::FileUtils.rm_rf storage_dir + end super storage_dir end @@ -142,6 +145,18 @@ describe "DODB::DataBase" do db[i]?.should be_nil end end + + it "preserves data on reopening" do + db1 = DODB::SpecDataBase.new + db1 << Ship.kisaragi + + db1.to_a.size.should eq(1) + + db2 = DODB::SpecDataBase.new remove_previous_data: false + db2 << Ship.mutsuki + + db1.to_a.size.should eq(2) + end end describe "indices" do diff --git a/src/dodb.cr b/src/dodb.cr index c568212..0004e91 100644 --- a/src/dodb.cr +++ b/src/dodb.cr @@ -9,7 +9,11 @@ class DODB::DataBase(V) def initialize(@directory_name : String) Dir.mkdir_p data_path - self.last_index = -1 + begin + self.last_index + rescue + self.last_index = -1 + end end private def index_file @@ -21,7 +25,7 @@ class DODB::DataBase(V) def last_index=(x : Int32) file = File.open(index_file, "w") - file << stringify_key(x) + file << x.to_s file.close