91 lines
1.8 KiB
Go
91 lines
1.8 KiB
Go
|
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 {
|
||
|
panic("model can not be nil")
|
||
|
}
|
||
|
if _, impled := prototype.(tabler); !impled {
|
||
|
panic("model does not implement tabler interface")
|
||
|
}
|
||
|
protomsg, impled := prototype.(proto.Message)
|
||
|
if !impled {
|
||
|
panic("model does not implement message interface")
|
||
|
}
|
||
|
scope := &scope{
|
||
|
&model{
|
||
|
Type: protomsg,
|
||
|
modelKind: reflect.TypeOf(protomsg),
|
||
|
modelName: string(protomsg.ProtoReflect().Descriptor().FullName()),
|
||
|
tableName: prototype.(tabler).TableName(),
|
||
|
},
|
||
|
s,
|
||
|
}
|
||
|
return scope
|
||
|
}
|