Class: MicroSql::KeyValueTable

Inherits:
Table
  • Object
show all
Defined in:
lib/micro_sql/key_value_table.rb

Instance Attribute Summary

Attributes inherited from Table

#db

Instance Method Summary collapse

Methods inherited from Table

#insert, #primary_key

Constructor Details

#initialize(db, table_name = "settings") ⇒ KeyValueTable

Returns a new instance of KeyValueTable.



6
7
8
# File 'lib/micro_sql/key_value_table.rb', line 6

def initialize(db, table_name = "settings")
  super db, "CREATE TABLE #{table_name}(uid TEXT PRIMARY KEY, value TEXT, ttl INTEGER NOT NULL)"
end

Instance Method Details

#[](key) ⇒ Object



10
11
12
13
# File 'lib/micro_sql/key_value_table.rb', line 10

def [](key)
  value, ttl = db.ask("SELECT value, ttl FROM #{table_name} WHERE uid=?", key)
  decode(value) if ttl && (ttl == 0 || ttl > Time.now.to_i)
end

#cached(key, ttl = nil, &block) ⇒ Object



19
20
21
# File 'lib/micro_sql/key_value_table.rb', line 19

def cached(key, ttl = nil, &block)
  self[key] || update(key, yield, ttl)
end

#delete_allObject



15
16
17
# File 'lib/micro_sql/key_value_table.rb', line 15

def delete_all
  @db.exec "DELETE FROM #{table_name}"
end

#expire(key, ttl) ⇒ Object



38
39
40
41
# File 'lib/micro_sql/key_value_table.rb', line 38

def expire(key, ttl)
  ttl = ttl ? ttl + Time.now.to_i : ttl
  @db.ask("UPDATE #{table_name} SET ttl=? WHERE uid=?", ttl, key)
end

#update(key, value, ttl = nil) ⇒ Object Also known as: []=



23
24
25
26
27
28
29
30
31
32
33
34
35
36
# File 'lib/micro_sql/key_value_table.rb', line 23

def update(key, value, ttl = nil)
  if value
    encoded = encode(value)
    ttl = ttl ? ttl + Time.now.to_i : 0
    affected = @db.ask("UPDATE #{table_name} SET value=?, ttl=? WHERE uid=?", encoded, ttl, key)
    if affected == 0
      @db.ask("INSERT INTO #{table_name}(value, ttl, uid) VALUES(?,?,?)", encoded, ttl, key)
    end
  else
    @db.ask("DELETE FROM #{table_name} WHERE uid=?", key)
  end

  value
end