62 lines
944 B
Go
Raw Normal View History

2024-07-11 16:37:26 +08:00
package db
import (
"context"
"io"
2024-07-11 16:37:26 +08:00
"ultone/internal/opt"
"ultone/internal/tool"
"gorm.io/gorm"
2024-07-11 16:37:26 +08:00
)
var (
Default *Client
2024-07-11 16:37:26 +08:00
)
type Client struct {
ctx context.Context
cli *gorm.DB
ttype string
cfgSqlite *cfgSqlite
2024-07-11 16:37:26 +08:00
}
func (c *Client) Type() string {
return c.ttype
2024-07-11 16:37:26 +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)
}
session := c.cli.Session(&gorm.Session{Context: ctx})
2024-07-11 16:37:26 +08:00
if opt.Debug {
session = session.Debug()
}
return session
}
func (c *Client) Close() {
d, _ := c.cli.DB()
d.Close()
}
// Dump
// Only for sqlite with mem mode to dump data to bytes(io.Reader)
func (c *Client) Dump() (reader io.ReadSeekCloser, ok bool) {
if c.ttype != "sqlite" {
return nil, false
}
if c.cfgSqlite.fsType != "mem" {
return nil, false
}
return c.cfgSqlite.memDump.Dump(), true
}