summaryrefslogtreecommitdiff
path: root/model/database.go
blob: 16a6ceaa8780fe8541456b9fc83753452177b607 (plain)
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
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
package model

import (
	"database/sql"
	"embed"
	"log"

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

var db *sql.DB

//go:embed sql/*.sql
var sqlCode embed.FS

func GetSql(code string) (string, error) {
	query, err := sqlCode.ReadFile("sql/" + code + ".sql")
	if err != nil {
		return "", err
	}

	return string(query), nil
}

func ConnectDatabase(path string) {
	var err error

	db, err = sql.Open("sqlite3", path)
	if err != nil {
		log.Fatal(err)
	}

	err = db.Ping()
	if err != nil {
		log.Fatal(err)
	}
}

func Transaction(f func(*sql.Tx) error) error {
	tx, err := db.Begin()
	if err != nil {
		log.Printf("Failed to start database transaction: %v", err)
		return err
	}
	defer func() {
		if tx.Rollback() == nil {
			log.Println("Rolled back transaction")
		}
	}()

	err = f(tx)
	if err != nil {
		log.Printf("Failed transaction: %v", err)
		return err
	}

	return tx.Commit()
}

func isDatabaseEmpty(tx *sql.Tx) bool {
	cmd := `SELECT COUNT(*) FROM sqlite_master WHERE type='table'`
	rows, err := tx.Query(cmd)
	if err != nil {
		log.Fatal(err)
	}
	defer rows.Close()

	if !rows.Next() {
		log.Fatalf("No rows on request of database table number")
	}

	var number int
	err = rows.Scan(&number)
	if err != nil {
		log.Fatalf("Failed to scan number of database tables to integer")
	}

	return number == 0
}

func MigrateDatabase() {
	err := Transaction(func(tx *sql.Tx) error {
		if isDatabaseEmpty(tx) {
			log.Println("Starting with empty database")
		}

		query, err := GetSql(`migrate`)
		if err != nil {
			log.Fatal(err)
		}
		_, err = tx.Exec(query)
		if err != nil {
			return err
		}
		return nil
	})
	if err != nil {
		log.Fatalf("Fatal: Database migration failed")
	}
}

func InjectTestRecipes() {
	Transaction(func(tx *sql.Tx) error {
		recipes := RecipeTestData()

		for _, recipe := range recipes {
			err := recipe.Create(tx)
			if err != nil {
				return err
			}
		}

		return nil
	})
}

func DisconnectDatabase() {
	var err error = db.Close()
	if err != nil {
		log.Printf("Failed to close database: %v\n", err)
	} else {
		log.Println("Closed database")
	}
}