-
Notifications
You must be signed in to change notification settings - Fork 0
/
db.go
108 lines (83 loc) · 2.58 KB
/
db.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
package manago
import (
"errors"
"fmt"
"reflect"
"github.com/jinzhu/gorm"
_ "github.com/jinzhu/gorm/dialects/mssql"
_ "github.com/jinzhu/gorm/dialects/postgres"
)
type Db struct {
DB *gorm.DB
config DatabaseConfig
}
func (dbc *Db) Check(config DatabaseConfig) (err error) {
dbc.config = config
_, err = dbc.Open()
return
}
func (dbc *Db) Open() (db *gorm.DB, err error) {
switch dbc.config.Server {
case "postgres":
if dbc.config.DisableSsl {
db, err = gorm.Open("postgres", fmt.Sprintf("postgres://%s:%s@%s:%d/%s?sslmode=disable", dbc.config.User, dbc.config.Pass, dbc.config.Host, dbc.config.Port, dbc.config.Name))
} else {
db, err = gorm.Open("postgres", fmt.Sprintf("host=%s port=%d user=%s dbname=%s password=%s", dbc.config.Host, dbc.config.Port, dbc.config.User, dbc.config.Name, dbc.config.Pass))
}
case "mssql":
// db, err = gorm.Open("mssql", fmt.Sprintf("sqlserver://%s:%s@%s:%d?database=%s", dbc.config.User, dbc.config.Pass, dbc.config.Host, dbc.config.Port, dbc.config.Name))
db, err = gorm.Open("mssql", fmt.Sprintf("server=%s;user id=%s;password=%s;port=%d;database=%s",
dbc.config.Host, dbc.config.User, dbc.config.Pass, dbc.config.Port, dbc.config.Name))
default:
db, err = nil, fmt.Errorf("database type not found: %v, cant connect", dbc.config)
}
dbc.DB = db
return
}
func (dbc *Db) Close() {
}
func (dbc *Db) AutoMigrate(modelsReflected map[string]reflect.Type) (err error) {
db, err := dbc.Open()
if err != nil {
return fmt.Errorf("models AutoMigrate failed: %w", err)
}
for _, v := range modelsReflected {
model := reflect.New(v).Interface()
fmt.Printf("Migrating model: %v\n", v)
db.AutoMigrate(model)
}
return
}
func (dbc *Db) CopyDb(modelsReflected map[string]reflect.Type, targetDb *Db) error {
source, err := dbc.Open()
if err != nil {
return errors.Join(errors.New("failed to open source db"), err)
}
defer source.Close()
target, err := targetDb.Open()
if err != nil {
return errors.Join(errors.New("failed to open target db"), err)
}
defer target.Close()
for _, v := range modelsReflected {
model := reflect.New(v).Interface()
rows, err := source.Model(model).Rows()
if err != nil {
return errors.Join(errors.New("failed to get rows"), err)
}
for rows.Next() {
err = source.ScanRows(rows, model)
if err != nil {
rows.Close()
return errors.Join(errors.New("failed to scan row"), err)
}
result := target.Create(model)
if result.Error != nil {
rows.Close()
return errors.Join(errors.New("failed to create new row in target db"), result.Error)
}
}
rows.Close()
}
return nil
}