~evanj/cms

ref: 7fc5d7258891c1c58ba07d1e9035517327be7a19 cms/internal/s/db/db.go -rw-r--r-- 1.2 KiB
7fc5d725Evan M Jones WIP(*): Project init. 10 months ago
                                                                                
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
package db

import (
	"database/sql"
	"log"

	"git.sr.ht/~evanj/security"
	_ "github.com/mattn/go-sqlite3"
)

const (
	perPage = 25
)

type DB struct {
	*sql.DB
	log *log.Logger
	sec securer
}

type securer interface {
	TokenCreate(val security.TokenMap) (string, error)
	TokenFrom(tokenString string) (security.TokenMap, error)
	HashCreate(salt, pass string) (string, error)
	HashCompare(salt, pass, hash string) error
}

func New(log *log.Logger, typ, creds string, sec securer) (*DB, error) {
	conn, err := sql.Open(typ, creds)
	if err != nil {
		return nil, err
	}

	db := &DB{
		conn,
		log,
		sec,
	}

	return db, nil
}

func (db *DB) EnsureSetup() error {
	var _ interface{}

	// user
	_, _ = db.Exec(`
		CREATE TABLE cms_user (
			ID INTEGER PRIMARY KEY AUTOINCREMENT,
			NAME TEXT UNIQUE NOT NULL,
			HASH TEXT NOT NULL
		);
	`)

	// space
	_, _ = db.Exec(`
		CREATE TABLE cms_space (
			ID INTEGER PRIMARY KEY AUTOINCREMENT,
			NAME TEXT NOT NULL,
			DESC TEXT NOT NULL
		);
	`)

	// user to space
	_, _ = db.Exec(`
		CREATE TABLE cms_user_to_space (
			ID INTEGER PRIMARY KEY AUTOINCREMENT,
			USER_ID INTEGER,
			SPACE_ID INTEGER,
			FOREIGN KEY(USER_ID) REFERENCES cms_user(ID),
			FOREIGN KEY(SPACE_ID) REFERENCES cms_space(ID)
		);
	`)

	return nil
}