58 lines
1.1 KiB
Go
Raw Normal View History

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