Class: Syntropy::Storage::KVStore

Inherits:
Store
  • Object
show all
Defined in:
lib/syntropy/storage/kv_store.rb

Overview

The KVStore class implements an SQLite-backed key-value store

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Methods inherited from Store

#execute, #query, #query_single_row, #query_single_value, #transaction

Constructor Details

#initialize(connection_pool, table_name) ⇒ KVStore

Returns a new instance of KVStore.



18
19
20
21
22
23
# File 'lib/syntropy/storage/kv_store.rb', line 18

def initialize(connection_pool, table_name)
  super(connection_pool)
  @table_name = table_name

  setup_queries
end

Instance Attribute Details

#q_getObject (readonly)

Returns the value of attribute q_get.



9
10
11
# File 'lib/syntropy/storage/kv_store.rb', line 9

def q_get
  @q_get
end

#q_setObject (readonly)

Returns the value of attribute q_set.



9
10
11
# File 'lib/syntropy/storage/kv_store.rb', line 9

def q_set
  @q_set
end

Class Method Details

.apply_schema(db, table_name) ⇒ Object



11
12
13
14
15
16
# File 'lib/syntropy/storage/kv_store.rb', line 11

def self.apply_schema(db, table_name)
  db.execute <<~SQL
    create table if not exists #{table_name} (key text primary key, value, expires float);
    create index if not exists idx_#{table_name}_expires on #{table_name} (expires) where expires is not null;
  SQL
end

Instance Method Details

#get(db, key) ⇒ Object



25
26
27
# File 'lib/syntropy/storage/kv_store.rb', line 25

def get(db, key)
  db[@q_get].bind(key).next
end

#set(db, key, value) ⇒ Object



29
30
31
# File 'lib/syntropy/storage/kv_store.rb', line 29

def set(db, key, value)
  db[@q_set].execute(key, value)
end

#setex(db, key, value, ttl) ⇒ Object



33
34
35
# File 'lib/syntropy/storage/kv_store.rb', line 33

def setex(db, key, value, ttl)
  db[@q_setex].execute(key, value, ttl ? Time.now.to_f + ttl : nil)
end

#sweep(db) ⇒ Object



37
38
39
# File 'lib/syntropy/storage/kv_store.rb', line 37

def sweep(db)
  db[@q_sweep].execute(Time.now.to_f)
end