user1051849 user1051849 - 2 months ago 10
Ruby Question

Clearing or Deleting a Ruby PStore

I've been experimenting with PStore to hold relatively large numbers of hash values using:

require "pstore"
store = PStore.new("data.pstore")


Seeing as this is stored in a file full of now-useless data, how do I clear or delete the "store" programatically? Obviously I could just delete the
store.pstore
file, but what i'm looking for is the PStore equivalent of:

DELETE FROM store WHERE 1=1;


Thanks!

Answer

What you're looking for is delete:

store.transaction { store.delete(key) }


store = PStore.new("data.pstore")
#=> #<PStore:0x007fd67f35a040 @abort=false, @filename="data.pstore", @lock=#<Thread::Mutex:0x007fd67f359f28>, @thread_safe=false, @ultra_safe=false>
store.transaction { store[:foo] = :bar }
# => #<PStore:0x007fd67f35a040 @abort=false, @filename="data.pstore", @lock=#<Thread::Mutex:0x007fd67f359f28>, @rdonly=false, @table={:foo=>:bar}, @thread_safe=false, @ultra_safe=false>
store.transaction { store.delete(:foo) }
#=> :bar
store
#=> #<PStore:0x007fd67f35a040 @abort=false, @filename="data.pstore", @lock=#<Thread::Mutex:0x007fd67f359f28>, @thread_safe=false, @ultra_safe=false

If you want to truncate the store you can iterate over the roots and delete them in a transaction:

roots = store.transaction { store.roots }
roots.each do |root|
  store.transaction { store.delete[root] }
end