Files
gormx/options.go
2025-07-12 17:12:24 +08:00

102 lines
2.1 KiB
Go

package gormx
import (
"context"
"time"
"github.com/yuninks/loggerx"
)
type clientOptions struct {
Db string
Mysql *MysqlOptions
Sqlite *SqliteOptions
Prefix string // 表名前缀,`Article` 的表名应该是 `it_articles`
SingularTable bool // 使用单数表名,启用该选项,此时,`Article` 的表名应该是 `it_article`
Charset string // 使用utf8mb4编码
Location *time.Location // 时区设置 "Local" "Asia/Shanghai"
Logger loggerx.LoggerInterface // 日志记录器
}
type MysqlOptions struct {
User string
Password string
Host string
Port int
Database string
}
type SqliteOptions struct {
DbPath string
}
func defaultOptions() clientOptions {
return clientOptions{
SingularTable: true,
Location: time.Local, // 默认本地
Charset: "utf8mb4",
Logger: loggerx.NewLogger(context.Background()),
}
}
type Option func(*clientOptions)
func SetMysql(user, password, host, database string, port int) Option {
return func(o *clientOptions) {
o.Db = "mysql"
o.Mysql = &MysqlOptions{
User: user,
Host: host,
Port: port,
Database: database,
Password: password,
}
if o.Mysql.Port == 0 {
o.Mysql.Port = 3306
}
}
}
// 使用sqlite数据库
func SetSqlite(dbPath string) Option {
return func(o *clientOptions) {
o.Db = "sqlite"
o.Sqlite = &SqliteOptions{
DbPath: dbPath,
}
if o.Sqlite.DbPath == "" {
o.Sqlite.DbPath = "sqlite.db"
}
}
}
// 使用postgres数据库
func SetPostgres() Option {
return func(o *clientOptions) {
o.Db = "postgres"
panic("postgres is not supported yet")
}
}
// 表名前缀
func SetTablePrefix(perfix string) Option {
return func(o *clientOptions) {
o.Prefix = perfix
}
}
// 设置时区,默认是本地
func SetLocation(loc *time.Location) Option {
return func(o *clientOptions) {
o.Location = loc
}
}
// 设置日志记录器
func SetLogger(logger loggerx.LoggerInterface) Option {
return func(o *clientOptions) {
o.Logger = logger
}
}