From 6c7d2fe5e33d9efb548d62daa4e74f258d656a5a Mon Sep 17 00:00:00 2001 From: fatkodima Date: Sun, 3 Jul 2022 19:28:14 +0300 Subject: [PATCH] Add ability to clear namespaces --- lib/redis/namespace.rb | 22 ++++++++++++++++++++++ spec/redis_spec.rb | 22 ++++++++++++++++++++++ 2 files changed, 44 insertions(+) diff --git a/lib/redis/namespace.rb b/lib/redis/namespace.rb index ea3a949..9e1350f 100644 --- a/lib/redis/namespace.rb +++ b/lib/redis/namespace.rb @@ -329,6 +329,23 @@ def eval(*args) end ruby2_keywords(:eval) if respond_to?(:ruby2_keywords, true) + def clear + batch_size = 1000 + + if supports_scan? + cursor = "0" + begin + cursor, keys = scan(cursor, count: batch_size) + del(*keys) unless keys.empty? + end until cursor == "0" + else + all_keys = keys("*") + all_keys.each_slice(batch_size) do |keys| + del(*keys) + end + end + end + ADMINISTRATIVE_COMMANDS.keys.each do |command| define_method(command) do |*args, &block| raise NoMethodError if deprecations? @@ -581,5 +598,10 @@ def create_enumerator(&block) Enumerator.new(&block) end end + + def supports_scan? + redis_version = Gem::Version.new(@redis.info["redis_version"]) + redis_version >= Gem::Version.new("2.8.0") + end end end diff --git a/spec/redis_spec.rb b/spec/redis_spec.rb index 04c7751..2a71ab5 100644 --- a/spec/redis_spec.rb +++ b/spec/redis_spec.rb @@ -949,4 +949,26 @@ expect(sub_sub_namespaced.full_namespace).to eql("ns:sub1:sub2") end end + + describe :clear do + it "should delete all the keys" do + @redis.set("foo", "bar") + @namespaced.mset("foo1", "bar", "foo2", "bar") + @namespaced.clear + + expect(@redis.keys).to eq ["foo"] + expect(@namespaced.keys).to be_empty + end + + it "should delete all the keys in older redis" do + allow(@redis).to receive(:info).and_return({ "redis_version" => "2.7.0" }) + + @redis.set("foo", "bar") + @namespaced.mset("foo1", "bar", "foo2", "bar") + @namespaced.clear + + expect(@redis.keys).to eq ["foo"] + expect(@namespaced.keys).to be_empty + end + end end