-
Notifications
You must be signed in to change notification settings - Fork 123
/
db.go
277 lines (251 loc) · 5.44 KB
/
db.go
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
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
package main
import (
"errors"
"fmt"
"time"
"github.com/jmoiron/sqlx"
"modernc.org/sqlite"
)
var (
errNoMatches = errors.New("no conversations found")
errManyMatches = errors.New("multiple conversations matched the input")
)
func handleSqliteErr(err error) error {
sqerr := &sqlite.Error{}
if errors.As(err, &sqerr) {
return fmt.Errorf(
"%w: %s",
sqerr,
sqlite.ErrorCodeString[sqerr.Code()],
)
}
return err
}
func openDB(ds string) (*convoDB, error) {
db, err := sqlx.Open("sqlite", ds)
if err != nil {
return nil, fmt.Errorf(
"could not create db: %w",
handleSqliteErr(err),
)
}
if err := db.Ping(); err != nil {
return nil, fmt.Errorf(
"could not ping db: %w",
handleSqliteErr(err),
)
}
if _, err := db.Exec(`
CREATE TABLE
IF NOT EXISTS conversations (
id string NOT NULL PRIMARY KEY,
title string NOT NULL,
updated_at datetime NOT NULL DEFAULT (strftime ('%Y-%m-%d %H:%M:%f', 'now')),
CHECK (id <> ''),
CHECK (title <> '')
)
`); err != nil {
return nil, fmt.Errorf("could not migrate db: %w", err)
}
if _, err := db.Exec(`
CREATE INDEX IF NOT EXISTS idx_conv_id ON conversations (id)
`); err != nil {
return nil, fmt.Errorf("could not migrate db: %w", err)
}
if _, err := db.Exec(`
CREATE INDEX IF NOT EXISTS idx_conv_title ON conversations (title)
`); err != nil {
return nil, fmt.Errorf("could not migrate db: %w", err)
}
if !hasColumn(db, "model") {
if _, err := db.Exec(`
ALTER TABLE conversations ADD COLUMN model string
`); err != nil {
return nil, fmt.Errorf("could not migrate db: %w", err)
}
}
return &convoDB{db: db}, nil
}
func hasColumn(db *sqlx.DB, col string) bool {
var count int
if err := db.Get(&count, `
SELECT count(*)
FROM pragma_table_info('conversations') c
WHERE c.name = $1
`, col); err != nil {
return false
}
return count > 0
}
type convoDB struct {
db *sqlx.DB
}
// Conversation in the database.
type Conversation struct {
ID string `db:"id"`
Title string `db:"title"`
UpdatedAt time.Time `db:"updated_at"`
Model *string `db:"model"`
}
func (c *convoDB) Close() error {
return c.db.Close() //nolint: wrapcheck
}
func (c *convoDB) Save(id, title, model string) error {
res, err := c.db.Exec(c.db.Rebind(`
UPDATE conversations
SET
title = ?,
model = ?,
updated_at = CURRENT_TIMESTAMP
WHERE
id = ?
`), title, model, id)
if err != nil {
return fmt.Errorf("Save: %w", err)
}
rows, err := res.RowsAffected()
if err != nil {
return fmt.Errorf("Save: %w", err)
}
if rows > 0 {
return nil
}
if _, err := c.db.Exec(c.db.Rebind(`
INSERT INTO
conversations (id, title, model)
VALUES
(?, ?, ?)
`), id, title, model); err != nil {
return fmt.Errorf("Save: %w", err)
}
return nil
}
func (c *convoDB) Delete(id string) error {
if _, err := c.db.Exec(c.db.Rebind(`
DELETE FROM conversations
WHERE
id = ?
`), id); err != nil {
return fmt.Errorf("Delete: %w", err)
}
return nil
}
func (c *convoDB) ListOlderThan(t time.Duration) ([]Conversation, error) {
var convos []Conversation
if err := c.db.Select(&convos, c.db.Rebind(`
SELECT
*
FROM
conversations
WHERE
updated_at < ?
`), time.Now().Add(-t)); err != nil {
return nil, fmt.Errorf("ListOlderThan: %w", err)
}
return convos, nil
}
func (c *convoDB) FindHEAD() (*Conversation, error) {
var convo Conversation
if err := c.db.Get(&convo, `
SELECT
*
FROM
conversations
ORDER BY
updated_at DESC
LIMIT
1
`); err != nil {
return nil, fmt.Errorf("FindHead: %w", err)
}
return &convo, nil
}
func (c *convoDB) findByExactTitle(result *[]Conversation, in string) error {
if err := c.db.Select(result, c.db.Rebind(`
SELECT
*
FROM
conversations
WHERE
title = ?
`), in); err != nil {
return fmt.Errorf("findByExactTitle: %w", err)
}
return nil
}
func (c *convoDB) findByIDOrTitle(result *[]Conversation, in string) error {
if err := c.db.Select(result, c.db.Rebind(`
SELECT
*
FROM
conversations
WHERE
id glob ?
OR title = ?
`), in+"*", in); err != nil {
return fmt.Errorf("findByIDOrTitle: %w", err)
}
return nil
}
func (c *convoDB) Completions(in string) ([]string, error) {
var result []string
if err := c.db.Select(&result, c.db.Rebind(`
SELECT
printf (
'%s%c%s',
CASE
WHEN length (?) < ? THEN substr (id, 1, ?)
ELSE id
END,
char(9),
title
)
FROM
conversations
WHERE
id glob ?
UNION
SELECT
printf ("%s%c%s", title, char(9), substr (id, 1, ?))
FROM
conversations
WHERE
title glob ?
`), in, sha1short, sha1short, in+"*", sha1short, in+"*"); err != nil {
return result, fmt.Errorf("Completions: %w", err)
}
return result, nil
}
func (c *convoDB) Find(in string) (*Conversation, error) {
var conversations []Conversation
var err error
if len(in) < sha1minLen {
err = c.findByExactTitle(&conversations, in)
} else {
err = c.findByIDOrTitle(&conversations, in)
}
if err != nil {
return nil, fmt.Errorf("Find: %w", err)
}
if len(conversations) > 1 {
return nil, errManyMatches
}
if len(conversations) == 1 {
return &conversations[0], nil
}
return nil, errNoMatches
}
func (c *convoDB) List() ([]Conversation, error) {
var convos []Conversation
if err := c.db.Select(&convos, `
SELECT
*
FROM
conversations
ORDER BY
updated_at DESC
`); err != nil {
return convos, fmt.Errorf("List: %w", err)
}
return convos, nil
}