2024-07-11 16:37:26 +08:00
|
|
|
package db
|
|
|
|
|
|
|
|
import (
|
|
|
|
"context"
|
2024-12-04 15:49:37 +08:00
|
|
|
|
2024-07-11 16:37:26 +08:00
|
|
|
"ultone/internal/opt"
|
|
|
|
"ultone/internal/tool"
|
2024-09-20 15:14:49 +08:00
|
|
|
|
|
|
|
"gorm.io/gorm"
|
2024-07-11 16:37:26 +08:00
|
|
|
)
|
|
|
|
|
2024-12-04 15:49:37 +08:00
|
|
|
var Default *Client
|
|
|
|
|
|
|
|
type DBType string
|
|
|
|
|
|
|
|
const (
|
|
|
|
DBTypeSqlite = "sqlite"
|
|
|
|
DBTypeMysql = "mysql"
|
|
|
|
DBTypePostgres = "postgres"
|
2024-07-11 16:37:26 +08:00
|
|
|
)
|
|
|
|
|
2024-09-20 15:14:49 +08:00
|
|
|
type Client struct {
|
2024-12-27 11:13:28 +08:00
|
|
|
ctx context.Context
|
|
|
|
cli *gorm.DB
|
|
|
|
dbType DBType
|
2024-07-11 16:37:26 +08:00
|
|
|
}
|
|
|
|
|
2024-12-04 15:49:37 +08:00
|
|
|
func (c *Client) Type() DBType {
|
|
|
|
return c.dbType
|
2024-07-11 16:37:26 +08:00
|
|
|
}
|
|
|
|
|
2024-09-20 15:14:49 +08:00
|
|
|
func (c *Client) Session(ctxs ...context.Context) *gorm.DB {
|
2024-07-11 16:37:26 +08:00
|
|
|
var ctx context.Context
|
|
|
|
if len(ctxs) > 0 && ctxs[0] != nil {
|
|
|
|
ctx = ctxs[0]
|
|
|
|
} else {
|
|
|
|
ctx = tool.Timeout(30)
|
|
|
|
}
|
|
|
|
|
2024-09-20 15:14:49 +08:00
|
|
|
session := c.cli.Session(&gorm.Session{Context: ctx})
|
2024-07-11 16:37:26 +08:00
|
|
|
|
|
|
|
if opt.Debug {
|
|
|
|
session = session.Debug()
|
|
|
|
}
|
|
|
|
|
|
|
|
return session
|
|
|
|
}
|
2024-09-20 15:14:49 +08:00
|
|
|
|
|
|
|
func (c *Client) Close() {
|
|
|
|
d, _ := c.cli.DB()
|
|
|
|
d.Close()
|
|
|
|
}
|