Ai
2 Star 0 Fork 0

carlmax_my/console-core-go

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
文件
克隆/下载
mongo.go 4.72 KB
一键复制 编辑 原始数据 按行查看 历史
carlmax_my 提交于 2025-08-18 15:45 +08:00 . optimize logger
// ///////////////////////////////////////
// not used yet
// ///////////////////////////////////////
package qmgo
import (
"context"
"fmt"
"sort"
"strings"
"gitee.com/carlmax_my/console-core-go/pkg/crypto/md5"
"gitee.com/carlmax_my/console-core-go/pkg/mongo"
"gitee.com/carlmax_my/console-core-go/pkg/mongo/internal"
"gitee.com/carlmax_my/console-core-go/pkg/types"
"github.com/pkg/errors"
"github.com/qiniu/qmgo"
"github.com/qiniu/qmgo/options"
"go.mongodb.org/mongo-driver/bson"
option "go.mongodb.org/mongo-driver/mongo/options"
)
type (
MongoRepo struct {
db *qmgo.QmgoClient
}
Index struct {
V any `bson:"v"`
Ns any `bson:"ns"`
Key []bson.E `bson:"key"`
Name string `bson:"name"`
}
)
func New(config *mongo.MongoConfig, logger types.ILogger) (repo *MongoRepo, err error) {
repo = new(MongoRepo)
err = repo.Initialization(config, logger)
return
}
func (m *MongoRepo) Indexes(ctx context.Context) error {
// 表名:索引列表 列: "表名": [][]string{{"index1", "index2"}}
indexMap := map[string][][]string{}
for collection, indexes := range indexMap {
err := m.CreateIndexes(ctx, collection, indexes)
if err != nil {
return err
}
}
return nil
}
func (m *MongoRepo) Initialization(mongoConfig *mongo.MongoConfig, logger types.ILogger) error {
var opts []options.ClientOptions
if mongoConfig.IsZap {
opts = internal.New(logger).GetClientOptions()
}
ctx := context.Background()
client, err := qmgo.Open(ctx, &qmgo.Config{
Uri: mongoConfig.Uri(),
Coll: mongoConfig.Coll,
Database: mongoConfig.Database,
MinPoolSize: &mongoConfig.MinPoolSize,
MaxPoolSize: &mongoConfig.MaxPoolSize,
SocketTimeoutMS: &mongoConfig.SocketTimeoutMs,
ConnectTimeoutMS: &mongoConfig.ConnectTimeoutMs,
Auth: &qmgo.Credential{
Username: mongoConfig.Username,
Password: mongoConfig.Password,
AuthSource: mongoConfig.AuthSource,
},
}, opts...)
if err != nil {
return errors.Wrap(err, "链接mongodb数据库失败!")
}
m.db = client
err = m.Indexes(ctx)
if err != nil {
return err
}
return nil
}
func (m *MongoRepo) CreateIndexes(ctx context.Context, name string, indexes [][]string) error {
collection, err := m.db.Database.Collection(name).CloneCollection()
if err != nil {
return errors.Wrapf(err, "获取[%s]的表对象失败!", name)
}
list, err := collection.Indexes().List(ctx)
if err != nil {
return errors.Wrapf(err, "获取[%s]的索引对象失败!", name)
}
var entities []Index
err = list.All(ctx, &entities)
if err != nil {
return errors.Wrapf(err, "获取[%s]的索引列表失败!", name)
}
length := len(indexes)
indexMap1 := make(map[string][]string, length)
for i := 0; i < length; i++ {
sort.Strings(indexes[i]) // 对索引key进行排序, 在使用bson.M搜索时, bson会自动按照key的字母顺序进行排序
length1 := len(indexes[i])
keys := make([]string, 0, length1)
for j := 0; j < length1; j++ {
if indexes[i][i][0] == '-' {
keys = append(keys, indexes[i][j], "-1")
continue
}
keys = append(keys, indexes[i][j], "1")
}
key := strings.Join(keys, "_")
_, o1 := indexMap1[key]
if o1 {
return errors.Errorf("索引[%s]重复!", key)
}
indexMap1[key] = indexes[i]
}
length = len(entities)
indexMap2 := make(map[string]map[string]string, length)
for i := 0; i < length; i++ {
_, o1 := indexMap2[entities[i].Name]
if !o1 {
keyLength := len(entities[i].Key)
v1 := make(map[string]string, keyLength)
for j := 0; j < keyLength; j++ {
_, o2 := v1[entities[i].Key[j].Key]
if !o2 {
v1 = make(map[string]string)
}
v2 := entities[i].Key[j].Key
v1[entities[i].Key[j].Key] = v2
indexMap2[entities[i].Name] = v1
}
}
}
for k1, v1 := range indexMap1 {
_, o2 := indexMap2[k1]
if o2 {
continue
} // 索引存在
if len(fmt.Sprintf("%s.%s.$%s", collection.Name(), name, v1)) > 127 {
err = m.db.Database.Collection(name).CreateOneIndex(ctx, options.IndexModel{
Key: v1,
IndexOptions: option.Index().SetName(md5.MD5V([]byte(k1))),
// IndexOptions: option.Index().SetName(util.MD5V([]byte(k1))).SetExpireAfterSeconds(86400), // SetExpireAfterSeconds(86400) 设置索引过期时间, 86400 = 1天
})
if err != nil {
return errors.Wrapf(err, "创建索引[%s]失败!", k1)
}
return nil
}
err = m.db.Database.Collection(name).CreateOneIndex(ctx, options.IndexModel{
Key: v1,
IndexOptions: option.Index().SetExpireAfterSeconds(86400),
// IndexOptions: option.Index().SetName(util.MD5V([]byte(k1))).SetExpireAfterSeconds(86400), // SetExpireAfterSeconds(86400) 设置索引过期时间(秒), 86400 = 1天
})
if err != nil {
return errors.Wrapf(err, "创建索引[%s]失败!", k1)
}
}
return nil
}
Loading...
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
Go
1
https://gitee.com/carlmax_my/console-core-go.git
git@gitee.com:carlmax_my/console-core-go.git
carlmax_my
console-core-go
console-core-go
v0.1.109

搜索帮助