summary refs log tree commit diff stats
path: root/storage/init.go
blob: 9894c5b53124860b9638dc6e67f78cbb77353933 (plain) (blame)
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
package storage

import (
	"database/sql"
	"fmt"
	"log"

	_ "github.com/mattn/go-sqlite3"
)

// initErr will log the error and close the database connection if
// necessary.
func initErr(db *DB, err error) {
	if db.Conn != nil {
		db.Conn.Close()
	}
	log.Fatalf("Initialization Error :: %s", err.Error())
}

func initDB(db *DB) {
	var err error

	db.Path = fmt.Sprintf("%s/grus.db", GetDir())

	db.Conn, err = sql.Open("sqlite3", db.Path)
	if err != nil {
		log.Printf("storage/init.go: %s\n",
			"Failed to open database connection")
		initErr(db, err)
	}

	sqlstmt := []string{
		`CREATE TABLE IF NOT EXISTS words (
        word   TEXT PRIMARY KEY NOT NULL,
        sorted TEXT NOT NULL);`,
		`INSERT INTO words(word, lexical)
        values("grus", "grsu");`,
	}

	// We range over statements and execute them one by one, this
	// is during initialization so it doesn't matter if it takes
	// few more ms. This way we know which statement caused the
	// program to fail.
	for _, s := range sqlstmt {
		stmt, err := db.Conn.Prepare(s)

		if err != nil {
			log.Printf("storage/init.go: %s\n",
				"failed to prepare statement")
			log.Println(s)
			initErr(db, err)
		}

		_, err = stmt.Exec()
		stmt.Close()
		if err != nil {
			log.Printf("storage/init.go: %s\n",
				"failed to execute statement")
			log.Println(s)
			initErr(db, err)
		}
	}
}