-
Notifications
You must be signed in to change notification settings - Fork 0
/
macros.go
77 lines (63 loc) · 1.49 KB
/
macros.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
package main
import (
"gorm.io/gorm"
"gorm.io/driver/sqlite"
"gorm.io/gorm/logger"
"log"
"errors"
)
var db *gorm.DB = nil
type Macro struct {
gorm.Model
Guild string
Name string
Expression string
}
func InitDB() {
log.SetPrefix("macros: ")
log.SetFlags(0)
var err error
db, err = gorm.Open(sqlite.Open("macros.db"), &gorm.Config{
Logger: logger.Default.LogMode(logger.Silent),
})
if err != nil {
log.Fatal(err)
}
db.AutoMigrate(&Macro{})
}
func FindMacro(guild string, name string) (*Macro, error) {
var macro Macro
result := db.Where("Guild = ? AND Name = ?", guild, name).First(¯o)
if result.Error != nil {
if errors.Is(result.Error, gorm.ErrRecordNotFound) {
return nil, errors.New("No rows found")
}
return nil, errors.New("Database error")
}
return ¯o, nil
}
func MakeMacro(macro *Macro) {
db.Create(macro)
}
func DeleteMacro(macro *Macro) {
db.Delete(macro)
}
func EditMacro(macro *Macro) {
db.Save(¯o)
}
func ListMacros(guild string) ([]Macro, error) {
var macros []Macro
result := db.Where("Guild = ?", guild).Order("Name").Find(¯os)
if result.Error != nil {
return nil, errors.New("Database error (possibly no rows found)")
}
return macros, nil
}
func ListMacrosByName(name string) ([]Macro, error) {
var macros []Macro
result := db.Where("Name = ?", name).Find(¯os)
if result.Error != nil {
return nil, errors.New("Database error (possibly no rows found)")
}
return macros, nil
}