-
Notifications
You must be signed in to change notification settings - Fork 0
/
db.go
57 lines (45 loc) · 1.23 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
package postgres
import (
"fmt"
pkdb "github.com/hopeio/cherry/initialize/conf_dao/gormdb"
"github.com/hopeio/cherry/initialize/initconf"
"gorm.io/driver/postgres"
"gorm.io/gorm"
"gorm.io/gorm/clause"
)
type Config pkdb.Config
func (c *Config) InitBeforeInjectWithInitConfig(conf *initconf.InitConfig) {
(*pkdb.Config)(c).InitBeforeInjectWithInitConfig(conf)
}
func (c *Config) Build() *gorm.DB {
(*pkdb.Config)(c).Init()
url := fmt.Sprintf("host=%s user=%s dbname=%s port=%d sslmode=%s password=%s TimeZone=%s",
c.Host, c.User, c.Database, c.Port, c.Postgres.SSLMode, c.Password, c.TimeZone)
return (*pkdb.Config)(c).Build(postgres.Open(url))
}
type DB pkdb.DB
func (db *DB) Config() any {
return (*Config)(&db.Conf)
}
func (db *DB) SetEntity() {
db.DB = (*Config)(&db.Conf).Build()
}
func (db *DB) Close() error {
return nil
}
func (db *DB) Table(name string) *gorm.DB {
name = db.TableName(name)
gdb := db.DB.Clauses()
gdb.Statement.TableExpr = &clause.Expr{SQL: gdb.Statement.Quote(name)}
gdb.Statement.Table = name
return gdb
}
func (db *DB) TableName(name string) string {
if db.Conf.Postgres.Schema != "" {
return db.Conf.Postgres.Schema + "." + name
}
return name
}
// TODO:
func (db *DB) Inject(configName string) {
}