diff options
| author | David Schlachter <t480-debian-git@schlachter.ca> | 2026-01-07 23:14:56 -0500 |
|---|---|---|
| committer | David Schlachter <t480-debian-git@schlachter.ca> | 2026-01-07 23:14:56 -0500 |
| commit | 729eca86cd34c1d93c220315e4736836634f84ed (patch) | |
| tree | 1ee82db4a01aa8fd5f57699ab83adf35ec151a33 /setup.go | |
| parent | da81f01d67fcc0d40abd95367d9d049d79c7cd21 (diff) | |
Move all DB setup to its own file
Diffstat (limited to 'setup.go')
| -rw-r--r-- | setup.go | 38 |
1 files changed, 37 insertions, 1 deletions
@@ -12,6 +12,42 @@ import ( "github.com/goccy/go-json" ) +func setupDatabase() (*sql.DB, error) { + db, err := sql.Open("sqlite3", dictionary) + if err != nil { + return nil, fmt.Errorf("opening DB '%s': %s", dictionary, err) + } + defer db.Close() + + _, err = db.Exec("create table IF NOT EXISTS words (word text not null, definition text);") + if err != nil { + return nil, fmt.Errorf("creating table: %s", err) + } + + row := db.QueryRow(`SELECT count(*) as count from words`) + var count int + err = row.Scan(&count) + if err != nil { + return nil, fmt.Errorf("counting rows: %s", err) + } + + // Only populate the database if it is empty. + if count > 0 { + return db, nil + } + + // Faster import performance. + _, err = db.Exec("PRAGMA synchronous = OFF;") + if err != nil { + return nil, fmt.Errorf("setting risky writes: %s", err) + } + + if err = populateDictionary(db); err != nil { + return nil, fmt.Errorf("failed to prepare dictionary: %s", err) + } + return db, nil +} + type rawDictionaryEntry struct { Word string `json:"word"` LangCode string `json:"lang_code"` @@ -49,7 +85,7 @@ type SenseForDictionaryEntry struct { Example string } -func readDictionary(db *sql.DB) error { +func populateDictionary(db *sql.DB) error { log.Printf("preparing list of dictionary words...") // Set up the template |
