feat: 添加 db(gorm) 支持

This commit is contained in:
zhaoyupeng
2025-06-17 14:02:19 +08:00
parent 1a35c30630
commit b3fdecd62f
6 changed files with 222 additions and 7 deletions

45
database/db/option.go Normal file
View File

@ -0,0 +1,45 @@
package db
import (
"context"
"fmt"
)
type config struct {
ctx context.Context
mysql *string
pg *string
sqlite *string
}
type OptionFn func(*config)
func WithCtx(ctx context.Context) OptionFn {
return func(c *config) {
if ctx != nil {
c.ctx = ctx
}
}
}
func WithMysql(host string, port int, user string, password string, database string) OptionFn {
return func(c *config) {
dsn := fmt.Sprintf("%s:%s@tcp(%s:%d)/%s?charset=utf8mb4&parseTime=True&loc=Local", user, password, host, port, database)
c.mysql = &dsn
}
}
func WithPg(host string, port int, user string, password string, database string) OptionFn {
return func(c *config) {
dsn := fmt.Sprintf("host=%s user=%s password=%s dbname=%s port=%d sslmode=disable TimeZone=Asia/Shanghai", host, user, password, database, port)
c.pg = &dsn
}
}
func WithSqlite(path string) OptionFn {
return func(c *config) {
if path != "" {
c.sqlite = &path
}
}
}