Class: Insika::Stores::Memory

Inherits:
Object
  • Object
show all
Includes:
Insika::Store
Defined in:
lib/insika/stores/memory.rb

Overview

In-memory backend for dev/test. Serializes JSON even in memory: exact parity of type semantics with SQLite — the contract suite is honest. No lock: cooperative fibers do not preempt in the middle of a Hash operation.

Instance Method Summary collapse

Constructor Details

#initializeMemory

Returns a new instance of Memory.



15
16
17
18
19
# File 'lib/insika/stores/memory.rb', line 15

def initialize
  @data = new_store
  @tx_depth = 0
  @snapshot = nil
end

Instance Method Details

#delete(scope, key) ⇒ Object



33
34
35
# File 'lib/insika/stores/memory.rb', line 33

def delete(scope, key)
  !@data[scope].delete(key).nil?
end

#get(scope, key) ⇒ Object



21
22
23
24
25
26
# File 'lib/insika/stores/memory.rb', line 21

def get(scope, key)
  raw = @data[scope][key]
  return nil if raw.nil?

  JSON.parse(raw)
end

#list(scope, prefix = nil) ⇒ Object



37
38
39
40
# File 'lib/insika/stores/memory.rb', line 37

def list(scope, prefix = nil)
  keys = @data[scope].keys.sort
  prefix ? keys.select { |k| k.start_with?(prefix) } : keys
end

#set(scope, key, value) ⇒ Object



28
29
30
31
# File 'lib/insika/stores/memory.rb', line 28

def set(scope, key, value)
  @data[scope][key] = serialize(value)
  value
end

#transactionObject

Snapshot at the start of the outermost transaction; an exception at any level -> restore the snapshot and re-propagate (a REAL rollback). A nested one reuses the outer (no SAVEPOINT).



45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
# File 'lib/insika/stores/memory.rb', line 45

def transaction
  if @tx_depth.positive?
    @tx_depth += 1
    begin
      return yield
    ensure
      @tx_depth -= 1
    end
  end

  @snapshot = deep_snapshot
  @tx_depth = 1
  begin
    yield
  rescue StandardError
    restore_snapshot
    raise
  ensure
    @tx_depth = 0
    @snapshot = nil
  end
end