🎉: init project

This commit is contained in:
loveuer
2024-07-11 16:37:26 +08:00
commit c46458c6f2
159 changed files with 19246 additions and 0 deletions

View File

@ -0,0 +1,38 @@
package db
import (
"context"
"gorm.io/gorm"
"ultone/internal/opt"
"ultone/internal/tool"
)
var (
cli = &client{}
)
type client struct {
cli *gorm.DB
ttype string
}
func Type() string {
return cli.ttype
}
func New(ctxs ...context.Context) *gorm.DB {
var ctx context.Context
if len(ctxs) > 0 && ctxs[0] != nil {
ctx = ctxs[0]
} else {
ctx = tool.Timeout(30)
}
session := cli.cli.Session(&gorm.Session{Context: ctx})
if opt.Debug {
session = session.Debug()
}
return session
}

View File

@ -0,0 +1,46 @@
package db
import (
"fmt"
"github.com/glebarez/sqlite"
"gorm.io/driver/mysql"
"gorm.io/driver/postgres"
"gorm.io/gorm"
"strings"
"ultone/internal/opt"
)
func Init() error {
strs := strings.Split(opt.Cfg.DB.Uri, "::")
if len(strs) != 2 {
return fmt.Errorf("db.Init: opt db uri invalid: %s", opt.Cfg.DB.Uri)
}
cli.ttype = strs[0]
var (
err error
dsn = strs[1]
)
switch strs[0] {
case "sqlite":
opt.Cfg.DB.Type = "sqlite"
cli.cli, err = gorm.Open(sqlite.Open(dsn))
case "mysql":
opt.Cfg.DB.Type = "mysql"
cli.cli, err = gorm.Open(mysql.Open(dsn))
case "postgres":
opt.Cfg.DB.Type = "postgres"
cli.cli, err = gorm.Open(postgres.Open(dsn))
default:
return fmt.Errorf("db type only support: [sqlite, mysql, postgres], unsupported db type: %s", strs[0])
}
if err != nil {
return fmt.Errorf("db.Init: open %s with dsn:%s, err: %w", strs[0], dsn, err)
}
return nil
}