From 858d92970d85014db78756b862dcaf2ff2ae349f Mon Sep 17 00:00:00 2001 From: Luka Vandervelden Date: Thu, 12 Dec 2019 00:01:02 +0100 Subject: [PATCH] reindex_everything! method added. --- spec/test.cr | 25 +++++++++++++++++++++++++ src/fsdb.cr | 14 ++++++++++++++ 2 files changed, 39 insertions(+) diff --git a/spec/test.cr b/spec/test.cr index f2e4b22..a6c27da 100644 --- a/spec/test.cr +++ b/spec/test.cr @@ -249,5 +249,30 @@ describe "DODB::DataBase" do db_ships_by_tags.get("flagship").should eq([] of Ship) end end + + describe "tools" do + it "rebuilds indexes" do + db = DODB::SpecDataBase.new + + db_ships_by_name = db.new_index "name", &.name + db_ships_by_class = db.new_partition "class", &.class + db_ships_by_tags = db.new_tags "tags", &.tags + + Ship.all_ships.each do |ship| + db[ship.id] = ship + end + + db.reindex_everything! + + Ship.all_ships.each do |ship| + db_ships_by_name.get?(ship.name).should eq(ship) + db_ships_by_class.get(ship.class).should contain(ship) + end + end + + # Migration testing code will go here as soon as migration testing + # becomes relevant (due to format changes or so). For small projects, + # reindexing will work very well in the meantime. + end end diff --git a/src/fsdb.cr b/src/fsdb.cr index 2bbb203..b71bcb7 100644 --- a/src/fsdb.cr +++ b/src/fsdb.cr @@ -159,5 +159,19 @@ class DODB::DataBase(K, V) private def read(file_path : String) V.from_json ::File.read file_path end + + # A very slow operation that removes all indices and then rewrites + # them all. + def reindex_everything! + old_data = to_h + + old_data.each do |key, value| + self.delete key + end + + old_data.each do |key, value| + self[key] = value + end + end end