-
Notifications
You must be signed in to change notification settings - Fork 7
/
evo.database.go
101 lines (87 loc) · 2.25 KB
/
evo.database.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
package evo
import (
"fmt"
"github.com/getevo/evo/v2/lib/settings"
"log"
"os"
"strings"
"time"
"github.com/getevo/evo/v2/lib/db/schema"
"gorm.io/driver/mysql"
"gorm.io/driver/sqlite"
"gorm.io/driver/sqlserver"
"gorm.io/gorm"
"gorm.io/gorm/logger"
)
var db *gorm.DB
func setupDatabase() {
var err error
var config = DatabaseConfig{}
settings.Register("Database", &config)
settings.Get("Database").Cast(&config)
if !config.Enabled {
return
}
var logLevel logger.LogLevel
switch config.Debug {
case 4:
logLevel = logger.Info
case 3:
logLevel = logger.Warn
case 2:
logLevel = logger.Error
default:
logLevel = logger.Silent
}
var newLog = logger.New(
log.New(os.Stdout, "\r\n", log.LstdFlags), // io writer
logger.Config{
SlowThreshold: config.SlowQueryThreshold, // Slow SQL threshold
LogLevel: logLevel, // Log level
Colorful: true, // Disable color
},
)
cfg := &gorm.Config{
Logger: newLog,
}
switch strings.ToLower(config.Type) {
case "mysql":
connectionString := fmt.Sprintf("%s:%s@tcp(%s)/%s?%s", config.Username, config.Password, config.Server, config.Database, config.Params)
db, err = gorm.Open(mysql.Open(connectionString), cfg)
case "mssql":
connectionString := fmt.Sprintf("user id=%s;password=%s;server=%s;database:%s;"+config.Params, config.Username, config.Password, config.Server, config.Database)
db, err = gorm.Open(sqlserver.Open(connectionString), cfg)
default:
db, err = gorm.Open(sqlite.Open(config.Database+config.Params), cfg)
}
if err != nil {
log.Fatal("unable to connect to database", "error", err)
return
}
//switch settings to database
/* var driver = database.Database{}
driver.Init()
settings.SetInterface(&driver)*/
}
// GetDBO return database object instance
func GetDBO() *gorm.DB {
if db == nil {
setupDatabase()
}
return db
}
type Model struct {
ID uint `json:"id" gorm:"primary_key"`
CreatedAt time.Time `json:"created_at"`
UpdatedAt time.Time `json:"updated_at"`
DeletedAt *time.Time `json:"deleted_at" sql:"index"`
}
func DoMigration() error {
return schema.DoMigration(db)
}
func Models() []schema.Model {
return schema.Models
}
func GetModel(name string) *schema.Model {
return schema.Find(name)
}