-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathinstance.go
More file actions
151 lines (109 loc) · 2.36 KB
/
instance.go
File metadata and controls
151 lines (109 loc) · 2.36 KB
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
package dbo
import (
"context"
"errors"
"fmt"
"strings"
"gorm.io/gorm"
)
type SeederEntry interface {
Name() string
Handler(db *gorm.DB) (err error)
}
type Instance interface {
Get(options ...DB) (db *gorm.DB, err error)
WithCancel(options ...DB) (db *gorm.DB, cancel context.CancelFunc, err error)
Migrate(models ...any) (err error)
Seed(entries ...SeederEntry) (err error)
}
type xInstance struct {
opts Options
db *gorm.DB
}
func (x *xInstance) New() *gorm.DB {
return NewSession(x.db)
}
func (x *xInstance) Get(options ...DB) (db *gorm.DB, err error) {
opts := x.dbOptions(options...)
if db = opts.DB; db == nil {
db = x.New()
}
if db == nil {
err = errors.New("Database connection not found")
return
}
// Add Clauses
if len(opts.Clauses) > 0 {
db = db.Clauses(opts.Clauses...).Session(&gorm.Session{})
}
// Add Scopes
if len(opts.Scopes) > 0 {
db = db.Scopes(opts.Scopes...).Session(&gorm.Session{})
}
return
}
func (x *xInstance) WithCancel(options ...DB) (db *gorm.DB, cancel context.CancelFunc, err error) {
opts := x.dbOptions(options...)
db, err = x.Get(opts)
if err != nil {
return
}
ctx, cancel := opts.newContext()
db = db.WithContext(ctx)
return
}
func (x *xInstance) Migrate(models ...any) (err error) {
fmt.Print("Running Database Migration... ")
db, err := x.Get()
if err != nil {
return
}
switch x.opts.getDriver() {
case DRIVER_MYSQL:
db = db.Set("gorm:table_options", fmt.Sprintf(
"ENGINE=%s CHARSET=%s COLLATE=%s",
x.opts.getEngine(),
x.opts.getCharset(),
x.opts.getCollation(),
))
}
err = db.AutoMigrate(models...)
if err != nil {
return
}
fmt.Println("Completed!")
fmt.Println()
return
}
func (x *xInstance) Seed(entries ...SeederEntry) (err error) {
fmt.Println("Running Database Seeders...")
db, err := x.Get()
if err != nil {
return
}
for _, entry := range entries {
err = x.seed(NewSession(db), entry)
if err != nil {
return
}
}
fmt.Println("Database Seeders Completed!")
fmt.Println()
return
}
func (x *xInstance) seed(db *gorm.DB, entry SeederEntry) (err error) {
name := strings.TrimSpace(entry.Name())
fmt.Printf("Seeding %v... ", name)
err = entry.Handler(db)
if err != nil {
return
}
fmt.Println("Completed!")
return
}
func (x *xInstance) dbOptions(options ...DB) DB {
if len(options) > 0 {
return options[0]
}
return DB{}
}