restructure
This commit is contained in:
31
providers/database/postgres/config.go
Executable file
31
providers/database/postgres/config.go
Executable file
@@ -0,0 +1,31 @@
|
||||
package postgres
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
)
|
||||
|
||||
type Config struct {
|
||||
Username string
|
||||
Password string
|
||||
Database string
|
||||
Host string
|
||||
Port uint
|
||||
SslMode string
|
||||
TimeZone string
|
||||
Prefix string // 表前缀
|
||||
Singular bool // 是否开启全局禁用复数,true表示开启
|
||||
MaxIdleConns int // 空闲中的最大连接数
|
||||
MaxOpenConns int // 打开到数据库的最大连接数
|
||||
}
|
||||
|
||||
func (m *Config) EmptyDsn() string {
|
||||
dsnTpl := "host=%s user=%s password=%s port=%d dbname=postgres sslmode=disable TimeZone=Asia/Shanghai"
|
||||
|
||||
return fmt.Sprintf(dsnTpl, m.Host, m.Username, m.Password, m.Port)
|
||||
}
|
||||
|
||||
// DSN connection dsn
|
||||
func (m *Config) DSN() string {
|
||||
dsnTpl := "host=%s user=%s password=%s dbname=%s port=%d sslmode=%s TimeZone=%s"
|
||||
return fmt.Sprintf(dsnTpl, m.Host, m.Username, m.Password, m.Database, m.Port, m.SslMode, m.TimeZone)
|
||||
}
|
||||
40
providers/database/postgres/postgres.go
Normal file
40
providers/database/postgres/postgres.go
Normal file
@@ -0,0 +1,40 @@
|
||||
package postgres
|
||||
|
||||
import (
|
||||
"log"
|
||||
|
||||
"github.com/rogeecn/atom/container"
|
||||
"go.uber.org/dig"
|
||||
|
||||
"gorm.io/driver/postgres"
|
||||
"gorm.io/gorm"
|
||||
"gorm.io/gorm/schema"
|
||||
)
|
||||
|
||||
func Provide(conf *Config, opts ...dig.ProvideOption) error {
|
||||
return container.Container.Provide(func() (*gorm.DB, error) {
|
||||
dbConfig := postgres.Config{
|
||||
DSN: conf.DSN(), // DSN data source name
|
||||
}
|
||||
log.Println("PostgreSQL DSN: ", dbConfig.DSN)
|
||||
|
||||
gormConfig := gorm.Config{
|
||||
NamingStrategy: schema.NamingStrategy{
|
||||
TablePrefix: conf.Prefix,
|
||||
SingularTable: conf.Singular,
|
||||
},
|
||||
DisableForeignKeyConstraintWhenMigrating: true,
|
||||
}
|
||||
|
||||
db, err := gorm.Open(postgres.New(dbConfig), &gormConfig)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
sqlDB, _ := db.DB()
|
||||
sqlDB.SetMaxIdleConns(conf.MaxIdleConns)
|
||||
sqlDB.SetMaxOpenConns(conf.MaxOpenConns)
|
||||
|
||||
return db, err
|
||||
}, opts...)
|
||||
}
|
||||
Reference in New Issue
Block a user