This repository was archived by the owner on Sep 21, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 149
/
Copy pathmodels.go
86 lines (76 loc) · 1.98 KB
/
models.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
package models
import (
"errors"
"reflect"
"strings"
"github.com/gernest/utron/config"
"github.com/jinzhu/gorm"
// support mysql, sqlite3 and postgresql
_ "github.com/go-sql-driver/mysql"
_ "github.com/jinzhu/gorm/dialects/sqlite"
_ "github.com/lib/pq"
)
// Model facilitate database interactions, supports postgres, mysql and foundation
type Model struct {
models map[string]reflect.Value
isOpen bool
*gorm.DB
}
// NewModel returns a new Model without opening database connection
func NewModel() *Model {
return &Model{
models: make(map[string]reflect.Value),
}
}
// IsOpen returns true if the Model has already established connection
// to the database
func (m *Model) IsOpen() bool {
return m.isOpen
}
// OpenWithConfig opens database connection with the settings found in cfg
func (m *Model) OpenWithConfig(cfg *config.Config) error {
db, err := gorm.Open(cfg.Database, cfg.DatabaseConn)
if err != nil {
return err
}
m.DB = db
m.isOpen = true
return nil
}
// Register adds the values to the models registry
func (m *Model) Register(values ...interface{}) error {
// do not work on them.models first, this is like an insurance policy
// whenever we encounter any error in the values nothing goes into the registry
models := make(map[string]reflect.Value)
if len(values) > 0 {
for _, val := range values {
rVal := reflect.ValueOf(val)
if rVal.Kind() == reflect.Ptr {
rVal = rVal.Elem()
}
switch rVal.Kind() {
case reflect.Struct:
models[getTypName(rVal.Type())] = reflect.New(rVal.Type())
default:
return errors.New("utron: models must be structs")
}
}
}
for k, v := range models {
m.models[k] = v
}
return nil
}
// AutoMigrateAll runs migrations for all the registered models
func (m *Model) AutoMigrateAll() {
for _, v := range m.models {
m.AutoMigrate(v.Interface())
}
}
func getTypName(typ reflect.Type) string {
if typ.Name() != "" {
return typ.Name()
}
split := strings.Split(typ.String(), ".")
return split[len(split)-1]
}