sdbc/sdbc.go

94 lines
2.0 KiB
Go
Raw Normal View History

2023-09-10 16:07:03 +00:00
package sdbc
import (
"github.com/glebarez/sqlite"
"github.com/sirupsen/logrus"
"gitter.top/common/lormatter"
"google.golang.org/protobuf/proto"
"gorm.io/gorm"
"reflect"
"time"
)
func init() {
var formatter = &lormatter.Formatter{
ShowTime: true,
}
formatter.Register()
}
type tabler interface {
TableName() string
}
type Config struct {
Dbname string // 数据库名
MaxIdleConn int // 最大空闲连接
MaxOpenConn int // 最大连接
MaxLifetime time.Duration // 最大生存时长
}
type sdbc struct {
dbname string
client *gorm.DB
}
func NewSDBC(cfg *Config) *sdbc {
if cfg == nil {
logrus.Fatalf("config can not be nil")
}
var (
driver = new(sdbc)
err error
)
driver.client, err = gorm.Open(sqlite.Open(cfg.Dbname), &gorm.Config{})
if err != nil {
logrus.Fatalf("open sqlite file failed: %v", err)
}
rawDB, err := driver.client.DB()
if err != nil {
logrus.Fatalf("get sqlite instance failed: %v", err)
}
if cfg.MaxOpenConn != 0 {
rawDB.SetMaxOpenConns(cfg.MaxOpenConn)
}
if cfg.MaxIdleConn != 0 {
rawDB.SetMaxIdleConns(cfg.MaxIdleConn)
}
if cfg.MaxLifetime != 0 {
rawDB.SetConnMaxLifetime(cfg.MaxLifetime)
}
driver.dbname = cfg.Dbname
return driver
}
func (s *sdbc) GetClient() *gorm.DB {
return s.client
}
func (s *sdbc) BindModel(prototype any) Operator {
if prototype == nil {
2023-09-10 16:13:23 +00:00
logrus.Panic("model can not be nil")
2023-09-10 16:07:03 +00:00
}
if _, impled := prototype.(tabler); !impled {
2023-09-10 16:13:23 +00:00
logrus.Panic("model does not implement tabler interface")
2023-09-10 16:07:03 +00:00
}
protomsg, impled := prototype.(proto.Message)
if !impled {
2023-09-10 16:13:23 +00:00
logrus.Panic("model does not implement message interface")
2023-09-10 16:07:03 +00:00
}
scope := &scope{
&model{
Type: protomsg,
modelKind: reflect.TypeOf(protomsg),
modelName: string(protomsg.ProtoReflect().Descriptor().FullName()),
tableName: prototype.(tabler).TableName(),
},
s,
}
2023-09-10 16:13:23 +00:00
if err := s.client.AutoMigrate(prototype); err != nil {
logrus.Panicf("auto create table failed: %v", err)
}
2023-09-10 16:07:03 +00:00
return scope
}