119 lines
2.2 KiB
Go
119 lines
2.2 KiB
Go
package mdbc
|
|
|
|
import (
|
|
"errors"
|
|
"fmt"
|
|
"os"
|
|
"reflect"
|
|
"runtime"
|
|
"strings"
|
|
|
|
"google.golang.org/protobuf/proto"
|
|
|
|
nested "github.com/antonfisher/nested-logrus-formatter"
|
|
"github.com/sirupsen/logrus"
|
|
"go.mongodb.org/mongo-driver/mongo"
|
|
)
|
|
|
|
func init() {
|
|
var getServeDir = func(path string) string {
|
|
var run, _ = os.Getwd()
|
|
return strings.Replace(path, run, ".", -1)
|
|
}
|
|
var formatter = &nested.Formatter{
|
|
NoColors: false,
|
|
HideKeys: true,
|
|
TimestampFormat: "2006-01-02 15:04:05",
|
|
CallerFirst: true,
|
|
CustomCallerFormatter: func(f *runtime.Frame) string {
|
|
s := strings.Split(f.Function, ".")
|
|
funcName := s[len(s)-1]
|
|
return fmt.Sprintf(" [%s:%d][%s()]", getServeDir(f.File), f.Line, funcName)
|
|
},
|
|
}
|
|
logrus.SetFormatter(formatter)
|
|
logrus.SetReportCaller(true)
|
|
|
|
// 注册错误码
|
|
register()
|
|
}
|
|
|
|
var (
|
|
// db 直连数据库连接句柄
|
|
db *Database
|
|
// rawClient mongo的client客户端 是db的上级
|
|
rawClient *mongo.Client
|
|
)
|
|
|
|
func GetDatabase() *Database {
|
|
return db
|
|
}
|
|
|
|
func GetMongodbClient() *mongo.Client {
|
|
return rawClient
|
|
}
|
|
|
|
type Model struct {
|
|
Type proto.Message // 模型原形
|
|
modelKind reflect.Type // 模型类型
|
|
modelName string // 模型名称
|
|
tableName string // 绑定表名
|
|
}
|
|
|
|
// NewModel 实例化model
|
|
func NewModel(msg interface{}) *Scope {
|
|
if db == nil {
|
|
panic("database nil")
|
|
}
|
|
|
|
if msg == nil {
|
|
panic("proto message nil")
|
|
}
|
|
|
|
remsg, ok := msg.(proto.Message)
|
|
if !ok {
|
|
panic("msg no match proto message")
|
|
}
|
|
m := &Model{Type: remsg}
|
|
|
|
typ := reflect.TypeOf(m.Type)
|
|
for typ.Kind() == reflect.Ptr {
|
|
typ = typ.Elem()
|
|
}
|
|
m.modelKind = typ
|
|
|
|
m.modelName = string(m.Type.ProtoReflect().Descriptor().FullName())
|
|
m.tableName = GetTableName(m.Type)
|
|
|
|
s := &Scope{
|
|
Model: m,
|
|
}
|
|
return s
|
|
}
|
|
|
|
// InitC 初始化client
|
|
type InitC struct{}
|
|
|
|
// Init 初始化client
|
|
func Init(c *ClientInit) *InitC {
|
|
rawClient = c.Client
|
|
return &InitC{}
|
|
}
|
|
|
|
// InitDB 初始化db
|
|
func (i *InitC) InitDB(c *Database) *InitC {
|
|
db = c
|
|
return &InitC{}
|
|
}
|
|
|
|
// InitDB 兼容以前的初始化方式
|
|
func InitDB(c *Database) {
|
|
db = c
|
|
rawClient = c.Client()
|
|
}
|
|
|
|
// IsRecordNotFound 检测记录是否存在
|
|
func IsRecordNotFound(err error) bool {
|
|
return errors.Is(err, &ErrRecordNotFound)
|
|
}
|