From 52753bce141a432239014912e11467b317670516 Mon Sep 17 00:00:00 2001 From: Luka Vandervelden Date: Fri, 3 Jan 2020 09:36:41 +0100 Subject: [PATCH] DODB::Index(V): #update(String, V) and #delete(String) added. --- src/dodb.cr | 2 +- src/dodb/index.cr | 35 ++++++++++++++++++++++++++++++++++- 2 files changed, 35 insertions(+), 2 deletions(-) diff --git a/src/dodb.cr b/src/dodb.cr index 5ea5994..c568212 100644 --- a/src/dodb.cr +++ b/src/dodb.cr @@ -50,7 +50,7 @@ class DODB::DataBase(V) ## # name is the name that will be used on the file system. def new_index(name : String, &block : Proc(V, String)) - Index(V).new(@directory_name, name, block).tap do |indexer| + Index(V).new(self, @directory_name, name, block).tap do |indexer| @indexers << indexer end end diff --git a/src/dodb/index.cr b/src/dodb/index.cr index 50aeb6b..d11d203 100644 --- a/src/dodb/index.cr +++ b/src/dodb/index.cr @@ -9,7 +9,9 @@ class DODB::Index(V) < DODB::Indexer(V) property key_proc : Proc(V, String) getter storage_root : String - def initialize(@storage_root, @name, @key_proc) + @storage : DODB::DataBase(V) + + def initialize(@storage, @storage_root, @name, @key_proc) Dir.mkdir_p indexing_directory end @@ -66,6 +68,37 @@ class DODB::Index(V) < DODB::Indexer(V) nil end + def get_key(index : String) : Int32 + file_path = file_path_index index + + raise MissingEntry.new(@name, index) unless ::File.exists? file_path + + ::File.readlink(file_path) + .sub(/\.json$/, "") + .sub(/^.*\//, "") + .to_i + end + + def get_with_key(index : String) : Tuple(V, Int32) + key = get_key index + + value = @storage[key] + + {value, key} + end + + def update(index : String, new_value : V) + _, key = get_with_key index + + @storage[key] = new_value + end + + def delete(index : String) + key = get_key index + + @storage.delete key + end + def indexing_directory : String "#{@storage_root}/indices/by_#{@name}" end