summary refs log tree commit diff stats
path: root/storage/sqlite3/init.go
blob: d1990318fecc6ca5192f2cbbe2f37623453b1251 (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
64
65
66
67
68
69
70
71
72
73
74
package sqlite3

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

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

// DB holds the database connection, mutex & path.
type DB struct {
	Path string
	Mu   *sync.RWMutex
	Conn *sql.DB
}

// 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())
}

// Init initializes a sqlite3 database.
func Init(db *DB) {
	var err error

	// We set the database path, first the environment variable
	// PERSEUS_DBPATH is checked. If it doesn't exist then use set
	// it to the default (perseus.db).
	envDBPath, exists := os.LookupEnv("PERSEUS_DBPATH")
	if !exists {
		envDBPath = "perseus.db"
	}
	db.Path = envDBPath

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

	// Create account table, this will hold information on account
	// like id, type & other user specific information. We are
	// using id because later we may want to add username change
	// or account delete functionality. If we add user delete
	// function then we'll just have to change the username here.
	stmt, err := db.Conn.Prepare(`
CREATE TABLE IF NOT EXISTS account (
       id       TEXT PRIMARY KEY,
       type     TEXT NOT NULL DEFAULT user,
       username TEXT NOT NULL,
       password TEXT NOT NULL);`)

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

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