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
|
package main
import (
"database/sql"
"errors"
"fmt"
"strings"
tea "github.com/charmbracelet/bubbletea"
)
func lookupWord(db *sql.DB, word string) tea.Cmd {
return func() tea.Msg {
word = strings.TrimSpace(word) // remove leading / trailing whitespace
// Replace apostrophes (possible if copy-pasting) with single quotes
word = strings.ReplaceAll(word, `’`, `'`)
rows, err := db.Query(`select definition from words where word = ?`, word)
if err != nil {
if errors.Is(err, sql.ErrNoRows) {
return definitionMsg("")
}
return errMsg(fmt.Errorf("looking up '%s': %s", word, err))
}
defer rows.Close()
var combinedDefinition []string
for rows.Next() {
var definition string
err = rows.Scan(&definition)
if err != nil {
return errMsg(fmt.Errorf("looking up '%s': %s", word, err))
}
combinedDefinition = append(combinedDefinition, definition)
}
if err := rows.Err(); err != nil {
return errMsg(fmt.Errorf("looking up '%s': %s", word, err))
}
return definitionMsg(strings.Join(combinedDefinition, "\n\n"))
}
}
|