/
store.go
187 lines (162 loc) · 4.71 KB
/
store.go
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
175
176
177
178
179
180
181
182
183
184
185
186
187
// Copyright 2022 European Digital Reading Lab. All rights reserved.
// Use of this source code is governed by a BSD-style license
// specified in the Github project LICENSE file.
// The stor package manages the storage of our entities.
package stor
import (
"fmt"
"log"
"os"
"strings"
"time"
"gorm.io/gorm"
"gorm.io/gorm/logger"
)
type (
// generic store
dbStore struct {
db *gorm.DB
}
// entity stores
publicationStore dbStore
licenseStore dbStore
eventStore dbStore
// Store interface, giving access to specialized interfaces
Store interface {
Publication() PublicationRepository
License() LicenseRepository
Event() EventRepository
}
// PublicationRepository interface, defining publication operations
PublicationRepository interface {
ListAll() (*[]Publication, error)
List(pageNum, pageSize int) (*[]Publication, error)
FindByType(contentType string) (*[]Publication, error)
Count() (int64, error)
Get(uuid string) (*Publication, error)
Create(p *Publication) error
Update(p *Publication) error
Delete(p *Publication) error
}
// LicenseRepository interface, defining license operations
LicenseRepository interface {
ListAll() (*[]LicenseInfo, error)
List(pageNum, pageSize int) (*[]LicenseInfo, error)
FindByUser(userID string) (*[]LicenseInfo, error)
FindByPublication(publicationID string) (*[]LicenseInfo, error)
FindByStatus(status string) (*[]LicenseInfo, error)
FindByDeviceCount(min int, max int) (*[]LicenseInfo, error)
Count() (int64, error)
Get(uuid string) (*LicenseInfo, error)
Create(p *LicenseInfo) error
Update(p *LicenseInfo) error
Delete(p *LicenseInfo) error
}
// EventRepository interface, defining event operations
EventRepository interface {
List(licenseID string) (*[]Event, error)
GetRegisterByDevice(licenseID string, deviceID string) (*Event, error)
Count(licenseID string) (int64, error)
Get(id uint) (*Event, error)
Create(e *Event) error
Update(e *Event) error
Delete(e *Event) error
}
)
// implementation of the different repository interfaces
func (s *dbStore) Publication() PublicationRepository {
return (*publicationStore)(s)
}
func (s *dbStore) License() LicenseRepository {
return (*licenseStore)(s)
}
func (s *dbStore) Event() EventRepository {
return (*eventStore)(s)
}
// List of status values as strings
const (
STATUS_READY = "ready"
STATUS_ACTIVE = "active"
STATUS_REVOKED = "revoked"
STATUS_RETURNED = "returned"
STATUS_CANCELLED = "cancelled"
STATUS_EXPIRED = "expired"
EVENT_REGISTER = "register"
EVENT_RENEW = "renew"
EVENT_RETURN = "return"
EVENT_REVOKE = "revoke"
EVENT_CANCEL = "cancel"
)
// Init initializes the database
func Init(dsn string) (Store, error) {
var err error
dialect, cnx := dbFromURI(dsn)
if dialect == "error" {
return nil, fmt.Errorf("incorrect database source name: %q", dsn)
}
// the use of time.Time fields for mysql requires parseTime
if dialect == "mysql" && !strings.Contains(cnx, "parseTime") {
return nil, fmt.Errorf("incomplete mysql database source name, parseTime required: %q", dsn)
}
// Any constraint for other databases?
// database logger
newLogger := logger.New(
log.New(os.Stdout, "\r\n", log.LstdFlags), // io writer
logger.Config{
SlowThreshold: time.Second, // Slow SQL threshold
LogLevel: logger.Warn, // Log level (Silent, Error, Warn, Info)
IgnoreRecordNotFoundError: true, // Ignore ErrRecordNotFound error for logger
Colorful: true, // Enable color
},
)
db, err := gorm.Open(GormDialector(cnx), &gorm.Config{
Logger: newLogger,
})
if err != nil {
log.Printf("Failed connecting to the database: %v", err)
return nil, err
}
err = performDialectSpecific(db, dialect)
if err != nil {
log.Printf("Failed performing dialect specific database init: %v", err)
return nil, err
}
err = db.AutoMigrate(&Publication{}, &LicenseInfo{}, &Event{})
if err != nil {
log.Printf("Failed performing database automigrate: %v", err)
return nil, err
}
stor := &dbStore{db: db}
return stor, nil
}
// dbFromURI
func dbFromURI(uri string) (string, string) {
parts := strings.Split(uri, "://")
if len(parts) != 2 {
return "error", ""
}
return parts[0], parts[1]
}
// performDialectSpecific
func performDialectSpecific(db *gorm.DB, dialect string) error {
switch dialect {
case "sqlite3":
err := db.Exec("PRAGMA journal_mode = WAL").Error
if err != nil {
return err
}
err = db.Exec("PRAGMA foreign_keys = ON").Error
if err != nil {
return err
}
case "mysql":
// nothing , so far
case "postgres":
// nothing , so far
case "mssql":
// nothing , so far
default:
return fmt.Errorf("invalid dialect: %s", dialect)
}
return nil
}