summaryrefslogtreecommitdiff
path: root/model/database.go
blob: d3fc115987db325055d1adfe5fb59215599de832 (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
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
package model

import (
	"database/sql"
	"log"

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

	"xengineering.eu/ceres/model/migrations"
)

type DB sql.DB

func OpenDB(path string) *DB {
	db, err := sql.Open("sqlite3", path)
	if err != nil {
		log.Fatal(err)
	}

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

	return (*DB)(db)
}

func (db *DB) Transaction(f func(*sql.Tx) error) error {
	tx, err := (*sql.DB)(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 (db *DB) IsEmpty() bool {
	var number int

	_ = db.Transaction(func(tx *sql.Tx) error {
		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")
		}

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

		return nil
	})

	return number == 0
}

func (db *DB) setupMinimal(execVersion string) error {
	return db.Transaction(func(tx *sql.Tx) error {
		cmd := `
CREATE TABLE metadata (
	key   TEXT PRIMARY KEY,
	value TEXT
);
INSERT INTO metadata
	(key, value)
VALUES
	('version', ?);
`
		_, err := tx.Exec(cmd, execVersion)
		return err
	})
}

func (db *DB) Version() string {
	var version string

	_ = db.Transaction(func(tx *sql.Tx) error {
		rows, err := tx.Query(`SELECT value FROM metadata WHERE key='version';`)
		if err != nil {
			log.Fatal(err)
		}
		defer rows.Close()

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

		err = rows.Scan(&version)
		if err != nil {
			log.Fatalf("Failed to scan database version to string")
		}

		return nil
	})

	return version
}

func (db *DB) Migrate(execVersion string) {
	err := db.Transaction(func(tx *sql.Tx) error {
		if db.IsEmpty() {
			log.Println("Starting with empty database")
			err := db.setupMinimal(execVersion)
			if err != nil {
				log.Fatalf("Failed to setup minimal database schema: %v", err)
			}

			log.Println("Executing initial migration")
			err = migrations.Migration001(tx)
			if err != nil {
				return err
			}
		}

		dbVersion := db.Version()
		if dbVersion != execVersion {
			log.Fatalf(
				"Database version '%s' does not match executable version '%s'",
				dbVersion,
				execVersion,
			)
		}

		return nil
	})
	if err != nil {
		log.Fatalf("Fatal: Database migration failed")
	}
}

func (db *DB) CreateExamples() {
	err := db.Transaction(func(tx *sql.Tx) error {
		recipes := RecipeTestData()

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

		return nil
	})
	if err != nil {
		log.Fatalf("Failed to inject example recipes: %v", err)
	}
}

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