summaryrefslogtreecommitdiff
path: root/storage/memory.go
blob: 088ce1c7c43e8f41219e7885424131492ac51d6e (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
package storage

import "elefant/models"

type Memories interface {
	Memorise(m *models.Memory) (*models.Memory, error)
	Recall(agent, topic string) (string, error)
	RecallTopics(agent string) ([]string, error)
}

func (p ProviderSQL) Memorise(m *models.Memory) (*models.Memory, error) {
	query := "INSERT INTO memories (agent, topic, mind) VALUES (:agent, :topic, :mind) RETURNING *;"
	stmt, err := p.db.PrepareNamed(query)
	if err != nil {
		p.logger.Error("failed to prepare stmt", "query", query, "error", err)
		return nil, err
	}
	defer stmt.Close()
	var memory models.Memory
	err = stmt.Get(&memory, m)
	if err != nil {
		p.logger.Error("failed to insert memory", "query", query, "error", err)
		return nil, err
	}
	return &memory, nil
}

func (p ProviderSQL) Recall(agent, topic string) (string, error) {
	query := "SELECT mind FROM memories WHERE agent = $1 AND topic = $2"
	var mind string
	err := p.db.Get(&mind, query, agent, topic)
	if err != nil {
		p.logger.Error("failed to get memory", "query", query, "error", err)
		return "", err
	}
	return mind, nil
}

func (p ProviderSQL) RecallTopics(agent string) ([]string, error) {
	query := "SELECT DISTINCT topic FROM memories WHERE agent = $1"
	var topics []string
	err := p.db.Select(&topics, query, agent)
	if err != nil {
		p.logger.Error("failed to get topics", "query", query, "error", err)
		return nil, err
	}
	return topics, nil
}