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

22
database/db/db.go Normal file
View File

@ -0,0 +1,22 @@
package db
import (
"context"
"gorm.io/gorm"
)
type DB interface {
Session(ctx context.Context) *gorm.DB
}
type db struct {
tx *gorm.DB
}
var (
Default DB
)
func (db *db) Session(ctx context.Context) *gorm.DB {
return db.tx.Session(&gorm.Session{Context: ctx})
}

48
database/db/new.go Normal file
View File

@ -0,0 +1,48 @@
package db
import (
"github.com/glebarez/sqlite"
"gorm.io/driver/mysql"
"gorm.io/driver/postgres"
"gorm.io/gorm"
)
var defaultSqlite = "data.db"
func New(opts ...OptionFn) (DB, error) {
var (
err error
conf = &config{
sqlite: &defaultSqlite,
}
tx *gorm.DB
)
for _, opt := range opts {
opt(conf)
}
if conf.mysql != nil {
tx, err = gorm.Open(mysql.Open(*conf.mysql))
goto CHECK
}
if conf.pg != nil {
tx, err = gorm.Open(postgres.Open(*conf.pg))
goto CHECK
}
tx, err = gorm.Open(sqlite.Open(*conf.sqlite))
CHECK:
if err != nil {
return nil, err
}
return &db{tx: tx}, nil
}
func Init(opts ...OptionFn) (err error) {
Default, err = New(opts...)
return err
}

25
database/db/new_test.go Normal file
View File

@ -0,0 +1,25 @@
package db
import (
"testing"
)
func TestNew(t *testing.T) {
//mdb, err := New(WithMysql("127.0.0.1", 3306, "root", "MyPassw0rd", "mydb"))
//if err != nil {
// t.Fatal(err)
//}
//
//type User struct {
// Id uint64 `gorm:"primaryKey"`
// Username string `gorm:"unique"`
//}
//
//if err = mdb.Session(t.Context()).AutoMigrate(&User{}); err != nil {
// t.Fatal(err)
//}
//
//if err = mdb.Session(t.Context()).Create(&User{Username: "zyp"}).Error; err != nil {
// t.Fatal(err)
//}
}

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
}
}
}