Class: Spurline::Session::Store::SQLite

Inherits:
Base
  • Object
show all
Defined in:
lib/spurline/session/store/sqlite.rb

Overview

SQLite-backed session store. Persists sessions across process restarts. Thread-safe via a single connection guarded by a Mutex.

Constant Summary collapse

TABLE_NAME =
"spurline_sessions"

Instance Method Summary collapse

Constructor Details

#initialize(path: Spurline.config.session_store_path, serializer: Spurline::Session::Serializer.new) ⇒ SQLite

Returns a new instance of SQLite.



14
15
16
17
18
19
# File 'lib/spurline/session/store/sqlite.rb', line 14

def initialize(path: Spurline.config.session_store_path, serializer: Spurline::Session::Serializer.new)
  @path = path
  @serializer = serializer
  @mutex = Mutex.new
  @db = nil
end

Instance Method Details

#clear!Object



74
75
76
77
78
# File 'lib/spurline/session/store/sqlite.rb', line 74

def clear!
  @mutex.synchronize do
    db.execute("DELETE FROM #{TABLE_NAME}")
  end
end

#delete(id) ⇒ Object



56
57
58
59
60
# File 'lib/spurline/session/store/sqlite.rb', line 56

def delete(id)
  @mutex.synchronize do
    db.execute("DELETE FROM #{TABLE_NAME} WHERE id = ?", [id])
  end
end

#exists?(id) ⇒ Boolean

Returns:



62
63
64
65
66
# File 'lib/spurline/session/store/sqlite.rb', line 62

def exists?(id)
  @mutex.synchronize do
    !db.get_first_value("SELECT 1 FROM #{TABLE_NAME} WHERE id = ? LIMIT 1", [id]).nil?
  end
end

#idsObject



80
81
82
83
84
# File 'lib/spurline/session/store/sqlite.rb', line 80

def ids
  @mutex.synchronize do
    db.execute("SELECT id FROM #{TABLE_NAME} ORDER BY id").map { |row| row.fetch("id") }
  end
end

#load(id) ⇒ Object



46
47
48
49
50
51
52
53
54
# File 'lib/spurline/session/store/sqlite.rb', line 46

def load(id)
  row = @mutex.synchronize do
    db.get_first_row("SELECT data FROM #{TABLE_NAME} WHERE id = ? LIMIT 1", [id])
  end
  return nil unless row

  payload = row.fetch("data")
  @serializer.from_json(payload, store: self)
end

#save(session) ⇒ Object



21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
# File 'lib/spurline/session/store/sqlite.rb', line 21

def save(session)
  now = Time.now.utc.iso8601(6)
  payload = @serializer.to_json(session)

  @mutex.synchronize do
    db.execute(
      "        INSERT OR REPLACE INTO \#{TABLE_NAME}\n        (id, state, agent_class, created_at, updated_at, data)\n        VALUES (\n          ?,\n          ?,\n          ?,\n          COALESCE((SELECT created_at FROM \#{TABLE_NAME} WHERE id = ?), ?),\n          ?,\n          ?\n        )\n      SQL\n      [session.id, session.state.to_s, session.agent_class, session.id, now, now, payload]\n    )\n  end\n\n  session\nend\n",

#sizeObject



68
69
70
71
72
# File 'lib/spurline/session/store/sqlite.rb', line 68

def size
  @mutex.synchronize do
    db.get_first_value("SELECT COUNT(*) FROM #{TABLE_NAME}").to_i
  end
end