summaryrefslogtreecommitdiff
path: root/golang/pkg/database/migrations.go
blob: 94207a542e183616bc70c73d352d170dd08992c8 (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
package database

import (
	"context"
	"database/sql"
	"embed"
	"io/fs"

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

type DB struct {
	ctx context.Context
	db  *sql.DB
}

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

func DBInit(ctx context.Context, url string) (myDB *DB, err error) {
	var db *sql.DB
	if db, err = sql.Open("sqlite3", url); err != nil {
		return nil, err
	}
	defer func() {
		if err != nil {
			_ = db.Close()
		}
	}()

	if _, err = db.ExecContext(ctx, "PRAGMA foreign_keys = ON"); err != nil {
		return nil, err
	}
	if _, err = db.ExecContext(ctx, "PRAGMA journal_mode = WAL"); err != nil {
		return nil, err
	}

	var version int
	if err = db.QueryRowContext(ctx, `SELECT version FROM schema_version;`).Scan(&version); err != nil {
		if err.Error() == "no such table: schema_version" {
			version = 0
		} else {
			return nil, err
		}
	}

	statements := make([]string, 0)
	err = fs.WalkDir(schemaFiles, ".", func(path string, d fs.DirEntry, err error) error {
		if d.IsDir() || err != nil {
			return err
		}
		var stmts []byte
		if stmts, err = schemaFiles.ReadFile(path); err != nil {
			return err
		} else {
			statements = append(statements, string(stmts))
		}
		return nil
	})
	if err != nil {
		return nil, err
	}

	for version < len(statements) {
		if _, err = db.ExecContext(ctx, statements[version]); err != nil {
			return nil, err
		}
		version++
	}
	if _, err = db.ExecContext(ctx, `DELETE FROM schema_version; INSERT INTO schema_version (version) VALUES (?);`, version); err != nil {
		return nil, err
	}
	return &DB{ctx: ctx, db: db}, nil
}

func (db *DB) Close() error {
	return db.db.Close()
}