summaryrefslogtreecommitdiff
path: root/model/dbmodel.go
blob: a4f4e4adae35df3c3042d86f1cf9731cf7623437 (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
package model

import (
	"errors"
	"fmt"
	"github.com/kch42/mailremind/schedule"
	"sync"
	"time"
)

var (
	NotFound = errors.New("Not Found")
)

type DBID interface {
	fmt.Stringer
}

type User interface {
	ID() DBID
	Email() string

	PWHash() []byte
	SetPWHash([]byte) error

	AddJob(subject string, content []byte, sched schedule.MultiSchedule, next time.Time) (Job, error)
	Jobs() []Job
	JobByID(DBID) (Job, error)
	CountJobs() int

	Active() bool
	SetActive(bool) error

	ActivationCode() string
	SetActivationCode(string) error

	Location() *time.Location
	SetLocation(*time.Location) error

	Delete() error
}

type Job interface {
	ID() DBID
	User() User

	Subject() string
	SetSubject(string) error

	Content() []byte
	SetContent([]byte) error

	Schedule() schedule.MultiSchedule
	SetSchedule(schedule.MultiSchedule) error

	Next() time.Time
	SetNext(time.Time) error

	Delete() error
}

type DBCon interface {
	Close()

	UserByID(DBID) (User, error)
	UserByMail(string) (User, error)

	AddUser(email string, pwhash []byte, location *time.Location, active bool, acCode string) (User, error)

	InactiveUsers(olderthan time.Time) []DBID

	JobsBefore(t time.Time) []Job // Get Jobs with next <= t
}

type DBInfo struct {
	Connect   func(dbconf string) (DBCon, error)
	ParseDBID func(string) (DBID, error)
}

var dbinfos map[string]DBInfo
var dbinfoInit sync.Once

func Register(name string, dbinfo DBInfo) {
	dbinfoInit.Do(func() {
		dbinfos = make(map[string]DBInfo)
	})

	dbinfos[name] = dbinfo
}

func GetDBInfo(name string) (DBInfo, bool) {
	dbinfo, ok := dbinfos[name]
	return dbinfo, ok
}

func AllDatabases() []string {
	names := make([]string, 0, len(dbinfos))
	for name := range dbinfos {
		names = append(names, name)
	}
	return names
}