- update dorm

master
李光春 1 year ago
parent 9ff541c4af
commit 0dce07f1ee

@ -4,7 +4,7 @@ import (
"github.com/uptrace/bun"
)
type ConfigBunClient struct {
type BunClientConfig struct {
Dns string // 地址
}
@ -12,5 +12,5 @@ type ConfigBunClient struct {
// https://bun.uptrace.dev/
type BunClient struct {
Db *bun.DB // 驱动
config *ConfigBunClient // 配置
config *BunClientConfig // 配置
}

@ -9,7 +9,7 @@ import (
"github.com/uptrace/bun/dialect/mysqldialect"
)
func NewBunMysqlClient(config *ConfigBunClient) (*BunClient, error) {
func NewBunMysqlClient(config *BunClientConfig) (*BunClient, error) {
var err error
c := &BunClient{config: config}

@ -7,7 +7,7 @@ import (
"github.com/uptrace/bun/driver/pgdriver"
)
func NewBunPgsqlClient(config *ConfigBunClient) (*BunClient, error) {
func NewBunPgsqlClient(config *BunClientConfig) (*BunClient, error) {
c := &BunClient{config: config}

@ -0,0 +1 @@
package dorm

@ -9,28 +9,29 @@ import (
"time"
)
type ConfigGormClient struct {
Dns string // 地址
Log struct {
Status bool // 状态
Path string // 路径
Slow int64 // 慢SQL阈值
Level string // 级别
NotFoundError bool // 忽略ErrRecordNotFound记录未找到错误
Colorful bool // 禁用彩色打印
} // 日志
Conn struct {
SetMaxIdle int // 设置空闲连接池中连接的最大数量
SetMaxOpen int // 设置打开数据库连接的最大数量
SetConnMaxLifetime int64 // 设置了连接可复用的最大时间
} // 连接
// GormClientFun *GormClient 驱动
type GormClientFun func() *GormClient
// GormClientTableFun *GormClient 驱动
// string 表名
type GormClientTableFun func() (*GormClient, string)
type GormClientConfig struct {
Dns string // 地址
LogStatus bool // 日志 - 状态
LogPath string // 日志 - 路径
LogSlow int64 // 日志 - 慢SQL阈值
LogLevel string // 日志 - 级别
ConnSetMaxIdle int // 连接 - 设置空闲连接池中连接的最大数量
ConnSetMaxOpen int // 连接 - 设置打开数据库连接的最大数量
ConnSetConnMaxLifetime int64 // 连接 - 设置了连接可复用的最大时间
}
// GormClient
// https://gorm.io/
type GormClient struct {
Db *gorm.DB // 驱动
config *ConfigGormClient // 配置
config *GormClientConfig // 配置
}
type writer struct{}

@ -0,0 +1,8 @@
package dorm
import "gorm.io/gorm"
var (
// GormNotFound 没有数据
GormNotFound = gorm.ErrRecordNotFound
)

@ -10,29 +10,29 @@ import (
"time"
)
func NewGormMysqlClient(config *ConfigGormClient) (*GormClient, error) {
func NewGormMysqlClient(config *GormClientConfig) (*GormClient, error) {
var err error
c := &GormClient{config: config}
// 判断路径
if c.config.Log.Path == "" {
if c.config.LogPath == "" {
logsUrl = "/logs/mysql"
} else {
logsUrl = c.config.Log.Path
logsUrl = c.config.LogPath
}
if c.config.Log.Status == true {
if c.config.LogStatus {
var slowThreshold time.Duration
var logLevel logger.LogLevel
if c.config.Log.Slow == 0 {
if c.config.LogSlow == 0 {
slowThreshold = 100 * time.Millisecond
} else {
slowThreshold = time.Duration(c.config.Log.Slow)
slowThreshold = time.Duration(c.config.LogSlow)
}
if c.config.Log.Level == "Error" {
if c.config.LogLevel == "Error" {
logLevel = logger.Error
} else if c.config.Log.Level == "Warn" {
} else if c.config.LogLevel == "Warn" {
logLevel = logger.Warn
} else {
logLevel = logger.Info
@ -41,10 +41,10 @@ func NewGormMysqlClient(config *ConfigGormClient) (*GormClient, error) {
Logger: logger.New(
writer{},
logger.Config{
SlowThreshold: slowThreshold, // 慢SQL阈值
LogLevel: logLevel, // 日志级别
IgnoreRecordNotFoundError: c.config.Log.NotFoundError, // 忽略ErrRecordNotFound记录未找到错误
Colorful: c.config.Log.Colorful, // 禁用彩色打印
SlowThreshold: slowThreshold, // 慢SQL阈值
LogLevel: logLevel, // 日志级别
IgnoreRecordNotFoundError: true, // 忽略ErrRecordNotFound记录未找到错误
Colorful: true, // 禁用彩色打印
},
),
NowFunc: func() time.Time {
@ -65,24 +65,24 @@ func NewGormMysqlClient(config *ConfigGormClient) (*GormClient, error) {
}
// 设置空闲连接池中连接的最大数量
if c.config.Conn.SetMaxIdle == 0 {
if c.config.ConnSetMaxIdle == 0 {
sqlDB.SetMaxIdleConns(10)
} else {
sqlDB.SetMaxIdleConns(c.config.Conn.SetMaxIdle)
sqlDB.SetMaxIdleConns(c.config.ConnSetMaxIdle)
}
// 设置打开数据库连接的最大数量
if c.config.Conn.SetMaxOpen == 0 {
if c.config.ConnSetMaxOpen == 0 {
sqlDB.SetMaxOpenConns(100)
} else {
sqlDB.SetMaxOpenConns(c.config.Conn.SetMaxOpen)
sqlDB.SetMaxOpenConns(c.config.ConnSetMaxOpen)
}
// 设置了连接可复用的最大时间
if c.config.Conn.SetConnMaxLifetime == 0 {
if c.config.ConnSetConnMaxLifetime == 0 {
sqlDB.SetConnMaxLifetime(time.Second * 600)
} else {
sqlDB.SetConnMaxLifetime(time.Duration(c.config.Conn.SetConnMaxLifetime))
sqlDB.SetConnMaxLifetime(time.Duration(c.config.ConnSetConnMaxLifetime))
}
return c, nil

@ -10,30 +10,30 @@ import (
"time"
)
func NewGormPostgresClient(config *ConfigGormClient) (*GormClient, error) {
func NewGormPostgresClient(config *GormClientConfig) (*GormClient, error) {
var err error
c := &GormClient{}
c.config = config
// 判断路径
if c.config.Log.Path == "" {
if c.config.LogPath == "" {
logsUrl = "/logs/postgresql"
} else {
logsUrl = c.config.Log.Path
logsUrl = c.config.LogPath
}
if c.config.Log.Status == true {
if c.config.LogStatus {
var slowThreshold time.Duration
var logLevel logger.LogLevel
if c.config.Log.Slow == 0 {
if c.config.LogSlow == 0 {
slowThreshold = 100 * time.Millisecond
} else {
slowThreshold = time.Duration(c.config.Log.Slow)
slowThreshold = time.Duration(c.config.LogSlow)
}
if c.config.Log.Level == "Error" {
if c.config.LogLevel == "Error" {
logLevel = logger.Error
} else if c.config.Log.Level == "Warn" {
} else if c.config.LogLevel == "Warn" {
logLevel = logger.Warn
} else {
logLevel = logger.Info
@ -42,10 +42,10 @@ func NewGormPostgresClient(config *ConfigGormClient) (*GormClient, error) {
Logger: logger.New(
writer{},
logger.Config{
SlowThreshold: slowThreshold, // 慢SQL阈值
LogLevel: logLevel, // 日志级别
IgnoreRecordNotFoundError: c.config.Log.NotFoundError, // 忽略ErrRecordNotFound记录未找到错误
Colorful: c.config.Log.Colorful, // 禁用彩色打印
SlowThreshold: slowThreshold, // 慢SQL阈值
LogLevel: logLevel, // 日志级别
IgnoreRecordNotFoundError: true, // 忽略ErrRecordNotFound记录未找到错误
Colorful: true, // 禁用彩色打印
},
),
NowFunc: func() time.Time {
@ -66,53 +66,53 @@ func NewGormPostgresClient(config *ConfigGormClient) (*GormClient, error) {
}
// 设置空闲连接池中连接的最大数量
if c.config.Conn.SetMaxIdle == 0 {
if c.config.ConnSetMaxIdle == 0 {
sqlDB.SetMaxIdleConns(10)
} else {
sqlDB.SetMaxIdleConns(c.config.Conn.SetMaxIdle)
sqlDB.SetMaxIdleConns(c.config.ConnSetMaxIdle)
}
// 设置打开数据库连接的最大数量
if c.config.Conn.SetMaxOpen == 0 {
if c.config.ConnSetMaxOpen == 0 {
sqlDB.SetMaxOpenConns(100)
} else {
sqlDB.SetMaxOpenConns(c.config.Conn.SetMaxOpen)
sqlDB.SetMaxOpenConns(c.config.ConnSetMaxOpen)
}
// 设置了连接可复用的最大时间
if c.config.Conn.SetConnMaxLifetime == 0 {
sqlDB.SetConnMaxLifetime(time.Second * 600)
if c.config.ConnSetConnMaxLifetime == 0 {
sqlDB.SetConnMaxLifetime(time.Hour)
} else {
sqlDB.SetConnMaxLifetime(time.Duration(c.config.Conn.SetConnMaxLifetime))
sqlDB.SetConnMaxLifetime(time.Duration(c.config.ConnSetConnMaxLifetime))
}
return c, nil
}
func NewGormPostgresqlClient(config *ConfigGormClient) (*GormClient, error) {
func NewGormPostgresqlClient(config *GormClientConfig) (*GormClient, error) {
var err error
c := &GormClient{}
c.config = config
// 判断路径
if c.config.Log.Path == "" {
if c.config.LogPath == "" {
logsUrl = "/logs/postgresql"
} else {
logsUrl = c.config.Log.Path
logsUrl = c.config.LogPath
}
if c.config.Log.Status == true {
if c.config.LogStatus {
var slowThreshold time.Duration
var logLevel logger.LogLevel
if c.config.Log.Slow == 0 {
if c.config.LogSlow == 0 {
slowThreshold = 100 * time.Millisecond
} else {
slowThreshold = time.Duration(c.config.Log.Slow)
slowThreshold = time.Duration(c.config.LogSlow)
}
if c.config.Log.Level == "Error" {
if c.config.LogLevel == "Error" {
logLevel = logger.Error
} else if c.config.Log.Level == "Warn" {
} else if c.config.LogLevel == "Warn" {
logLevel = logger.Warn
} else {
logLevel = logger.Info
@ -121,10 +121,10 @@ func NewGormPostgresqlClient(config *ConfigGormClient) (*GormClient, error) {
Logger: logger.New(
writer{},
logger.Config{
SlowThreshold: slowThreshold, // 慢SQL阈值
LogLevel: logLevel, // 日志级别
IgnoreRecordNotFoundError: c.config.Log.NotFoundError, // 忽略ErrRecordNotFound记录未找到错误
Colorful: c.config.Log.Colorful, // 禁用彩色打印
SlowThreshold: slowThreshold, // 慢SQL阈值
LogLevel: logLevel, // 日志级别
IgnoreRecordNotFoundError: true, // 忽略ErrRecordNotFound记录未找到错误
Colorful: true, // 禁用彩色打印
},
),
NowFunc: func() time.Time {
@ -145,24 +145,24 @@ func NewGormPostgresqlClient(config *ConfigGormClient) (*GormClient, error) {
}
// 设置空闲连接池中连接的最大数量
if c.config.Conn.SetMaxIdle == 0 {
if c.config.ConnSetMaxIdle == 0 {
sqlDB.SetMaxIdleConns(10)
} else {
sqlDB.SetMaxIdleConns(c.config.Conn.SetMaxIdle)
sqlDB.SetMaxIdleConns(c.config.ConnSetMaxIdle)
}
// 设置打开数据库连接的最大数量
if c.config.Conn.SetMaxOpen == 0 {
if c.config.ConnSetMaxOpen == 0 {
sqlDB.SetMaxOpenConns(100)
} else {
sqlDB.SetMaxOpenConns(c.config.Conn.SetMaxOpen)
sqlDB.SetMaxOpenConns(c.config.ConnSetMaxOpen)
}
// 设置了连接可复用的最大时间
if c.config.Conn.SetConnMaxLifetime == 0 {
sqlDB.SetConnMaxLifetime(time.Second * 600)
if c.config.ConnSetConnMaxLifetime == 0 {
sqlDB.SetConnMaxLifetime(time.Hour)
} else {
sqlDB.SetConnMaxLifetime(time.Duration(c.config.Conn.SetConnMaxLifetime))
sqlDB.SetConnMaxLifetime(time.Duration(c.config.ConnSetConnMaxLifetime))
}
return c, nil

@ -0,0 +1,16 @@
package dorm
import "encoding/json"
// JsonDecodeNoError json字符串转结构体不报错
func JsonDecodeNoError(b []byte) map[string]interface{} {
var data map[string]interface{}
_ = json.Unmarshal(b, &data)
return data
}
// JsonEncodeNoError 结构体转json字符串不报错
func JsonEncodeNoError(data interface{}) string {
jsons, _ := json.Marshal(data)
return string(jsons)
}

@ -4,48 +4,56 @@ import (
"context"
"errors"
"fmt"
"go.mongodb.org/mongo-driver/bson"
"go.mongodb.org/mongo-driver/mongo"
"go.mongodb.org/mongo-driver/mongo/options"
)
type ConfigMongoClient struct {
// MongoClientFun *MongoClient 驱动
// string 库名
type MongoClientFun func() (*MongoClient, string)
// MongoClientCollectionFun *MongoClient 驱动
// string 库名
// string 集合
type MongoClientCollectionFun func() (*MongoClient, string, string)
// MongoClientConfig 实例配置
type MongoClientConfig struct {
Dns string // 地址
Opts *options.ClientOptions
DatabaseName string // 库名
}
// MongoClient 实例
type MongoClient struct {
Db *mongo.Client // 驱动
config *ConfigMongoClient // 配置
databaseName string // 库名
collectionName string // 表名
//filterArr []queryFilter // 查询条件数组
filter bson.D // 查询条件
db *mongo.Client // 驱动
configDatabaseName string // 库名
}
func NewMongoClient(config *ConfigMongoClient) (*MongoClient, error) {
// NewMongoClient 创建实例
func NewMongoClient(config *MongoClientConfig) (*MongoClient, error) {
var ctx = context.Background()
var err error
c := &MongoClient{config: config}
c := &MongoClient{}
c.databaseName = c.config.DatabaseName
c.configDatabaseName = config.DatabaseName
// 连接到MongoDB
if c.config.Dns != "" {
c.Db, err = mongo.Connect(context.Background(), options.Client().ApplyURI(c.config.Dns))
if config.Dns != "" {
c.db, err = mongo.Connect(ctx, options.Client().ApplyURI(config.Dns))
if err != nil {
return nil, errors.New(fmt.Sprintf("连接失败:%v", err))
}
} else {
c.Db, err = mongo.Connect(context.Background(), c.config.Opts)
c.db, err = mongo.Connect(ctx, config.Opts)
if err != nil {
return nil, errors.New(fmt.Sprintf("连接失败:%v", err))
}
}
// 检查连接
err = c.Db.Ping(context.TODO(), nil)
err = c.db.Ping(ctx, nil)
if err != nil {
return nil, errors.New(fmt.Sprintf("检查连接失败:%v", err))
}
@ -54,10 +62,6 @@ func NewMongoClient(config *ConfigMongoClient) (*MongoClient, error) {
}
// Close 关闭
func (c *MongoClient) Close() error {
err := c.Db.Disconnect(context.TODO())
if err != nil {
return errors.New(fmt.Sprintf("关闭失败:%v", err))
}
return nil
func (c *MongoClient) Close(ctx context.Context) error {
return c.db.Disconnect(ctx)
}

@ -0,0 +1,60 @@
package dorm
import (
"context"
"go.mongodb.org/mongo-driver/bson"
"go.mongodb.org/mongo-driver/mongo"
"go.mongodb.org/mongo-driver/mongo/options"
)
type MongoCollectionOptions struct {
db *mongo.Client // 驱动
configDatabaseName string // 库名
dbCollection *mongo.Collection // 集合
}
// Collection 选择集合
func (cd *MongoDatabaseOptions) Collection(name string, opts ...*options.CollectionOptions) *MongoCollectionOptions {
return &MongoCollectionOptions{
db: cd.db, // 驱动
configDatabaseName: cd.configDatabaseName, // 库名
dbCollection: cd.dbDatabase.Collection(name, opts...), // 集合
}
}
// CreateOneIndexes 创建一个索引
func (cc *MongoCollectionOptions) CreateOneIndexes(ctx context.Context, key string, value string) (string, error) {
return cc.dbCollection.Indexes().CreateOne(ctx, mongo.IndexModel{
Keys: bson.D{{
Key: key,
Value: value,
}},
})
}
// CreateOneUniqueIndexes 创建一个唯一索引
func (cc *MongoCollectionOptions) CreateOneUniqueIndexes(ctx context.Context, key string, value string) (string, error) {
return cc.dbCollection.Indexes().CreateOne(ctx, mongo.IndexModel{
Keys: bson.D{{
Key: key,
Value: value,
}},
Options: options.Index().SetUnique(true),
})
}
// CreateOneUniqueIndexesOpts 创建一个索引
func (cc *MongoCollectionOptions) CreateOneUniqueIndexesOpts(ctx context.Context, key string, value string, opts *options.IndexOptions) (string, error) {
return cc.dbCollection.Indexes().CreateOne(ctx, mongo.IndexModel{
Keys: bson.D{{
Key: key,
Value: value,
}},
Options: opts,
})
}
// CreateManyIndexes 创建多个索引
func (cc *MongoCollectionOptions) CreateManyIndexes(ctx context.Context, models []mongo.IndexModel) ([]string, error) {
return cc.dbCollection.Indexes().CreateMany(ctx, models)
}

@ -0,0 +1,100 @@
package dorm
import (
"context"
"go.mongodb.org/mongo-driver/mongo"
"go.mongodb.org/mongo-driver/mongo/options"
)
// InsertOne 插入一个文档
func (cc *MongoCollectionOptions) InsertOne(ctx context.Context, document interface{}, opts ...*options.InsertOneOptions) (*mongo.InsertOneResult, error) {
return cc.dbCollection.InsertOne(ctx, document, opts...)
}
// InsertMany 插入多个文档
func (cc *MongoCollectionOptions) InsertMany(ctx context.Context, document []interface{}, opts ...*options.InsertManyOptions) (*mongo.InsertManyResult, error) {
return cc.dbCollection.InsertMany(ctx, document, opts...)
}
// DeleteOne 删除一个文档
func (cc *MongoCollectionOptions) DeleteOne(ctx context.Context, filter interface{}, opts ...*options.DeleteOptions) (*mongo.DeleteResult, error) {
return cc.dbCollection.DeleteOne(ctx, filter, opts...)
}
// DeleteMany 删除多个文档
func (cc *MongoCollectionOptions) DeleteMany(ctx context.Context, filter interface{}, opts ...*options.DeleteOptions) (*mongo.DeleteResult, error) {
return cc.dbCollection.DeleteMany(ctx, filter, opts...)
}
// UpdateByID 按ID更新
func (cc *MongoCollectionOptions) UpdateByID(ctx context.Context, id interface{}, update interface{}, opts ...*options.UpdateOptions) (*mongo.UpdateResult, error) {
return cc.dbCollection.UpdateByID(ctx, id, update, opts...)
}
// UpdateOne 更新一个文档
func (cc *MongoCollectionOptions) UpdateOne(ctx context.Context, filter interface{}, update interface{}, opts ...*options.UpdateOptions) (*mongo.UpdateResult, error) {
return cc.dbCollection.UpdateOne(ctx, filter, update, opts...)
}
// UpdateMany 更新多个文档
func (cc *MongoCollectionOptions) UpdateMany(ctx context.Context, filter interface{}, update interface{}, opts ...*options.UpdateOptions) (*mongo.UpdateResult, error) {
return cc.dbCollection.UpdateMany(ctx, filter, update, opts...)
}
// ReplaceOne 替换一个文档
func (cc *MongoCollectionOptions) ReplaceOne(ctx context.Context, filter interface{}, update interface{}, opts ...*options.ReplaceOptions) (*mongo.UpdateResult, error) {
return cc.dbCollection.ReplaceOne(ctx, filter, update, opts...)
}
// Aggregate 统计分析
func (cc *MongoCollectionOptions) Aggregate(ctx context.Context, pipeline interface{}, opts ...*options.AggregateOptions) (*mongo.Cursor, error) {
return cc.dbCollection.Aggregate(ctx, pipeline, opts...)
}
// CountDocuments 计数文档
func (cc *MongoCollectionOptions) CountDocuments(ctx context.Context, filter interface{}, opts ...*options.CountOptions) (int64, error) {
return cc.dbCollection.CountDocuments(ctx, filter, opts...)
}
// EstimatedDocumentCount 估计文档计数
func (cc *MongoCollectionOptions) EstimatedDocumentCount(ctx context.Context, opts ...*options.EstimatedDocumentCountOptions) (int64, error) {
return cc.dbCollection.EstimatedDocumentCount(ctx, opts...)
}
func (cc *MongoCollectionOptions) Distinct(ctx context.Context, fieldName string, filter interface{}, opts ...*options.DistinctOptions) ([]interface{}, error) {
return cc.dbCollection.Distinct(ctx, fieldName, filter, opts...)
}
// Find 查询多个文档
func (cc *MongoCollectionOptions) Find(ctx context.Context, filter interface{}, opts ...*options.FindOptions) (*mongo.Cursor, error) {
return cc.dbCollection.Find(ctx, filter, opts...)
}
// FindOne 查询一个文档
func (cc *MongoCollectionOptions) FindOne(ctx context.Context, filter interface{}, opts ...*options.FindOneOptions) *mongo.SingleResult {
return cc.dbCollection.FindOne(ctx, filter, opts...)
}
func (cc *MongoCollectionOptions) FindOneAndDelete(ctx context.Context, filter interface{}, opts ...*options.FindOneAndDeleteOptions) *mongo.SingleResult {
return cc.dbCollection.FindOneAndDelete(ctx, filter, opts...)
}
func (cc *MongoCollectionOptions) FindOneAndReplace(ctx context.Context, filter interface{}, replacement interface{}, opts ...*options.FindOneAndReplaceOptions) *mongo.SingleResult {
return cc.dbCollection.FindOneAndReplace(ctx, filter, replacement, opts...)
}
func (cc *MongoCollectionOptions) FindOneAndUpdate(ctx context.Context, filter interface{}, replacement interface{}, opts ...*options.FindOneAndUpdateOptions) *mongo.SingleResult {
return cc.dbCollection.FindOneAndUpdate(ctx, filter, replacement, opts...)
}
func (cc *MongoCollectionOptions) Watch(ctx context.Context, pipeline interface{}, opts ...*options.ChangeStreamOptions) (*mongo.ChangeStream, error) {
return cc.dbCollection.Watch(ctx, pipeline, opts...)
}
func (cc *MongoCollectionOptions) Indexes(ctx context.Context) mongo.IndexView {
return cc.dbCollection.Indexes()
}
func (cc *MongoCollectionOptions) Drop(ctx context.Context) error {
return cc.dbCollection.Drop(ctx)
}

@ -1,185 +0,0 @@
package dorm
import (
"context"
"go.mongodb.org/mongo-driver/bson"
"go.mongodb.org/mongo-driver/mongo"
"go.mongodb.org/mongo-driver/mongo/options"
)
// InsertOne 插入一个文档
func (c *MongoClient) InsertOne(document interface{}) (result *mongo.InsertOneResult, err error) {
collection := c.Db.Database(c.getDatabaseName()).Collection(c.collectionName)
result, err = collection.InsertOne(context.TODO(), document)
return
}
// InsertMany 插入多个文档
func (c *MongoClient) InsertMany(documents []interface{}) (result *mongo.InsertManyResult, err error) {
collection := c.Db.Database(c.getDatabaseName()).Collection(c.collectionName)
result, err = collection.InsertMany(context.TODO(), documents)
return
}
// Delete 删除文档
func (c *MongoClient) Delete(filter interface{}) (err error) {
collection := c.Db.Database(c.getDatabaseName()).Collection(c.collectionName)
_, err = collection.DeleteOne(context.TODO(), filter)
return
}
// DeleteId 删除文档
func (c *MongoClient) DeleteId(id interface{}) (err error) {
collection := c.Db.Database(c.getDatabaseName()).Collection(c.collectionName)
_, err = collection.DeleteOne(context.TODO(), bson.M{"_id": id})
return
}
// DeleteMany 删除多个文档
func (c *MongoClient) DeleteMany(filter interface{}) (result *mongo.DeleteResult, err error) {
collection := c.Db.Database(c.getDatabaseName()).Collection(c.collectionName)
result, err = collection.DeleteMany(context.TODO(), filter)
return
}
// UpdateOne 更新单个文档
// 修改字段的值($set)
// 字段增加值 inc($inc)
// 从数组中增加一个元素 push($push)
// 从数组中删除一个元素 pull($pull)
func (c *MongoClient) UpdateOne(filter interface{}, update interface{}) (err error) {
collection := c.Db.Database(c.getDatabaseName()).Collection(c.collectionName)
_, err = collection.UpdateOne(context.TODO(), filter, update)
return
}
// UpdateId 更新单个文档
// 修改字段的值($set)
// 字段增加值 inc($inc)
// 从数组中增加一个元素 push($push)
// 从数组中删除一个元素 pull($pull)
func (c *MongoClient) UpdateId(id interface{}, update interface{}) (err error) {
collection := c.Db.Database(c.getDatabaseName()).Collection(c.collectionName)
_, err = collection.UpdateOne(context.TODO(), bson.M{"_id": id}, update)
return
}
// UpdateMany 更新多个文档
// 修改字段的值($set)
// 字段增加值 inc($inc)
// 从数组中增加一个元素 push($push)
// 从数组中删除一个元素 pull($pull)
func (c *MongoClient) UpdateMany(filter interface{}, update interface{}) (result *mongo.UpdateResult, err error) {
collection := c.Db.Database(c.getDatabaseName()).Collection(c.collectionName)
result, err = collection.UpdateMany(context.TODO(), filter, update)
return
}
type FindResultI interface {
Many(result interface{}) error
}
// Find 查询
func (c *MongoClient) Find(filter interface{}) (*mongo.Cursor, error) {
collection := c.Db.Database(c.getDatabaseName()).Collection(c.collectionName)
return collection.Find(context.TODO(), filter)
}
type FindOneResultI interface {
One(result interface{}) error
}
// FindOne 查询单个文档
func (c *MongoClient) FindOne(filter interface{}) *mongo.SingleResult {
collection := c.Db.Database(c.getDatabaseName()).Collection(c.collectionName)
return collection.FindOne(context.TODO(), filter)
}
type FindManyResultI interface {
Many(result interface{}) error
}
// FindMany 查询多个文档
func (c *MongoClient) FindMany(filter interface{}) (*mongo.Cursor, error) {
collection := c.Db.Database(c.getDatabaseName()).Collection(c.collectionName)
return collection.Find(context.TODO(), filter)
}
// FindManyByFilters 多条件查询
func (c *MongoClient) FindManyByFilters(filter interface{}) (result *mongo.Cursor, err error) {
collection, err := c.Db.Database(c.getDatabaseName()).Collection(c.collectionName).Clone()
result, err = collection.Find(context.TODO(), bson.M{"$and": filter})
return result, err
}
// FindManyByFiltersSort 多条件查询支持排序
func (c *MongoClient) FindManyByFiltersSort(filter interface{}, Sort interface{}) (result *mongo.Cursor, err error) {
collection, err := c.Db.Database(c.getDatabaseName()).Collection(c.collectionName).Clone()
findOptions := options.Find()
findOptions.SetSort(Sort)
result, err = collection.Find(context.TODO(), filter, findOptions)
return result, err
}
// FindCollection 查询集合文档
func (c *MongoClient) FindCollection(Limit int64) (result *mongo.Cursor, err error) {
collection := c.Db.Database(c.getDatabaseName()).Collection(c.collectionName)
findOptions := options.Find()
findOptions.SetLimit(Limit)
result, err = collection.Find(context.TODO(), bson.D{{}}, findOptions)
return result, err
}
// FindCollectionSort 查询集合文档支持排序
func (c *MongoClient) FindCollectionSort(Sort interface{}, Limit int64) (result *mongo.Cursor, err error) {
collection := c.Db.Database(c.getDatabaseName()).Collection(c.collectionName)
findOptions := options.Find()
findOptions.SetSort(Sort)
findOptions.SetLimit(Limit)
result, err = collection.Find(context.TODO(), bson.D{{}}, findOptions)
return result, err
}
// FindManyCollectionSort 查询集合文档支持排序支持条件
func (c *MongoClient) FindManyCollectionSort(filter interface{}, Sort interface{}) (result *mongo.Cursor, err error) {
collection := c.Db.Database(c.getDatabaseName()).Collection(c.collectionName)
findOptions := options.Find()
findOptions.SetSort(Sort)
result, err = collection.Find(context.TODO(), filter, findOptions)
return result, err
}
// CollectionCount 查询集合里有多少数据
func (c *MongoClient) CollectionCount() (name string, size int64) {
collection := c.Db.Database(c.getDatabaseName()).Collection(c.collectionName)
name = collection.Name()
size, _ = collection.EstimatedDocumentCount(context.TODO())
return name, size
}
// CollectionDocuments 按选项查询集合
// Skip 跳过
// Limit 读取数量
// sort 1 -1 . 1 为升序 -1 为降序
func (c *MongoClient) CollectionDocuments(Skip, Limit int64, sort int, key string, value interface{}) (result *mongo.Cursor, err error) {
collection := c.Db.Database(c.getDatabaseName()).Collection(c.collectionName)
SORT := bson.D{{"_id", sort}}
filter := bson.D{{key, value}}
findOptions := options.Find().SetSort(SORT).SetLimit(Limit).SetSkip(Skip)
result, err = collection.Find(context.TODO(), filter, findOptions)
return result, err
}
// AggregateByFiltersSort 统计分析
func (c *MongoClient) AggregateByFiltersSort(pipeline interface{}) (result *mongo.Cursor, err error) {
collection := c.Db.Database(c.getDatabaseName()).Collection(c.collectionName)
result, err = collection.Aggregate(context.TODO(), pipeline)
return result, err
}
// CountDocumentsByFilters 统计数量
func (c *MongoClient) CountDocumentsByFilters(filter interface{}) (count int64, err error) {
collection := c.Db.Database(c.getDatabaseName()).Collection(c.collectionName)
count, err = collection.CountDocuments(context.TODO(), filter)
return count, err
}

@ -1,15 +0,0 @@
package dorm
import (
"context"
"go.mongodb.org/mongo-driver/mongo"
)
type FindResult struct {
cursor *mongo.Cursor
err error
}
func (f *FindResult) Many(result interface{}) error {
return f.cursor.All(context.TODO(), result)
}

@ -1,15 +0,0 @@
package dorm
import (
"context"
"go.mongodb.org/mongo-driver/mongo"
)
type FindManyResult struct {
cursor *mongo.Cursor
err error
}
func (f *FindManyResult) Many(result interface{}) error {
return f.cursor.All(context.TODO(), result)
}

@ -1,11 +0,0 @@
package dorm
import "go.mongodb.org/mongo-driver/mongo"
type FindOneResult struct {
singleResult *mongo.SingleResult
}
func (f *FindOneResult) One(result interface{}) error {
return f.singleResult.Decode(result)
}

@ -0,0 +1,69 @@
package dorm
import (
"context"
"go.mongodb.org/mongo-driver/mongo"
"go.mongodb.org/mongo-driver/mongo/options"
"reflect"
)
type MongoDatabaseOptions struct {
db *mongo.Client // 驱动
configDatabaseName string // 库名
dbDatabase *mongo.Database // 数据库
}
// Database 选择数据库
func (c *MongoClient) Database(name string, opts ...*options.DatabaseOptions) *MongoDatabaseOptions {
return &MongoDatabaseOptions{
db: c.db, // 驱动
configDatabaseName: c.configDatabaseName, // 库名
dbDatabase: c.db.Database(name, opts...), // 数据库
}
}
// CreateCollection 创建集合
func (cd *MongoDatabaseOptions) CreateCollection(ctx context.Context, name string, opts ...*options.CreateCollectionOptions) error {
return cd.dbDatabase.CreateCollection(ctx, name, opts...)
}
// CreateTimeSeriesCollection 创建时间序列集合
func (cd *MongoDatabaseOptions) CreateTimeSeriesCollection(ctx context.Context, name string, timeField string) error {
return cd.dbDatabase.CreateCollection(ctx, name, options.CreateCollection().SetTimeSeriesOptions(options.TimeSeries().SetTimeField(timeField)))
}
// Model 传入模型自动获取库名和表名
// https://studygolang.com/articles/896
// DatabaseName 库名
// CollectionName 集合名
func (c *MongoClient) Model(value interface{}) *MongoCollectionOptions {
var databaseOptions *MongoDatabaseOptions
var collectionOptions *MongoCollectionOptions
val := reflect.ValueOf(value)
methodDatabaseNameValue := val.MethodByName("DatabaseName")
if methodDatabaseNameValue.IsValid() {
databaseName := methodDatabaseNameValue.Call(nil)[0].String()
databaseOptions = c.Database(databaseName)
} else {
databaseOptions = c.Database(c.configDatabaseName)
}
methodCollectionNameValue := val.MethodByName("CollectionName")
if methodCollectionNameValue.IsValid() {
collectionName := methodCollectionNameValue.Call(nil)[0].String()
collectionOptions = databaseOptions.Collection(collectionName)
} else {
methodTableNameValue := val.MethodByName("TableName")
if methodTableNameValue.IsValid() {
collectionName := methodTableNameValue.Call(nil)[0].String()
collectionOptions = databaseOptions.Collection(collectionName)
} else {
panic(NoConfigCollectionName)
}
}
return collectionOptions
}

@ -0,0 +1,8 @@
package dorm
import "errors"
var (
NoConfigDatabaseName = errors.New("没有配置库名")
NoConfigCollectionName = errors.New("没有配置集合名")
)

@ -4,15 +4,5 @@ import "go.mongodb.org/mongo-driver/mongo"
// GetDb 获取驱动
func (c *MongoClient) GetDb() *mongo.Client {
return c.Db
}
// 获取库名
func (c *MongoClient) getDatabaseName() string {
return c.databaseName
}
// 获取表名
func (c *MongoClient) getCollectionName() string {
return c.collectionName
return c.db
}

@ -1,10 +0,0 @@
package dorm
import "encoding/json"
// JsonDecodeNoError Json解码不报错
func JsonDecodeNoError(b []byte) map[string]interface{} {
var data map[string]interface{}
_ = json.Unmarshal(b, &data)
return data
}

@ -0,0 +1,59 @@
package dorm
import (
"context"
"go.mongodb.org/mongo-driver/mongo"
"log"
)
type MongoSessionOptions struct {
db *mongo.Client // 驱动
configDatabaseName string // 库名
session mongo.Session // 会话
sessionContext mongo.SessionContext // 会话上下文
}
// Begin 开始事务,会同时创建开始会话需要在退出时关闭会话
func (c *MongoClient) Begin() *MongoSessionOptions {
var ctx = context.TODO()
var err error
ms := &MongoSessionOptions{}
ms.db = c.GetDb()
ms.configDatabaseName = c.configDatabaseName
// 开始会话
ms.session, err = ms.db.StartSession()
if err != nil {
log.Println("开始会话异常:", err)
}
// 会话上下文
ms.sessionContext = mongo.NewSessionContext(ctx, ms.session)
// 会话开启事务
err = ms.session.StartTransaction()
return ms
}
// Rollback 回滚事务
func (cs *MongoSessionOptions) Rollback() {
var ctx = context.TODO()
err := cs.session.AbortTransaction(ctx)
if err != nil {
log.Println("回滚事务异常:", err)
}
cs.session.EndSession(ctx)
}
// Commit 提交事务
func (cs *MongoSessionOptions) Commit() {
var ctx = context.TODO()
err := cs.session.CommitTransaction(ctx)
if err != nil {
log.Println("提交事务异常:", err)
}
cs.session.EndSession(ctx)
}

@ -0,0 +1,25 @@
package dorm
import (
"go.mongodb.org/mongo-driver/mongo"
"go.mongodb.org/mongo-driver/mongo/options"
)
type MongoSessionCollectionOptions struct {
db *mongo.Client // 驱动
configDatabaseName string // 库名
session mongo.Session // 会话
sessionContext mongo.SessionContext // 会话上下文
dbCollection *mongo.Collection // 集合
}
// Collection 选择集合
func (csd *MongoSessionDatabaseOptions) Collection(name string, opts ...*options.CollectionOptions) *MongoSessionCollectionOptions {
return &MongoSessionCollectionOptions{
db: csd.db, // 驱动
configDatabaseName: csd.configDatabaseName, // 库名
session: csd.session, // 会话
sessionContext: csd.sessionContext, // 会话上下文
dbCollection: csd.dbDatabase.Collection(name, opts...), // 集合
}
}

@ -0,0 +1,99 @@
package dorm
import (
"go.mongodb.org/mongo-driver/mongo"
"go.mongodb.org/mongo-driver/mongo/options"
)
// InsertOne 插入一个文档
func (csc *MongoSessionCollectionOptions) InsertOne(document interface{}, opts ...*options.InsertOneOptions) (*mongo.InsertOneResult, error) {
return csc.dbCollection.InsertOne(csc.sessionContext, document, opts...)
}
// InsertMany 插入多个文档
func (csc *MongoSessionCollectionOptions) InsertMany(document []interface{}, opts ...*options.InsertManyOptions) (*mongo.InsertManyResult, error) {
return csc.dbCollection.InsertMany(csc.sessionContext, document, opts...)
}
// DeleteOne 删除一个文档
func (csc *MongoSessionCollectionOptions) DeleteOne(filter interface{}, opts ...*options.DeleteOptions) (*mongo.DeleteResult, error) {
return csc.dbCollection.DeleteOne(csc.sessionContext, filter, opts...)
}
// DeleteMany 删除多个文档
func (csc *MongoSessionCollectionOptions) DeleteMany(filter interface{}, opts ...*options.DeleteOptions) (*mongo.DeleteResult, error) {
return csc.dbCollection.DeleteMany(csc.sessionContext, filter, opts...)
}
// UpdateByID 按ID更新
func (csc *MongoSessionCollectionOptions) UpdateByID(id interface{}, update interface{}, opts ...*options.UpdateOptions) (*mongo.UpdateResult, error) {
return csc.dbCollection.UpdateByID(csc.sessionContext, id, update, opts...)
}
// UpdateOne 更新一个文档
func (csc *MongoSessionCollectionOptions) UpdateOne(filter interface{}, update interface{}, opts ...*options.UpdateOptions) (*mongo.UpdateResult, error) {
return csc.dbCollection.UpdateOne(csc.sessionContext, filter, update, opts...)
}
// UpdateMany 更新多个文档
func (csc *MongoSessionCollectionOptions) UpdateMany(filter interface{}, update interface{}, opts ...*options.UpdateOptions) (*mongo.UpdateResult, error) {
return csc.dbCollection.UpdateMany(csc.sessionContext, filter, update, opts...)
}
// ReplaceOne 替换一个文档
func (csc *MongoSessionCollectionOptions) ReplaceOne(filter interface{}, update interface{}, opts ...*options.ReplaceOptions) (*mongo.UpdateResult, error) {
return csc.dbCollection.ReplaceOne(csc.sessionContext, filter, update, opts...)
}
// Aggregate 统计分析
func (csc *MongoSessionCollectionOptions) Aggregate(pipeline interface{}, opts ...*options.AggregateOptions) (*mongo.Cursor, error) {
return csc.dbCollection.Aggregate(csc.sessionContext, pipeline, opts...)
}
// CountDocuments 计数文档
func (csc *MongoSessionCollectionOptions) CountDocuments(filter interface{}, opts ...*options.CountOptions) (int64, error) {
return csc.dbCollection.CountDocuments(csc.sessionContext, filter, opts...)
}
// EstimatedDocumentCount 估计文档计数
func (csc *MongoSessionCollectionOptions) EstimatedDocumentCount(opts ...*options.EstimatedDocumentCountOptions) (int64, error) {
return csc.dbCollection.EstimatedDocumentCount(csc.sessionContext, opts...)
}
func (csc *MongoSessionCollectionOptions) Distinct(fieldName string, filter interface{}, opts ...*options.DistinctOptions) ([]interface{}, error) {
return csc.dbCollection.Distinct(csc.sessionContext, fieldName, filter, opts...)
}
// Find 查询多个文档
func (csc *MongoSessionCollectionOptions) Find(filter interface{}, opts ...*options.FindOptions) (*mongo.Cursor, error) {
return csc.dbCollection.Find(csc.sessionContext, filter, opts...)
}
// FindOne 查询一个文档
func (csc *MongoSessionCollectionOptions) FindOne(filter interface{}, opts ...*options.FindOneOptions) *mongo.SingleResult {
return csc.dbCollection.FindOne(csc.sessionContext, filter, opts...)
}
func (csc *MongoSessionCollectionOptions) FindOneAndDelete(filter interface{}, opts ...*options.FindOneAndDeleteOptions) *mongo.SingleResult {
return csc.dbCollection.FindOneAndDelete(csc.sessionContext, filter, opts...)
}
func (csc *MongoSessionCollectionOptions) FindOneAndReplace(filter interface{}, replacement interface{}, opts ...*options.FindOneAndReplaceOptions) *mongo.SingleResult {
return csc.dbCollection.FindOneAndReplace(csc.sessionContext, filter, replacement, opts...)
}
func (csc *MongoSessionCollectionOptions) FindOneAndUpdate(filter interface{}, replacement interface{}, opts ...*options.FindOneAndUpdateOptions) *mongo.SingleResult {
return csc.dbCollection.FindOneAndUpdate(csc.sessionContext, filter, replacement, opts...)
}
func (csc *MongoSessionCollectionOptions) Watch(pipeline interface{}, opts ...*options.ChangeStreamOptions) (*mongo.ChangeStream, error) {
return csc.dbCollection.Watch(csc.sessionContext, pipeline, opts...)
}
func (csc *MongoSessionCollectionOptions) Indexes() mongo.IndexView {
return csc.dbCollection.Indexes()
}
func (csc *MongoSessionCollectionOptions) Drop() error {
return csc.dbCollection.Drop(csc.sessionContext)
}

@ -0,0 +1,62 @@
package dorm
import (
"go.mongodb.org/mongo-driver/mongo"
"go.mongodb.org/mongo-driver/mongo/options"
"reflect"
)
type MongoSessionDatabaseOptions struct {
db *mongo.Client // 驱动
configDatabaseName string // 库名
session mongo.Session // 会话
sessionContext mongo.SessionContext // 会话上下文
dbDatabase *mongo.Database // 数据库
}
// Database 选择数据库
func (cs *MongoSessionOptions) Database(name string, opts ...*options.DatabaseOptions) *MongoSessionDatabaseOptions {
return &MongoSessionDatabaseOptions{
db: cs.db, // 驱动
configDatabaseName: cs.configDatabaseName, // 库名
session: cs.session, // 会话
sessionContext: cs.sessionContext, // 会话上下文
dbDatabase: cs.db.Database(name, opts...), // 数据库
}
}
// Model 传入模型自动获取库名和表名
// https://studygolang.com/articles/896
// DatabaseName 库名
// CollectionName 集合名
func (cs *MongoSessionOptions) Model(value interface{}) *MongoSessionCollectionOptions {
var sessionDatabaseOptions *MongoSessionDatabaseOptions
var sessionCollectionOptions *MongoSessionCollectionOptions
val := reflect.ValueOf(value)
methodDatabaseNameValue := val.MethodByName("DatabaseName")
if methodDatabaseNameValue.IsValid() {
databaseName := methodDatabaseNameValue.Call(nil)[0].String()
sessionDatabaseOptions = cs.Database(databaseName)
} else {
sessionDatabaseOptions = cs.Database(cs.configDatabaseName)
}
methodCollectionNameValue := val.MethodByName("CollectionName")
if methodCollectionNameValue.IsValid() {
collectionName := methodCollectionNameValue.Call(nil)[0].String()
sessionCollectionOptions = sessionDatabaseOptions.Collection(collectionName)
} else {
methodTableNameValue := val.MethodByName("TableName")
if methodTableNameValue.IsValid() {
collectionName := methodTableNameValue.Call(nil)[0].String()
sessionCollectionOptions = sessionDatabaseOptions.Collection(collectionName)
} else {
panic(NoConfigCollectionName)
}
}
return sessionCollectionOptions
}

@ -0,0 +1,20 @@
package dorm
import (
"go.mongodb.org/mongo-driver/mongo"
)
// GetDb 获取驱动
func (cs *MongoSessionOptions) GetDb() *mongo.Client {
return cs.db
}
// GetSession 获取会话
func (cs *MongoSessionOptions) GetSession() mongo.Session {
return cs.session
}
// GetSessionContext 获取会话上下文
func (cs *MongoSessionOptions) GetSessionContext() mongo.SessionContext {
return cs.sessionContext
}

@ -1,28 +0,0 @@
package dorm
import "reflect"
// Database 设置库名
func (c *MongoClient) Database(databaseName string) *MongoClient {
c.databaseName = databaseName
return c
}
// Collection 设置表名
func (c *MongoClient) Collection(collectionName string) *MongoClient {
c.collectionName = collectionName
return c
}
// Model 传入模型自动获取库名和表名
func (c *MongoClient) Model(value interface{}) *MongoClient {
// https://studygolang.com/articles/896
val := reflect.ValueOf(value)
if methodValue := val.MethodByName("Database"); methodValue.IsValid() {
c.databaseName = methodValue.Call(nil)[0].String()
}
if methodValue := val.MethodByName("TableName"); methodValue.IsValid() {
c.collectionName = methodValue.Call(nil)[0].String()
}
return c
}

@ -7,44 +7,79 @@ import (
"time"
)
// BsonTime 类型
// BsonTime 时间类型
type BsonTime time.Time
// Value 时间类型
func (t BsonTime) Value() string {
return gotime.SetCurrent(time.Time(t)).Bson()
}
// MarshalJSON 实现json序列化
func (t BsonTime) MarshalJSON() ([]byte, error) {
//log.Println("MarshalJSON")
func (bt BsonTime) MarshalJSON() ([]byte, error) {
b := make([]byte, 0)
b = append(b, gotime.SetCurrent(time.Time(t)).Bson()...)
b = append(b, '"')
b = append(b, gotime.SetCurrent(time.Time(bt)).Bson()...)
b = append(b, '"')
return b, nil
}
// UnmarshalJSON 实现json反序列化
func (t *BsonTime) UnmarshalJSON(data []byte) (err error) {
//log.Println("UnmarshalJSON")
t1 := gotime.SetCurrentParse(string(data))
*t = BsonTime(t1.Time)
return
func (bt *BsonTime) UnmarshalJSON(data []byte) (err error) {
if string(data) == "null" {
return nil
}
bsonTime := gotime.SetCurrentParse(string(data))
*bt = BsonTime(bsonTime.Time)
return nil
}
// Time 转时间
func (bt BsonTime) Time() time.Time {
return gotime.SetCurrent(time.Time(bt)).Time
}
// Format 转时间字符串
func (bt BsonTime) Format() string {
return gotime.SetCurrent(time.Time(bt)).Format()
}
// TimePro 转时间操作
func (bt BsonTime) TimePro() gotime.Pro {
return gotime.SetCurrent(time.Time(bt))
}
// NewBsonTimeCurrent 创建当前时间
func NewBsonTimeCurrent() BsonTime {
return BsonTime(gotime.Current().Time)
}
// NewBsonTimeFromTime 创建某个时间
func NewBsonTimeFromTime(t time.Time) BsonTime {
return BsonTime(t)
}
// NewBsonTimeFromString 创建某个时间 字符串
func NewBsonTimeFromString(t string) BsonTime {
return BsonTime(gotime.SetCurrentParse(t).Time)
}
// Value 时间类型
func (bt BsonTime) Value() string {
return gotime.SetCurrent(time.Time(bt)).Bson()
}
// MarshalBSONValue 实现bson序列化
func (t BsonTime) MarshalBSONValue() (bsontype.Type, []byte, error) {
//log.Println("MarshalBSONValue")
targetTime := gotime.SetCurrent(time.Time(t)).Bson()
return bson.MarshalValue(targetTime)
func (bt BsonTime) MarshalBSONValue() (bsontype.Type, []byte, error) {
return bson.MarshalValue(gotime.SetCurrent(time.Time(bt)).Bson())
}
// UnmarshalBSONValue 实现bson反序列化
func (t *BsonTime) UnmarshalBSONValue(t2 bsontype.Type, data []byte) error {
//log.Println("UnmarshalBSONValue")
func (bt *BsonTime) UnmarshalBSONValue(t bsontype.Type, data []byte) error {
t1 := gotime.SetCurrentParse(string(data))
//if string(data) == "" {
// return errors.New(fmt.Sprintf("%s, %s, %s", "读取数据失败:", t2, data))
// return errors.New(fmt.Sprintf("%s, %s, %s", "读取数据失败:", t, data))
//}
*t = BsonTime(t1.Time)
*bt = BsonTime(t1.Time)
return nil
}

@ -1,48 +0,0 @@
package dorm
import (
"context"
"go.mongodb.org/mongo-driver/mongo"
)
type MongoTransaction struct {
startSession mongo.Session
Session mongo.SessionContext
db *mongo.Client // 驱动
databaseName string // 库名
collectionName string // 表名
}
// Begin 开始事务,会同时创建开始会话需要在退出时关闭会话
func (c *MongoClient) Begin() (ms MongoTransaction, err error) {
ms.db = c.Db
// 开始会话
ms.startSession, err = ms.db.StartSession()
if err != nil {
panic(err)
}
// 会话上下文
ms.Session = mongo.NewSessionContext(context.Background(), ms.startSession)
// 会话开启事务
err = ms.startSession.StartTransaction()
return ms, err
}
// Close 关闭会话
func (ms *MongoTransaction) Close() {
ms.startSession.EndSession(context.TODO())
}
// Rollback 回滚事务
func (ms *MongoTransaction) Rollback() error {
return ms.startSession.AbortTransaction(context.Background())
}
// Commit 提交事务
func (ms *MongoTransaction) Commit() error {
return ms.startSession.CommitTransaction(context.Background())
}

@ -1,174 +0,0 @@
package dorm
import (
"context"
"go.mongodb.org/mongo-driver/bson"
"go.mongodb.org/mongo-driver/mongo"
"go.mongodb.org/mongo-driver/mongo/options"
)
// InsertOne 插入一个文档
func (ms *MongoTransaction) InsertOne(document interface{}) (result *mongo.InsertOneResult, err error) {
collection := ms.db.Database(ms.getDatabaseName()).Collection(ms.collectionName)
result, err = collection.InsertOne(ms.Session, document)
return
}
// InsertMany 插入多个文档
func (ms *MongoTransaction) InsertMany(documents []interface{}) (result *mongo.InsertManyResult, err error) {
collection := ms.db.Database(ms.getDatabaseName()).Collection(ms.collectionName)
result, err = collection.InsertMany(ms.Session, documents)
return
}
// Delete 删除文档
func (ms *MongoTransaction) Delete(filter interface{}) (err error) {
collection := ms.db.Database(ms.getDatabaseName()).Collection(ms.collectionName)
_, err = collection.DeleteOne(ms.Session, filter)
return
}
// DeleteId 删除文档
func (ms *MongoTransaction) DeleteId(id interface{}) (err error) {
collection := ms.db.Database(ms.getDatabaseName()).Collection(ms.collectionName)
_, err = collection.DeleteOne(ms.Session, bson.M{"_id": id})
return
}
// DeleteMany 删除多个文档
func (ms *MongoTransaction) DeleteMany(key string, value interface{}) (result *mongo.DeleteResult, err error) {
collection := ms.db.Database(ms.getDatabaseName()).Collection(ms.collectionName)
filter := bson.D{{key, value}}
result, err = collection.DeleteMany(ms.Session, filter)
return
}
// UpdateOne 更新单个文档
// 修改字段的值($set)
// 字段增加值 inc($inc)
// 从数组中增加一个元素 push($push)
// 从数组中删除一个元素 pull($pull)
func (ms *MongoTransaction) UpdateOne(filter interface{}, update interface{}) (err error) {
collection := ms.db.Database(ms.getDatabaseName()).Collection(ms.collectionName)
_, err = collection.UpdateOne(ms.Session, filter, update)
return
}
// UpdateId 更新单个文档
// 修改字段的值($set)
// 字段增加值 inc($inc)
// 从数组中增加一个元素 push($push)
// 从数组中删除一个元素 pull($pull)
func (ms *MongoTransaction) UpdateId(id interface{}, update interface{}) (err error) {
collection := ms.db.Database(ms.getDatabaseName()).Collection(ms.collectionName)
_, err = collection.UpdateOne(context.TODO(), bson.M{"_id": id}, update)
return
}
// UpdateMany 更新多个文档
// 修改字段的值($set)
// 字段增加值 inc($inc)
// 从数组中增加一个元素 push($push)
// 从数组中删除一个元素 pull($pull)
func (ms *MongoTransaction) UpdateMany(filter interface{}, update interface{}) (result *mongo.UpdateResult, err error) {
collection := ms.db.Database(ms.getDatabaseName()).Collection(ms.collectionName)
result, err = collection.UpdateMany(ms.Session, filter, update)
return
}
// Find 查询
func (ms *MongoTransaction) Find(filter interface{}) (*mongo.Cursor, error) {
collection := ms.db.Database(ms.getDatabaseName()).Collection(ms.collectionName)
return collection.Find(ms.Session, filter)
}
// FindOne 查询单个文档
func (ms *MongoTransaction) FindOne(filter interface{}) *mongo.SingleResult {
collection := ms.db.Database(ms.getDatabaseName()).Collection(ms.collectionName)
return collection.FindOne(ms.Session, filter)
}
// FindMany 查询多个文档
func (ms *MongoTransaction) FindMany(filter interface{}) (*mongo.Cursor, error) {
collection := ms.db.Database(ms.getDatabaseName()).Collection(ms.collectionName)
return collection.Find(ms.Session, filter)
}
// FindManyByFilters 多条件查询
func (ms *MongoTransaction) FindManyByFilters(filter interface{}) (result *mongo.Cursor, err error) {
collection, err := ms.db.Database(ms.getDatabaseName()).Collection(ms.collectionName).Clone()
result, err = collection.Find(ms.Session, bson.M{"$and": filter})
return result, err
}
// FindManyByFiltersSort 多条件查询支持排序
func (ms *MongoTransaction) FindManyByFiltersSort(filter interface{}, Sort interface{}) (result *mongo.Cursor, err error) {
collection, err := ms.db.Database(ms.getDatabaseName()).Collection(ms.collectionName).Clone()
findOptions := options.Find()
findOptions.SetSort(Sort)
result, err = collection.Find(ms.Session, filter, findOptions)
return result, err
}
// FindCollection 查询集合文档
func (ms *MongoTransaction) FindCollection(Limit int64) (result *mongo.Cursor, err error) {
collection := ms.db.Database(ms.getDatabaseName()).Collection(ms.collectionName)
findOptions := options.Find()
findOptions.SetLimit(Limit)
result, err = collection.Find(ms.Session, bson.D{{}}, findOptions)
return result, err
}
// FindCollectionSort 查询集合文档支持排序
func (ms *MongoTransaction) FindCollectionSort(Sort interface{}, Limit int64) (result *mongo.Cursor, err error) {
collection := ms.db.Database(ms.getDatabaseName()).Collection(ms.collectionName)
findOptions := options.Find()
findOptions.SetSort(Sort)
findOptions.SetLimit(Limit)
result, err = collection.Find(ms.Session, bson.D{{}}, findOptions)
return result, err
}
// FindManyCollectionSort 查询集合文档支持排序支持条件
func (ms *MongoTransaction) FindManyCollectionSort(filter interface{}, Sort interface{}) (result *mongo.Cursor, err error) {
collection := ms.db.Database(ms.getDatabaseName()).Collection(ms.collectionName)
findOptions := options.Find()
findOptions.SetSort(Sort)
result, err = collection.Find(ms.Session, filter, findOptions)
return result, err
}
// CollectionCount 查询集合里有多少数据
func (ms *MongoTransaction) CollectionCount(ctx context.Context) (name string, size int64) {
collection := ms.db.Database(ms.getDatabaseName()).Collection(ms.collectionName)
name = collection.Name()
size, _ = collection.EstimatedDocumentCount(ctx)
return name, size
}
// CollectionDocuments 按选项查询集合
// Skip 跳过
// Limit 读取数量
// sort 1 -1 . 1 为升序 -1 为降序
func (ms *MongoTransaction) CollectionDocuments(Skip, Limit int64, sort int, key string, value interface{}) (result *mongo.Cursor, err error) {
collection := ms.db.Database(ms.getDatabaseName()).Collection(ms.collectionName)
SORT := bson.D{{"_id", sort}}
filter := bson.D{{key, value}}
findOptions := options.Find().SetSort(SORT).SetLimit(Limit).SetSkip(Skip)
result, err = collection.Find(ms.Session, filter, findOptions)
return result, err
}
// AggregateByFiltersSort 统计分析
func (ms *MongoTransaction) AggregateByFiltersSort(pipeline interface{}) (result *mongo.Cursor, err error) {
collection := ms.db.Database(ms.getDatabaseName()).Collection(ms.collectionName)
result, err = collection.Aggregate(ms.Session, pipeline)
return result, err
}
// CountDocumentsByFilters 统计数量
func (ms *MongoTransaction) CountDocumentsByFilters(filter interface{}) (count int64, err error) {
collection := ms.db.Database(ms.getDatabaseName()).Collection(ms.collectionName)
count, err = collection.CountDocuments(ms.Session, filter)
return count, err
}

@ -1,11 +0,0 @@
package dorm
// 获取库名
func (ms *MongoTransaction) getDatabaseName() string {
return ms.databaseName
}
// 获取表名
func (ms *MongoTransaction) getCollectionName() string {
return ms.collectionName
}

@ -1,28 +0,0 @@
package dorm
import "reflect"
// Database 设置库名
func (ms *MongoTransaction) Database(databaseName string) *MongoTransaction {
ms.databaseName = databaseName
return ms
}
// Collection 设置表名
func (ms *MongoTransaction) Collection(collectionName string) *MongoTransaction {
ms.collectionName = collectionName
return ms
}
// Model 传入模型自动获取库名和表名
func (ms *MongoTransaction) Model(value interface{}) *MongoTransaction {
// https://studygolang.com/articles/896
val := reflect.ValueOf(value)
if methodValue := val.MethodByName("Database"); methodValue.IsValid() {
ms.databaseName = methodValue.Call(nil)[0].String()
}
if methodValue := val.MethodByName("TableName"); methodValue.IsValid() {
ms.collectionName = methodValue.Call(nil)[0].String()
}
return ms
}

@ -0,0 +1 @@
package dorm

@ -0,0 +1 @@
package dorm

@ -0,0 +1 @@
package dorm

@ -8,21 +8,25 @@ import (
"time"
)
type ConfigRedisClient struct {
Addr string // 地址
Password string // 密码
DB int // 数据库
PoolSize int // 连接池大小
// RedisClientFun *RedisClient 驱动
type RedisClientFun func() *RedisClient
type RedisClientConfig struct {
Addr string // 地址
Password string // 密码
DB int // 数据库
PoolSize int // 连接池大小
ReadTimeout time.Duration // 读取超时
}
// RedisClient
// https://redis.uptrace.dev/
type RedisClient struct {
Db *redis.Client // 驱动
config *ConfigRedisClient // 配置
config *RedisClientConfig // 配置
}
func NewRedisClient(config *ConfigRedisClient) (*RedisClient, error) {
func NewRedisClient(config *RedisClientConfig) (*RedisClient, error) {
c := &RedisClient{}
c.config = config
@ -31,10 +35,11 @@ func NewRedisClient(config *ConfigRedisClient) (*RedisClient, error) {
}
c.Db = redis.NewClient(&redis.Options{
Addr: c.config.Addr, // 地址
Password: c.config.Password, // 密码
DB: c.config.DB, // 数据库
PoolSize: c.config.PoolSize, // 连接池大小
Addr: c.config.Addr, // 地址
Password: c.config.Password, // 密码
DB: c.config.DB, // 数据库
PoolSize: c.config.PoolSize, // 连接池大小
ReadTimeout: c.config.ReadTimeout, // 读取超时
})
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)

@ -62,8 +62,21 @@ func (r *RedisClient) Del(ctx context.Context, keys ...string) *redis.IntCmd {
return r.Db.Del(ctx, keys...)
}
// Keys 按前缀获取所有 key
func (r *RedisClient) Keys(ctx context.Context, prefix string) *redis.SliceCmd {
// Keys 按前缀获取所有key名
func (r *RedisClient) Keys(ctx context.Context, prefix string) []string {
values, _ := r.Db.Keys(ctx, prefix).Result()
keys := make([]string, 0, len(values))
if len(values) <= 0 {
return keys
}
for _, value := range values {
keys = append(keys, value)
}
return keys
}
// KeysValue 按前缀获取所有key值
func (r *RedisClient) KeysValue(ctx context.Context, prefix string) *redis.SliceCmd {
values, _ := r.Db.Keys(ctx, prefix).Result()
if len(values) <= 0 {
return &redis.SliceCmd{}

@ -26,6 +26,6 @@ func (r *RedisClient) PubSubChannels(ctx context.Context, pattern string) *redis
}
// PubSubNumSub 查询指定的channel有多少个订阅者
func (r *RedisClient) PubSubNumSub(ctx context.Context, channels ...string) *redis.StringIntMapCmd {
func (r *RedisClient) PubSubNumSub(ctx context.Context, channels ...string) *redis.MapStringIntCmd {
return r.Db.PubSubNumSub(ctx, channels...)
}

@ -0,0 +1,8 @@
package dorm
import "errors"
var (
// RedisKeysNotFound keys没有数据
RedisKeysNotFound = errors.New("ERR wrong number of arguments for 'mget' command")
)

@ -6,21 +6,20 @@ import (
)
type HashOperation struct {
db *redis.Client
ctx context.Context
db *redis.Client
}
// NewHashOperation hash类型数据操作 https://www.tizi365.com/archives/296.html
func NewHashOperation(db *redis.Client, ctx context.Context) *HashOperation {
return &HashOperation{db: db, ctx: ctx}
func NewHashOperation(db *redis.Client) *HashOperation {
return &HashOperation{db: db}
}
// Set 根据key和field字段设置field字段的值
func (cl *HashOperation) Set(key string, value interface{}) *redis.IntCmd {
return cl.db.HSet(cl.ctx, key, value)
func (cl *HashOperation) Set(ctx context.Context, key string, value interface{}) *redis.IntCmd {
return cl.db.HSet(ctx, key, value)
}
// Get 根据key和field字段设置field字段的值
func (cl *HashOperation) Get(key, field string) *redis.StringCmd {
return cl.db.HGet(cl.ctx, key, field)
func (cl *HashOperation) Get(ctx context.Context, key, field string) *redis.StringCmd {
return cl.db.HGet(ctx, key, field)
}

@ -0,0 +1,73 @@
package dorm
import (
"context"
"errors"
"fmt"
"github.com/go-redis/redis/v9"
"time"
)
// RedisClientLock https://github.com/go-redis/redis
type RedisClientLock struct {
operation *RedisClient // 操作
}
// NewLock 实例化锁
func (r *RedisClient) NewLock() *RedisClientLock {
return &RedisClientLock{r}
}
// Lock 上锁
// key 锁名
// val 锁内容
// ttl 锁过期时间
func (rl *RedisClientLock) Lock(ctx context.Context, key string, val string, ttl time.Duration) (resp string, err error) {
if ttl <= 0 {
return resp, errors.New("长期请使用 LockForever 方法")
}
// 获取
get, err := rl.operation.Get(ctx, key).Result()
if errors.Is(err, redis.Nil) {
// 设置
err = rl.operation.Set(ctx, key, val, ttl).Err()
if err != nil {
return resp, errors.New(fmt.Sprintf("上锁失败:%s", err.Error()))
}
return val, nil
}
if get != "" {
return resp, errors.New("上锁失败,已存在")
}
return resp, errors.New(fmt.Sprintf("获取异常:%s", err.Error()))
}
// Unlock 解锁
// key 锁名
func (rl *RedisClientLock) Unlock(ctx context.Context, key string) error {
_, err := rl.operation.Del(ctx, key).Result()
if err != nil {
return errors.New(fmt.Sprintf("解锁失败:%s", err.Error()))
}
return err
}
// LockForever 永远上锁
// key 锁名
// val 锁内容
func (rl *RedisClientLock) LockForever(ctx context.Context, key string, val string) (resp string, err error) {
// 获取
get, err := rl.operation.Get(ctx, key).Result()
if errors.Is(err, redis.Nil) {
// 设置
err = rl.operation.Set(ctx, key, val, 0).Err()
if err != nil {
return resp, errors.New(fmt.Sprintf("上锁失败:%s", err.Error()))
}
return val, nil
}
if get != "" {
return resp, errors.New("上锁失败,已存在")
}
return resp, errors.New(fmt.Sprintf("获取异常:%s", err.Error()))
}

@ -1,6 +1,7 @@
package dorm
import (
"context"
"encoding/json"
"time"
)
@ -33,12 +34,12 @@ func (r *RedisClient) NewSimpleCache(operation *StringOperation, expire time.Dur
}
// SetCache 设置缓存
func (c *SimpleCache) SetCache(key string, value interface{}) {
c.Operation.Set(key, value, WithExpire(c.Expire)).Unwrap()
func (c *SimpleCache) SetCache(ctx context.Context, key string, value interface{}) {
c.Operation.Set(ctx, key, value, WithExpire(c.Expire)).Unwrap()
}
// GetCache 获取缓存
func (c *SimpleCache) GetCache(key string) (ret interface{}) {
func (c *SimpleCache) GetCache(ctx context.Context, key string) (ret interface{}) {
if c.Serializer == SerializerJson {
f := func() string {
obj := c.JsonGetter()
@ -48,14 +49,14 @@ func (c *SimpleCache) GetCache(key string) (ret interface{}) {
}
return string(b)
}
ret = c.Operation.Get(key).UnwrapOrElse(f)
c.SetCache(key, ret)
ret = c.Operation.Get(ctx, key).UnwrapOrElse(f)
c.SetCache(ctx, key, ret)
} else if c.Serializer == SerializerString {
f := func() string {
return c.DBGetter()
}
ret = c.Operation.Get(key).UnwrapOrElse(f)
c.SetCache(key, ret)
ret = c.Operation.Get(ctx, key).UnwrapOrElse(f)
c.SetCache(ctx, key, ret)
}
return
}

@ -1,7 +1,7 @@
package dorm
import (
"log"
"context"
"time"
)
@ -23,17 +23,16 @@ func (r *RedisClient) NewSimpleInterfaceCache(operation *SimpleOperation, expire
}
// SetCache 设置缓存
func (c *SimpleInterfaceCache) SetCache(key string, value interface{}) {
c.Operation.Set(key, value, WithExpire(c.Expire)).Unwrap()
func (c *SimpleInterfaceCache) SetCache(ctx context.Context, key string, value interface{}) {
c.Operation.Set(ctx, key, value, WithExpire(c.Expire)).Unwrap()
}
// GetCache 获取缓存
func (c *SimpleInterfaceCache) GetCache(key string) (ret interface{}) {
func (c *SimpleInterfaceCache) GetCache(ctx context.Context, key string) (ret interface{}) {
f := func() interface{} {
return c.DBGetter()
}
ret = c.Operation.Get(key).UnwrapOrElse(f)
c.SetCache(key, ret)
log.Println(ret)
ret = c.Operation.Get(ctx, key).UnwrapOrElse(f)
c.SetCache(ctx, key, ret)
return ret
}

@ -1,6 +1,7 @@
package dorm
import (
"context"
"encoding/json"
"time"
)
@ -23,12 +24,12 @@ func (r *RedisClient) NewSimpleJsonCache(operation *StringOperation, expire time
}
// SetCache 设置缓存
func (c *SimpleJsonCache) SetCache(key string, value interface{}) {
c.Operation.Set(key, value, WithExpire(c.Expire)).Unwrap()
func (c *SimpleJsonCache) SetCache(ctx context.Context, key string, value interface{}) {
c.Operation.Set(ctx, key, value, WithExpire(c.Expire)).Unwrap()
}
// GetCache 获取缓存
func (c *SimpleJsonCache) GetCache(key string) (ret interface{}) {
func (c *SimpleJsonCache) GetCache(ctx context.Context, key string) (ret interface{}) {
f := func() string {
obj := c.DBGetter()
b, err := json.Marshal(obj)
@ -37,7 +38,7 @@ func (c *SimpleJsonCache) GetCache(key string) (ret interface{}) {
}
return string(b)
}
ret = c.Operation.Get(key).UnwrapOrElse(f)
c.SetCache(key, ret)
ret = c.Operation.Get(ctx, key).UnwrapOrElse(f)
c.SetCache(ctx, key, ret)
return
}

@ -7,32 +7,28 @@ import (
)
type SimpleOperation struct {
db *redis.Client
ctx context.Context
db *redis.Client
}
func (r *RedisClient) NewSimpleOperation() *SimpleOperation {
return &SimpleOperation{
db: r.Db,
ctx: context.Background(),
}
return &SimpleOperation{db: r.Db}
}
// Set 设置
func (o *SimpleOperation) Set(key string, value interface{}, attrs ...*OperationAttr) *SimpleResult {
func (o *SimpleOperation) Set(ctx context.Context, key string, value interface{}, attrs ...*OperationAttr) *SimpleResult {
exp := OperationAttrs(attrs).Find(AttrExpr)
if exp == nil {
exp = time.Second * 0
}
return NewSimpleResult(o.db.Set(o.ctx, key, value, exp.(time.Duration)).Result())
return NewSimpleResult(o.db.Set(ctx, key, value, exp.(time.Duration)).Result())
}
// Get 获取单个
func (o *SimpleOperation) Get(key string) *SimpleResult {
return NewSimpleResult(o.db.Get(o.ctx, key).Result())
func (o *SimpleOperation) Get(ctx context.Context, key string) *SimpleResult {
return NewSimpleResult(o.db.Get(ctx, key).Result())
}
// Del 删除key操作支持批量删除
func (o *SimpleOperation) Del(keys ...string) *redis.IntCmd {
return o.db.Del(o.ctx, keys...)
func (o *SimpleOperation) Del(ctx context.Context, keys ...string) *redis.IntCmd {
return o.db.Del(ctx, keys...)
}

@ -1,6 +1,7 @@
package dorm
import (
"context"
"time"
)
@ -22,16 +23,16 @@ func (r *RedisClient) NewSimpleStringCache(operation *StringOperation, expire ti
}
// SetCache 设置缓存
func (c *SimpleStringCache) SetCache(key string, value string) {
c.Operation.Set(key, value, WithExpire(c.Expire)).Unwrap()
func (c *SimpleStringCache) SetCache(ctx context.Context, key string, value string) {
c.Operation.Set(ctx, key, value, WithExpire(c.Expire)).Unwrap()
}
// GetCache 获取缓存
func (c *SimpleStringCache) GetCache(key string) (ret string) {
func (c *SimpleStringCache) GetCache(ctx context.Context, key string) (ret string) {
f := func() string {
return c.DBGetter()
}
ret = c.Operation.Get(key).UnwrapOrElse(f)
c.SetCache(key, ret)
ret = c.Operation.Get(ctx, key).UnwrapOrElse(f)
c.SetCache(ctx, key, ret)
return
}

@ -7,37 +7,33 @@ import (
)
type StringOperation struct {
db *redis.Client
ctx context.Context
db *redis.Client
}
func (r *RedisClient) NewStringOperation() *StringOperation {
return &StringOperation{
db: r.Db,
ctx: context.Background(),
}
return &StringOperation{db: r.Db}
}
// Set 设置
func (o *StringOperation) Set(key string, value interface{}, attrs ...*OperationAttr) *StringResult {
func (o *StringOperation) Set(ctx context.Context, key string, value interface{}, attrs ...*OperationAttr) *StringResult {
exp := OperationAttrs(attrs).Find(AttrExpr)
if exp == nil {
exp = time.Second * 0
}
return NewStringResult(o.db.Set(o.ctx, key, value, exp.(time.Duration)).Result())
return NewStringResult(o.db.Set(ctx, key, value, exp.(time.Duration)).Result())
}
// Get 获取单个
func (o *StringOperation) Get(key string) *StringResult {
return NewStringResult(o.db.Get(o.ctx, key).Result())
func (o *StringOperation) Get(ctx context.Context, key string) *StringResult {
return NewStringResult(o.db.Get(ctx, key).Result())
}
// MGet 获取多个
func (o *StringOperation) MGet(keys ...string) *SliceResult {
return NewSliceResult(o.db.MGet(o.ctx, keys...).Result())
func (o *StringOperation) MGet(ctx context.Context, keys ...string) *SliceResult {
return NewSliceResult(o.db.MGet(ctx, keys...).Result())
}
// Del 删除key操作支持批量删除
func (o *StringOperation) Del(keys ...string) *redis.IntCmd {
return o.db.Del(o.ctx, keys...)
func (o *StringOperation) Del(ctx context.Context, keys ...string) *redis.IntCmd {
return o.db.Del(ctx, keys...)
}

@ -0,0 +1 @@
package dorm

@ -0,0 +1 @@
package dorm

@ -0,0 +1 @@
package dorm

@ -0,0 +1 @@
package dorm

@ -0,0 +1 @@
package dorm

@ -0,0 +1,76 @@
package dorm
// Bool 复制 bool 对象,并返回复制体
func Bool(b bool) bool {
return b
}
// Uint8 复制 int8 对象,并返回复制体
func Uint8(ui uint8) uint8 {
return ui
}
// Uint16 复制 uint16 对象,并返回复制体
func Uint16(ui uint16) uint16 {
return ui
}
// Uint32 复制 uint32 对象,并返回复制体
func Uint32(ui uint32) uint32 {
return ui
}
// Uint64 复制 uint64 对象,并返回复制体
func Uint64(ui uint64) uint64 {
return ui
}
// Int8 复制 int8 对象,并返回复制体
func Int8(i int8) int8 {
return i
}
// Int16 复制 int16 对象,并返回复制体
func Int16(i int16) int16 {
return i
}
// Int32 复制 int64 对象,并返回复制体
func Int32(i int32) int32 {
return i
}
// Int64 复制 int64 对象,并返回复制体
func Int64(i int64) int64 {
return i
}
// Float32 复制 float32 对象,并返回复制体
func Float32(f float32) float32 {
return f
}
// Float64 复制 float64 对象,并返回复制体
func Float64(f float64) float64 {
return f
}
// String 复制 string 对象,并返回复制体
func String(s string) string {
return s
}
// Int 复制 int 对象,并返回复制体
func Int(i int) int {
return i
}
// Uint 复制 uint 对象,并返回复制体
func Uint(ui uint) uint {
return ui
}
// Any 复制 any 对象,并返回复制体
func Any(a any) any {
return a
}

@ -6,7 +6,7 @@ import (
"strings"
)
// XmlDecodeNoError Xml解码,不报错
// XmlDecodeNoError xml字符串转结构体,不报错
func XmlDecodeNoError(b []byte) map[string]interface{} {
xtj := strings.NewReader(string(b))
jtx, _ := xml2json.Convert(xtj)
@ -14,3 +14,8 @@ func XmlDecodeNoError(b []byte) map[string]interface{} {
_ = json.Unmarshal(jtx.Bytes(), &data)
return data
}
// XmlEncodeNoError 结构体转json字符串不报错
func XmlEncodeNoError(data interface{}) string {
return JsonEncodeNoError(data)
}

@ -4,13 +4,13 @@ import (
"xorm.io/xorm"
)
type ConfigXormClient struct {
type XormClientConfigXorm struct {
Dns string // 地址
}
// XormClient
// https://xorm.io/
type XormClient struct {
Db *xorm.Engine // 驱动
config *ConfigXormClient // 配置
Db *xorm.Engine // 驱动
config *XormClientConfigXorm // 配置
}

@ -7,7 +7,7 @@ import (
"xorm.io/xorm"
)
func NewXormMysqlClient(config *ConfigXormClient) (*XormClient, error) {
func NewXormMysqlClient(config *XormClientConfigXorm) (*XormClient, error) {
var err error
c := &XormClient{config: config}

@ -7,7 +7,7 @@ import (
"xorm.io/xorm"
)
func NewXormPostgresClient(config *ConfigXormClient) (*XormClient, error) {
func NewXormPostgresClient(config *XormClientConfigXorm) (*XormClient, error) {
var err error
c := &XormClient{config: config}

Loading…
Cancel
Save