forked from charmbracelet/mods
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathdb.go
222 lines (200 loc) · 4.5 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
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)
}
return &convoDB{db: db}, nil
}
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"`
}
func (c *convoDB) Close() error {
return c.db.Close() //nolint: wrapcheck
}
func (c *convoDB) Save(id, title string) error {
res, err := c.db.Exec(c.db.Rebind(`
update conversations
set title = ?, updated_at = current_timestamp
where id = ?
`), title, 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)
values (?, ?)
`), id, title); 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) 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
}