summaryrefslogtreecommitdiff
path: root/db/main.go
blob: 49658cd8be0d13d50f301cd0beff08c4e0fece7d (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
75
76
77
package db

import (
	"database/sql"
	"os"
	"path/filepath"
	"sync"

	"github.com/go-playground/validator/v10"
	_ "github.com/mattn/go-sqlite3"
)

type SafeDB struct {
	mu       sync.Mutex
	validate *validator.Validate

	path string
	db   *sql.DB
}

func (safe *SafeDB) setupPath() error {
	const path string = "/var/lib/redq/"
	const name string = "redq.sqlite3"

	err := os.MkdirAll(path, os.ModeDir)
	if err != nil {
		return err
	}

	safe.path = filepath.Join(path, name)
	return nil
}

func NewSafeDB() (*SafeDB, error) {
	const create string = `
		CREATE TABLE IF NOT EXISTS Accounts(
			id        INTEGER PRIMARY KEY,
			UserName  CHAR(64)	NOT NULL UNIQUE,
			Password  CHAR(128)	NOT NULL,

			Level     INTEGER	NOT NULL,
			FirstName CHAR(32)	NOT NULL,
			LastName  CHAR(32)	NOT NULL
		);

		CREATE TABLE IF NOT EXISTS Bearer(
			id	  INTEGER PRIMARY KEY,
			Token     CHAR(128)	NOT NULL UNIQUE,
			ValidUpTo TIME		NOT NULL,
			accountId INTEGER	NOT NULL,

			FOREIGN KEY (accountId)
			REFERENCES Accounts (id)
		);
	`
	safe := &SafeDB{}
	err := safe.setupPath()
	if err != nil {
		return nil, err
	}

	safe.mu.Lock()
	defer safe.mu.Unlock()

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

	_, err = safe.db.Exec(create)
	if err != nil {
		return nil, err
	}

	safe.validate = validator.New(validator.WithRequiredStructEnabled())
	return safe, nil
}