A simple Russian-to-English dictionary written just for fun
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
This repo is archived. You can view files and clone it, but cannot push or open issues/pull-requests.
dict_go/internal/db.go

86 lines
1.6 KiB

package internal
import (
"database/sql"
"log"
)
func initDatabase(path string) *sql.DB {
db, err := sql.Open("sqlite3", "file:"+path)
if err != nil {
log.Fatalln(err.Error())
}
_, sqlerr := db.Exec(`
CREATE TABLE IF NOT EXISTS words (
english VARCHAR(255),
russian VARCHAR(255)
)
`)
if sqlerr != nil {
log.Fatalln(err.Error())
}
return db
}
func insertWord(db *sql.DB, word *Word) error {
_, err := db.Exec(`
INSERT INTO words (
english,
russian
) VALUES (
?,
?
)
`, word.English, word.Russian)
return err
}
func deleteWord(db *sql.DB, word *Word) (int, error) {
result, err := db.Exec(`
DELETE FROM words
WHERE english = ? OR russian = ?
`, word.English, word.Russian)
deleted, _ := result.RowsAffected()
return int(deleted), err
}
func lookupWord(db *sql.DB, word *Word) error {
row := db.QueryRow(`
SELECT
english, russian
FROM words
WHERE english LIKE ? COLLATE NOCASE
OR russian LIKE ? COLLATE NOCASE
LIMIT 1
`, "%"+word.English+"%", "%"+word.Russian+"%")
err := row.Scan(
&word.English,
&word.Russian,
)
return err
}
func getAllWords(db *sql.DB) ([]*Word, error) {
rows, err := db.Query(`
SELECT
english, russian
FROM words
`)
defer rows.Close()
l := 1
// instead of appending to a slice (and reallocating memory every time), we
// increase the capacity of the slice by 2 every time we hit the capacity
words := make([]*Word, 0, l)
for i := 1; rows.Next(); i++ {
if i > l {
t := make([]*Word, len(words), l*2)
copy(t, words)
words = t
l *= 2
}
word := Word{}
rows.Scan(&word.English, &word.Russian)
words = append(words, &word)
}
return words, err
}