Class: Llmemory::ShortTerm::Stores::PostgresStore

Inherits:
Base
  • Object
show all
Includes:
Crypto::FieldHelpers
Defined in:
lib/llmemory/short_term/stores/postgres_store.rb

Instance Method Summary collapse

Constructor Details

#initialize(database_url: nil, cipher: nil) ⇒ PostgresStore

Returns a new instance of PostgresStore.



12
13
14
15
16
# File 'lib/llmemory/short_term/stores/postgres_store.rb', line 12

def initialize(database_url: nil, cipher: nil)
  @database_url = database_url || Llmemory.configuration.database_url
  @connection = nil
  @cipher = cipher || Llmemory.build_cipher
end

Instance Method Details

#delete(user_id, session_id) ⇒ Object



42
43
44
45
46
47
48
49
# File 'lib/llmemory/short_term/stores/postgres_store.rb', line 42

def delete(user_id, session_id)
  ensure_table!
  conn.exec_params(
    "DELETE FROM llmemory_checkpoints WHERE user_id = $1 AND session_id = $2",
    [user_id, session_id]
  )
  true
end

#list_sessions(user_id:) ⇒ Object



57
58
59
60
61
62
63
64
# File 'lib/llmemory/short_term/stores/postgres_store.rb', line 57

def list_sessions(user_id:)
  ensure_table!
  result = conn.exec_params(
    "SELECT session_id FROM llmemory_checkpoints WHERE user_id = $1",
    [user_id]
  )
  result.map { |r| r["session_id"] }
end

#list_usersObject



51
52
53
54
55
# File 'lib/llmemory/short_term/stores/postgres_store.rb', line 51

def list_users
  ensure_table!
  result = conn.exec("SELECT DISTINCT user_id FROM llmemory_checkpoints")
  result.map { |r| r["user_id"] }
end

#load(user_id, session_id) ⇒ Object



32
33
34
35
36
37
38
39
40
# File 'lib/llmemory/short_term/stores/postgres_store.rb', line 32

def load(user_id, session_id)
  ensure_table!
  result = conn.exec_params(
    "SELECT state FROM llmemory_checkpoints WHERE user_id = $1 AND session_id = $2",
    [user_id, session_id]
  )
  row = result.first
  row ? deserialize(row["state"]) : nil
end

#save(user_id, session_id, state) ⇒ Object



18
19
20
21
22
23
24
25
26
27
28
29
30
# File 'lib/llmemory/short_term/stores/postgres_store.rb', line 18

def save(user_id, session_id, state)
  ensure_table!
  conn.exec_params(
    <<~SQL,
      INSERT INTO llmemory_checkpoints (user_id, session_id, state, updated_at)
      VALUES ($1, $2, $3, $4)
      ON CONFLICT (user_id, session_id)
      DO UPDATE SET state = $3, updated_at = $4
    SQL
    [user_id, session_id, serialize(state), Time.now.utc.iso8601]
  )
  true
end