Skip to content

Commit

Permalink
Add ability to clear namespaces
Browse files Browse the repository at this point in the history
  • Loading branch information
fatkodima committed Jul 3, 2022
1 parent f2f6016 commit 6c7d2fe
Show file tree
Hide file tree
Showing 2 changed files with 44 additions and 0 deletions.
22 changes: 22 additions & 0 deletions lib/redis/namespace.rb
Original file line number Diff line number Diff line change
Expand Up @@ -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?
Expand Down Expand Up @@ -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
22 changes: 22 additions & 0 deletions spec/redis_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -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

0 comments on commit 6c7d2fe

Please sign in to comment.