class MicroSql::KeyValueTable

Public Class Methods

new(db, table_name = "settings") click to toggle source
Calls superclass method MicroSql::Table::new
# File lib/micro_sql/key_value_table.rb, line 6
def initialize(db, table_name = "settings")
  sql = if db.is_a?(MicroSql::PgAdapter)
    "CREATE TABLE #{table_name}_b(uid TEXT PRIMARY KEY, value BYTEA, ttl INTEGER NOT NULL)"
  else
    "CREATE TABLE #{table_name}(uid TEXT PRIMARY KEY, value TEXT, ttl INTEGER NOT NULL)"
  end

  super db, sql
end

Public Instance Methods

[](key) click to toggle source
# File lib/micro_sql/key_value_table.rb, line 16
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
[]=(key, value, ttl = nil)
Alias for: update
cached(key, ttl = nil) { || ... } click to toggle source
# File lib/micro_sql/key_value_table.rb, line 25
def cached(key, ttl = nil, &block)
  self[key] || update(key, yield, ttl)
end
delete_all() click to toggle source
# File lib/micro_sql/key_value_table.rb, line 21
def delete_all
  @db.exec "DELETE FROM #{table_name}"
end
expire(key, ttl) click to toggle source
# File lib/micro_sql/key_value_table.rb, line 44
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) click to toggle source
# File lib/micro_sql/key_value_table.rb, line 29
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
Also aliased as: []=

Private Instance Methods

decode(io) click to toggle source
# File lib/micro_sql/key_value_table.rb, line 53
def decode(io)
  return unless io
  return PG::Connection.unescape_bytea(io) if db.is_a?(MicroSql::PgAdapter)

  JSON.parse("[#{io}]").first
end
encode(value) click to toggle source
# File lib/micro_sql/key_value_table.rb, line 60
def encode(value)
  return unless value
  
  return db.connection.escape_bytea(value.to_s) if db.is_a?(MicroSql::PgAdapter)
  
  value.to_json
end