summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
-rw-r--r--main.go28
-rw-r--r--setup.go38
2 files changed, 39 insertions, 27 deletions
diff --git a/main.go b/main.go
index 7306df2..fa0cd20 100644
--- a/main.go
+++ b/main.go
@@ -3,7 +3,6 @@
package main
import (
- "database/sql"
"log"
_ "github.com/mattn/go-sqlite3"
@@ -13,32 +12,9 @@ const rawDictionary = "/home/david/work/french-wiktionary-flashcards/raw-wiktext
const dictionary = "/home/david/work/french-wiktionary-flashcards/raw-wiktextract-data.sqlite3"
func main() {
- db, err := sql.Open("sqlite3", dictionary)
+ _, err := setupDatabase()
if err != nil {
- log.Fatalf("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 {
- log.Fatalf("creating table: %s", err)
- }
-
- _, err = db.Exec("PRAGMA synchronous = OFF;")
- if err != nil {
- log.Fatalf("setting risky writes: %s", err)
- }
-
- row := db.QueryRow(`SELECT count(*) as count from words`)
- var count int
- err = row.Scan(&count)
- if err != nil {
- log.Fatalf("counting rows: %s", err)
- }
- if count == 0 {
- if err = readDictionary(db); err != nil {
- log.Fatalf("failed to prepare dictionary: %s", err)
- }
+ log.Fatalf("setting up database: %s", err)
}
}
diff --git a/setup.go b/setup.go
index 6366921..4506282 100644
--- a/setup.go
+++ b/setup.go
@@ -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