fix: update user nickname;

feat: add database/kafka.
This commit is contained in:
loveuer
2024-12-04 15:49:37 +08:00
parent 3ec150b015
commit e5ae2efcef
15 changed files with 585 additions and 64 deletions

View File

@ -3,25 +3,32 @@ package db
import (
"context"
"io"
"ultone/internal/opt"
"ultone/internal/tool"
"gorm.io/gorm"
)
var (
Default *Client
var Default *Client
type DBType string
const (
DBTypeSqlite = "sqlite"
DBTypeMysql = "mysql"
DBTypePostgres = "postgres"
)
type Client struct {
ctx context.Context
cli *gorm.DB
ttype string
dbType DBType
cfgSqlite *cfgSqlite
}
func (c *Client) Type() string {
return c.ttype
func (c *Client) Type() DBType {
return c.dbType
}
func (c *Client) Session(ctxs ...context.Context) *gorm.DB {
@ -49,7 +56,7 @@ func (c *Client) 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" {
if c.dbType != DBTypeSqlite {
return nil, false
}

View File

@ -8,7 +8,7 @@ import (
)
func TestOpen(t *testing.T) {
myClient, err := New(context.TODO(), "sqlite::", OptSqliteByMem())
myClient, err := New(context.TODO(), "sqlite::", OptSqliteByMem(nil))
if err != nil {
t.Fatalf("TestOpen: New err = %v", err)
}
@ -37,7 +37,7 @@ func TestOpen(t *testing.T) {
t.Fatalf("TestOpen: ReadAll err = %v", err)
}
os.WriteFile("dump.db", bs, 0644)
os.WriteFile("dump.db", bs, 0o644)
}
myClient.Close()

View File

@ -11,35 +11,38 @@ import (
)
func New(ctx context.Context, uri string, opts ...Option) (*Client, error) {
strs := strings.Split(uri, "::")
parts := strings.SplitN(uri, "::", 2)
if len(strs) != 2 {
if len(parts) != 2 {
return nil, fmt.Errorf("db.Init: opt db uri invalid: %s", uri)
}
c := &Client{ttype: strs[0], cfgSqlite: &cfgSqlite{fsType: "file"}}
c := &Client{cfgSqlite: &cfgSqlite{fsType: "file"}}
for _, f := range opts {
f(c)
}
var (
err error
dsn = strs[1]
dsn = parts[1]
)
switch strs[0] {
switch parts[0] {
case "sqlite":
c.dbType = DBTypeSqlite
err = openSqlite(c, dsn)
case "mysql":
c.dbType = DBTypeMysql
c.cli, err = gorm.Open(mysql.Open(dsn))
case "postgres":
c.dbType = DBTypePostgres
c.cli, err = gorm.Open(postgres.Open(dsn))
default:
return nil, fmt.Errorf("db type only support: [sqlite, mysql, postgres], unsupported db type: %s", strs[0])
return nil, fmt.Errorf("db type only support: [sqlite, mysql, postgres], unsupported db type: %s", parts[0])
}
if err != nil {
return nil, fmt.Errorf("db.Init: open %s with dsn:%s, err: %w", strs[0], dsn, err)
return nil, fmt.Errorf("db.Init: open %s with dsn:%s, err: %w", parts[0], dsn, err)
}
return c, nil