Class: Anemone::Storage::SQLite3

Inherits:
Object
  • Object
show all
Defined in:
lib/anemone/storage/sqlite3.rb

Instance Method Summary collapse

Constructor Details

#initialize(file) ⇒ SQLite3



12
13
14
15
# File 'lib/anemone/storage/sqlite3.rb', line 12

def initialize(file)
  @db = ::SQLite3::Database.new(file)
  create_schema
end

Instance Method Details

#[](url) ⇒ Object



17
18
19
20
21
22
# File 'lib/anemone/storage/sqlite3.rb', line 17

def [](url)
  value = @db.get_first_value('SELECT data FROM anemone_storage WHERE key = ?', url.to_s)
  if value
    Marshal.load(value)
  end
end

#[]=(url, value) ⇒ Object



24
25
26
27
28
29
30
31
# File 'lib/anemone/storage/sqlite3.rb', line 24

def []=(url, value)
  data = Marshal.dump(value)
  if has_key?(url)
    @db.execute('UPDATE anemone_storage SET data = ? WHERE key = ?', data, url.to_s)
  else
    @db.execute('INSERT INTO anemone_storage (data, key) VALUES(?, ?)', data, url.to_s)
  end
end

#closeObject



63
64
65
# File 'lib/anemone/storage/sqlite3.rb', line 63

def close
  @db.close
end

#delete(url) ⇒ Object



33
34
35
36
37
# File 'lib/anemone/storage/sqlite3.rb', line 33

def delete(url)
  page = self[url]
  @db.execute('DELETE FROM anemone_storage WHERE key = ?', url.to_s)
  page
end

#eachObject



39
40
41
42
43
44
# File 'lib/anemone/storage/sqlite3.rb', line 39

def each
  @db.execute("SELECT key, data FROM anemone_storage ORDER BY id") do |row|
    value = Marshal.load(row[1])
    yield row[0], value
  end
end

#has_key?(url) ⇒ Boolean



59
60
61
# File 'lib/anemone/storage/sqlite3.rb', line 59

def has_key?(url)
  !!@db.get_first_value('SELECT id FROM anemone_storage WHERE key = ?', url.to_s)
end

#keysObject



55
56
57
# File 'lib/anemone/storage/sqlite3.rb', line 55

def keys
  @db.execute("SELECT key FROM anemone_storage ORDER BY id").map{|t| t[0]}
end

#merge!(hash) ⇒ Object



46
47
48
49
# File 'lib/anemone/storage/sqlite3.rb', line 46

def merge!(hash)
  hash.each { |key, value| self[key] = value }
  self
end

#sizeObject



51
52
53
# File 'lib/anemone/storage/sqlite3.rb', line 51

def size
  @db.get_first_value('SELECT COUNT(id) FROM anemone_storage')
end