cosmo

package module
v1.2.6 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Jan 7, 2026 License: Apache-2.0 Imports: 18 Imported by: 5

README

Cosmo - MongoDB ORM 框架

Cosmo 是一个轻量级的 MongoDB ORM 框架,提供了简洁的 API 和强大的功能,帮助开发者更高效地与 MongoDB 数据库交互。

目录结构

cosmo/
├── clause/          # 查询条件构建模块
│   ├── build.go     # 查询条件构建逻辑
│   ├── filter.go    # 过滤器定义
│   ├── format.go    # 格式化工具
│   ├── funcs.go     # 函数工具
│   ├── query.go     # 查询条件定义
│   ├── query_test.go # 查询条件测试
│   └── where.go     # 条件构建
├── update/          # 更新操作构建模块
│   ├── build.go     # 更新操作构建逻辑
│   ├── selector.go  # 字段选择器
│   └── update.go    # 更新操作定义
├── utils/           # 工具函数模块
│   ├── const.go     # 常量定义
│   ├── utils.go     # 工具函数
│   └── utils_test.go # 工具函数测试
├── bulkWrite.go     # 批量写操作
├── cache.go         # 缓存功能
├── callbacks.go     # 回调函数
├── chainable.go     # 链式操作
├── client.go        # MongoDB 客户端
├── command.go       # 命令执行
├── config.go        # 配置管理
├── cosmo.go         # 框架核心
├── cosmo_test.go    # 框架测试
├── define.go        # 类型定义
├── errors.go        # 错误定义
├── finisher.go      # 操作完成器
├── go.mod           # Go 模块定义
├── go.sum           # Go 模块依赖
├── health.go        # 连接池健康检查
├── migrator.go      # 自动迁移
├── paging.go        # 分页功能
├── session.go       # 会话管理
└── statement.go     # 语句构建

核心功能

1. 连接池管理

Cosmo 提供了强大的连接池管理功能,包括:

  • 自动健康检查
  • 连接自动恢复
  • 指数退避重试
  • 监控指标收集
// 创建数据库实例
import "github.com/hwcer/cosmo"

db := cosmo.New()

// 启动数据库连接
if err := db.Start("test_db", "mongodb://localhost:27017"); err != nil {
    panic(err)
}

// 关闭数据库连接
if err := db.Close(); err != nil {
    panic(err)
}
2. 查询条件构建

使用 clause 包构建复杂的查询条件:

// 构建查询条件
q := clause.New()
q.Eq("name", "张三")
q.Gte("age", 18)
q.In("status", []string{"active", "pending"})

// 复杂条件
orClause := clause.New()
orClause.Lt("age", 18)
orClause.Gte("age", 65)
q.Match(clause.QueryOperationOR, orClause)
3. 更新操作构建

使用 update 包构建更新操作:

// 构建更新操作
u := update.New()
u.Set("name", "李四")
u.Inc("age", 1)
u.Unset("oldField")

// 批量更新
u.Save(map[string]any{
    "status": "active",
    "updatedAt": time.Now(),
})
4. 模型定义
// 定义模型
type User struct {
    ID        primitive.ObjectID `bson:"_id" json:"id"`
    Name      string             `bson:"name" json:"name"`
    Age       int                `bson:"age" json:"age"`
    Email     string             `bson:"email" json:"email"`
    Status    string             `bson:"status" json:"status"`
    CreatedAt time.Time          `bson:"created_at" json:"createdAt"`
    UpdatedAt time.Time          `bson:"updated_at" json:"updatedAt"`
}

// 预注册模型
config := &cosmo.Config{}
config.Register(&User{})
5. 数据库操作
重要说明
  1. 查询条件构建

    • 使用 db.Model(&Model{}) 方法指定要操作的模型
    • 推荐使用SQL风格字符串构建查询条件:Where("name = ? AND age > ?", "John", 18)
    • 支持主键值查询:Where("5f8d0d55b54764421b715620")
    • 支持字段名和值的简洁格式:Where("name", "John")
  2. 更新操作构建

    • 使用 db.Update() 方法更新单个文档
    • 使用 db.Updates() 方法更新多个文档
    • 推荐使用bson.M类型支持MongoDB原生操作符:Update(bson.M{"$set": bson.M{"status": "inactive"}})
    • 支持map类型自动转为$set操作:Update(map[string]any{"name": "李四"})
    • 支持update.Update类型实现复杂更新:Update(update.Set("name", "王五").Inc("age", 1))
创建数据
user := &User{
    Name:      "张三",
    Age:       25,
    Email:     "[email protected]",
    Status:    "active",
    CreatedAt: time.Now(),
    UpdatedAt: time.Now(),
}

if err := db.Create(user); err != nil {
    panic(err)
}
查询数据
// 查询单个文档
var user User
if err := db.First(&user, bson.M{"name": "张三"}); err != nil {
    panic(err)
}

// 查询多个文档
var users []User
if err := db.Model(&User{}).Where("status = ?", "active").Find(&users); err != nil {
    panic(err)
}

// 带分页的查询
var users []User
if err := db.Model(&User{}).Where("age >= ?", 18).Offset(0).Limit(10).Find(&users); err != nil {
    panic(err)
}
更新数据
// 更新单个文档(使用update.Update类型)
if err := db.Model(&User{}).Where("_id = ?", userID).Update(bson.M{"$set": bson.M{"status": "inactive"}}); err != nil {
    panic(err)
}

// 更新多个文档(使用批量更新)
if err := db.Model(&User{}).Where("age > ?", 65).Updates(bson.M{"status": "retired"}); err != nil {
    panic(err)
}

// 更新单个文档(直接使用map,自动转为$set操作)
if err := db.Model(&User{}).Where("_id = ?", userID).Update(bson.M{"name": "李四", "age": 26}); err != nil {
    panic(err)
}

// 使用Update结构体进行复杂更新
up := update.New()
up.Set("name", "王五")
up.Inc("age", 1)
up.Unset("oldField")
if err := db.Model(&User{}).Where("_id = ?", userID).Update(up); err != nil {
    panic(err)
}
删除数据
// 删除单个文档
if err := db.Model(&User{}).Where("_id = ?", userID).Delete(); err != nil {
    panic(err)
}

// 删除多个文档
if err := db.Model(&User{}).Where("status = ?", "inactive").Delete(); err != nil {
    panic(err)
}

// 根据结构体中的_id字段删除记录
if err := db.Delete(&User{Id: userID}); err != nil {
    panic(err)
}

// 删除多个记录(使用IN条件)
if err := db.Model(&User{}).Delete([]string{userID1, userID2, userID3}); err != nil {
    panic(err)
}
6. 批量操作
// 创建批量写入操作
users := []*User{
    {Name: "张三", Age: 25}, 
    {Name: "李四", Age: 30},
}

bulk := db.BulkWrite(&User{})
for _, user := range users {
    bulk.InsertOne(user)
}

// 执行批量操作
if err := bulk.Execute(); err != nil {
    panic(err)
}
7. 缓存功能

Cosmo 提供了内置的缓存功能,可以提高查询性能:

// 实现 CacheModel 接口
type User struct {
    // ... 字段定义
    UpdatedAt int64 `bson:"updated_at" json:"updatedAt"`
}

func (u *User) GetUpdate() int64 {
    return u.UpdatedAt
}

// 实现 CacheHandle 接口
type UserCacheHandle struct{}

func (h *UserCacheHandle) Reload(ts int64, cb cosmo.CacheSetter) error {
    // 从数据库加载数据
    var users []*User
    if err := db.Where(clause.Gt("updated_at", ts)).Find(&users); err != nil {
        return err
    }
    
    // 设置缓存
    for _, user := range users {
        cb(user.ID.Hex(), user)
    }
    
    return nil
}

// 使用缓存
handle := &UserCacheHandle{}
db.Cache(handle, 5*time.Minute)
8. 自动迁移
// 自动创建或更新索引
db := cosmo.New()
db.Config.Register(&User{})
db.Config.Register(&Order{})

err := db.AutoMigrator(&User{}, &Order{})
if err != nil {
    panic(err)
}
9. 事务支持
// 开始事务
tx := db.Begin()

// 执行操作
user := &User{Name: "张三"}
if err := tx.Create(user); err != nil {
    tx.Rollback()
    panic(err)
}

order := &Order{UserID: user.ID, Product: "Product A"}
if err := tx.Create(order); err != nil {
    tx.Rollback()
    panic(err)
}

// 提交事务
if err := tx.Commit(); err != nil {
    panic(err)
}
10. 连接池管理
// 自定义连接池配置
cosmo.PoolConfig.CheckInterval = 15 * time.Second
cosmo.PoolConfig.MaxRetries = 5
cosmo.PoolConfig.RetryDelay = 1 * time.Second

// 创建连接池管理器
pool := cosmo.NewPoolManager("mongodb://localhost:27017")
pool.Start()

// 检查连接健康状态
status := pool.CheckNow()
if status.IsHealthy {
    fmt.Println("连接健康")
} else {
    fmt.Printf("连接不健康: %v\n", status.Error)
}

配置

连接池配置
cosmo.PoolConfig = struct {
    CheckInterval            time.Duration // 健康检查间隔
    CheckTimeout             time.Duration // 检查超时时间
    MaxRetries               int           // 最大重试次数
    RetryDelay               time.Duration // 重试延迟
    RecoverTimeout           time.Duration // 恢复超时时间
    StabilizationDelay       time.Duration // 系统稳定延迟
    CloseDelay               time.Duration // 关闭旧客户端延迟
    CloseTimeout             time.Duration // 关闭旧客户端超时
    QuickCheckTimeout        time.Duration // 快速健康检查超时
    WaitHealthyCheckInterval time.Duration // 等待健康检查间隔
    WaitHealthyNeededCount   int           // 连续健康检查通过次数
    WarmupQueryCount         int           // 预热查询次数
    WarmupQueryInterval      time.Duration // 预热查询间隔
    ExecuteWaitTimeout       time.Duration // 执行等待超时
    FailureThreshold         int           // 连续失败阈值
    BackoffBase              int           // 指数退避基数
    AttemptOffset            int           // 尝试次数偏移量
    MaxBackoffDelay          time.Duration // 最大退避延迟
    RecoveryPingTimeout      time.Duration // 恢复过程中的Ping超时
    RecoveryQueryTimeout     time.Duration // 恢复过程中的查询超时
}{}

安装

go get github.com/hwcer/cosmo

快速开始

package main

import (
    "fmt"
    "time"

    "github.com/hwcer/cosmo"
    "go.mongodb.org/mongo-driver/bson/primitive"
)

// 定义模型
type User struct {
    ID        primitive.ObjectID `bson:"_id" json:"id"`
    Name      string             `bson:"name" json:"name"`
    Age       int                `bson:"age" json:"age"`
    Email     string             `bson:"email" json:"email"`
    Status    string             `bson:"status" json:"status"`
    CreatedAt time.Time          `bson:"created_at" json:"createdAt"`
    UpdatedAt time.Time          `bson:"updated_at" json:"updatedAt"`
}

func main() {
    // 创建数据库实例
    db := cosmo.New()
    
    // 连接到数据库
    if err := db.Start("test_db", "mongodb://localhost:27017"); err != nil {
        panic(err)
    }
    defer db.Close()
    
    // 预注册模型
    db.Config.Register(&User{})
    
    // 自动迁移
    if err := db.AutoMigrator(&User{}); err != nil {
        panic(err)
    }
    
    // 创建数据
    user := &User{
        Name:      "张三",
        Age:       25,
        Email:     "[email protected]",
        Status:    "active",
        CreatedAt: time.Now(),
        UpdatedAt: time.Now(),
    }
    
    if err := db.Create(user); err != nil {
        panic(err)
    }
    
    fmt.Printf("创建用户成功: %+v\n", user)
    
    // 查询数据
    var foundUser User
    if err := db.First(&foundUser, bson.M{"_id": user.ID}); err != nil {
        panic(err)
    }
    
    fmt.Printf("查询用户成功: %+v\n", foundUser)
    
    // 更新数据
    if err := db.Model(&User{}).Where(bson.M{"_id": user.ID}).Update(bson.M{"name": "李四"}); err != nil {
        panic(err)
    }
    
    // 删除数据
    if err := db.Delete(&User{Id: user.ID}); err != nil {
        panic(err)
    }
    
    fmt.Println("操作完成")
}

API 参考

DB 结构体方法
方法名 描述
New() 创建新的数据库实例
Start(dbname string, address interface{}) error 启动数据库连接
Close() error 关闭数据库连接
Session(session *Session) *DB 创建新的数据库会话
Database(dbname string) *DB 切换数据库
Collection(model any) (tx *DB, coll *mongo.Collection) 获取集合
BulkWrite(model any, filter ...BulkWriteUpdateFilter) *BulkWrite 创建批量写操作
WithContext(ctx context.Context) *DB 设置上下文
Create(value interface{}) error 创建文档
First(dest interface{}, conds ...interface{}) error 查询单个文档
Find(dest interface{}, conds ...interface{}) error 查询多个文档
Update(update interface{}, conds ...interface{}) error 更新文档
Delete(conds ...interface{}) error 删除文档
AutoMigrator(dst ...interface{}) error 自动迁移
Begin() *DB 开始事务
Commit() error 提交事务
Rollback() error 回滚事务
PoolManager 方法
方法名 描述
NewPoolManager(uri string) *PoolManager 创建连接池管理器
Start() 启动连接池
CheckNow() *HealthStatus 立即执行健康检查
IsHealthy() bool 检查连接是否健康
WaitForHealthy(ctx context.Context, timeout time.Duration) bool 等待连接恢复健康
PrepareForBulkOperation(ctx context.Context) error 为批量操作做准备
Execute(ctx context.Context, operation func(*mongo.Client) error) error 安全执行数据库操作
clause.Query 方法
方法名 描述
New() *Query 创建查询条件
Eq(k string, v interface{}) 等于条件
Gt(k string, v interface{}) 大于条件
Gte(k string, v interface{}) 大于等于条件
Lt(k string, v interface{}) 小于条件
Lte(k string, v interface{}) 小于等于条件
Ne(k string, v interface{}) 不等于条件
In(k string, v interface{}) 包含条件
Nin(k string, v interface{}) 不包含条件
OR(v ...*Node) OR 条件
AND(v ...*Node) AND 条件
NOT(v ...*Node) NOT 条件
NOR(v ...*Node) NOR 条件
update.Update 方法
方法名 描述
New() Update 创建更新操作
NewFromMap(v map[string]any) Update 从映射创建更新操作
Set(k string, v interface{}) 设置字段
Inc(k string, v interface{}) 递增字段
Unset(k string) 删除字段
SetOnInert(k string, v interface{}) 插入时设置字段
Min(k string, v interface{}) 最小值字段
Max(k string, v interface{}) 最大值字段
Pop(k string, v interface{}) 弹出数组元素
Pull(k string, v interface{}) 移除数组元素
Push(k string, v interface{}) 添加数组元素
MSet(vs map[string]any) 批量设置字段

最佳实践

  1. 使用连接池管理:始终使用 PoolManager 来管理数据库连接,而不是直接创建 mongo.Client

  2. 预注册模型:在应用启动时预注册所有模型,以便自动创建索引。

  3. 使用事务:对于需要原子性的操作,使用事务来确保数据一致性。

  4. 合理使用缓存:对于频繁访问的数据,使用缓存来提高性能。

  5. 使用查询条件构建器:使用 clause 包来构建复杂的查询条件,而不是直接使用 bson.M

  6. 使用更新操作构建器:使用 update 包来构建更新操作,而不是直接使用 bson.M

  7. 定期检查连接健康状态:使用 PoolManager 的健康检查功能来确保连接池的可用性。

  8. 处理错误:始终检查并处理数据库操作的错误。

贡献

欢迎提交 Issue 和 Pull Request。

许可证

MIT License

Documentation

Overview

Package cosmo 是一个轻量级的 MongoDB ORM 框架,提供了类似 GORM 的接口,支持模型映射、查询构建和批量操作。 它包含连接池管理、事务支持、自动迁移、缓存机制等功能,适用于构建高性能的 MongoDB 应用程序。

Index

Constants

View Source
const DefaultPageSize = 1000
View Source
const PageUpdateFieldName = "update" //UPDATE

Variables

View Source
var (
	ErrMissingWhereClause = errors.New("WHERE conditions required")

	ErrInvalidValue = errors.New("invalid value, should be pointer to struct or slice")

	ErrSelectOnOmitsExist = errors.New("select on omits exist")

	ErrOmitOnSelectsExist = errors.New("omit on selects exist")
)

Functions

func IsBusinessError added in v1.2.3

func IsBusinessError(err error) bool

检查是不是无法恢复的业务错误

1、插入时主键重复

2、数据类型错误

func IsNetworkError added in v1.2.3

func IsNetworkError(err error) bool

检查是不是MONGO网络错误

func UpdateOne added in v0.0.3

func UpdateOne(tx *DB, coll *mongo.Collection, filter clause.Filter, data update.Update, upsert bool) (err error)

Types

type BulkWrite

type BulkWrite struct {
	// contains filtered or unexported fields
}

func (*BulkWrite) Delete

func (this *BulkWrite) Delete(where ...interface{})

func (*BulkWrite) Insert

func (this *BulkWrite) Insert(documents ...interface{})

func (*BulkWrite) Options added in v0.0.3

func (this *BulkWrite) Options(opts ...*options.BulkWriteOptions)

func (*BulkWrite) Result added in v0.0.3

func (this *BulkWrite) Result() *mongo.BulkWriteResult

func (*BulkWrite) Save

func (this *BulkWrite) Save(data any, where ...any)

func (*BulkWrite) SetUpdateFilter added in v1.1.0

func (this *BulkWrite) SetUpdateFilter(filter BulkWriteUpdateFilter)

func (*BulkWrite) Size added in v1.1.0

func (this *BulkWrite) Size() int

Size 等待提交的事务数量

func (*BulkWrite) String added in v1.2.3

func (this *BulkWrite) String() string

func (*BulkWrite) Submit added in v1.1.0

func (this *BulkWrite) Submit() (err error)

Submit 提交修改

func (*BulkWrite) Update

func (this *BulkWrite) Update(data any, where ...any)

Update 更新 data map[string]any update.Update bson.M

type BulkWriteUpdateFilter added in v1.1.0

type BulkWriteUpdateFilter func(up update.Update)

type Cache added in v1.1.0

type Cache struct {
	// contains filtered or unexported fields
}

func NewCache added in v1.1.0

func NewCache(handle CacheHandle) *Cache

NewCache 创建一个新的缓存实例 handle: 缓存句柄,用于加载和刷新缓存数据

func (*Cache) Cursor added in v1.1.0

func (this *Cache) Cursor(update int64, filter CacheFilter) []any

func (*Cache) Delete added in v1.1.0

func (this *Cache) Delete(id string)

func (*Cache) Get added in v1.1.0

func (this *Cache) Get(id string) any

func (*Cache) Has added in v1.1.0

func (this *Cache) Has(id string) (ok bool)

func (*Cache) Len added in v1.1.0

func (this *Cache) Len() int

func (*Cache) Listener added in v1.1.0

func (this *Cache) Listener(t CacheEventType, id string, update int64)

Listener 监听数据库变化 id 变更数据ID update 变化时间

func (*Cache) Lock added in v1.1.0

func (this *Cache) Lock(f func() error) error

func (*Cache) Page added in v1.1.0

func (this *Cache) Page(page *Paging, filter CacheFilter) (err error)

func (*Cache) Range added in v1.1.0

func (this *Cache) Range(f func(any) bool)

func (*Cache) Reload added in v1.1.0

func (this *Cache) Reload(ts int64, handle ...CacheHandle) error

type CacheData added in v1.1.0

type CacheData struct {
	// contains filtered or unexported fields
}

CacheData 缓存数据结构体,用于存储缓存的模型数据

func NewCacheData added in v1.1.0

func NewCacheData() *CacheData

NewCacheData 创建一个新的缓存数据实例

func (*CacheData) Copy added in v1.1.0

func (this *CacheData) Copy() *CacheData

func (*CacheData) Delete added in v1.1.0

func (this *CacheData) Delete(id any) *CacheData

type CacheEventType added in v1.1.0

type CacheEventType int8

CacheEventType 缓存事件类型

const (
	CacheEventTypeCreate CacheEventType = 0 // 创建事件
	CacheEventTypeUpdate CacheEventType = 1 // 更新事件
	CacheEventTypeDelete CacheEventType = 2 // 删除事件
)

type CacheFilter added in v1.1.0

type CacheFilter func(v CacheModel) any

CacheFilter 缓存过滤函数类型,用于过滤缓存数据,返回nil表示过滤失败

type CacheHandle added in v1.1.0

type CacheHandle interface {
	// Reload 重新加载缓存数据
	// ts: 时间戳,用于加载指定时间之后更新的数据
	// cb: 缓存设置函数,用于将加载的数据添加到缓存中
	Reload(ts int64, cb CacheSetter) error
}

CacheHandle 缓存句柄接口,用于实现缓存的加载和刷新

type CacheModel added in v1.1.0

type CacheModel interface {
	GetUpdate() int64 // 获取模型的更新时间戳
}

CacheModel 缓存模型接口,用于支持缓存功能的模型需要实现此接口

type CacheSetter added in v1.1.0

type CacheSetter func(k any, v CacheModel)

CacheSetter 缓存设置函数类型,用于将模型添加到缓存中

type Config

type Config struct {
	// contains filtered or unexported fields
}

Config GORM config

func (*Config) Register

func (c *Config) Register(model interface{})

Register 预注册的MODEL在启动时会自动创建索引

type Cursor added in v1.2.1

type Cursor interface {
	Decode(val interface{}) error
}

type DB

type DB struct {
	*Config // 数据库配置

	Error        error // 错误信息
	RowsAffected int64 // 操作影响的条数
	// contains filtered or unexported fields
}

DB 是 Cosmo ORM 框架的核心结构体,提供了数据库操作的入口点。 它封装了数据库连接、事务管理、模型映射等功能,支持链式操作。

func New

func New(configs ...*Config) (db *DB)

New 创建一个新的 Cosmo DB 实例。 参数 configs 是可选的数据库配置,可以设置连接池、日志、插件等选项。 如果不提供配置,将使用默认配置。 返回值是 DB 实例,作为所有数据库操作的入口点。

使用示例:

db := cosmo.New(&cosmo.Config{
    PoolConfig: &cosmo.PoolConfig{
        Address: "mongodb://localhost:27017",
        CheckInterval: 30 * time.Second,
    },
})

func (*DB) AutoMigrator

func (db *DB) AutoMigrator(dst ...interface{}) error

AutoMigrator 自动迁移功能,根据模型定义自动创建或更新索引 dst: 要迁移的模型对象,可以传入多个模型 返回值: 迁移过程中发生的错误

func (*DB) BulkWrite

func (db *DB) BulkWrite(model any, filter ...BulkWriteUpdateFilter) *BulkWrite

BulkWrite 创建批量写入操作实例。 参数 model 是要操作的模型类型。 参数 filter 是可选的批量更新过滤器。 返回值是 BulkWrite 实例,用于构建和执行批量写入操作。

使用示例:

bw := db.BulkWrite(&User{}, cosmo.BulkWriteUpdateFilter{
    UpdateBy: "_id",
})

bw.InsertMany(users) bw.UpdateMany(updates) result, err := bw.Execute()

func (*DB) Close

func (db *DB) Close() error

func (*DB) Collection

func (db *DB) Collection(model any) (tx *DB, coll *mongo.Collection)

Collection 获取指定模型或集合名称对应的 MongoDB 集合。 参数 model 可以是结构体类型或集合名称字符串。 返回值 tx 是新的 DB 实例,coll 是 MongoDB 集合对象。

使用示例: tx, coll := db.Collection(&User{}) 或 tx, coll := db.Collection("users")

func (*DB) Count

func (db *DB) Count(count interface{}, conds ...interface{}) (tx *DB)

Count 统计文档数,count 必须为一个指向数字的指针 *int *int32 *int64

func (*DB) Create

func (db *DB) Create(value interface{}) (tx *DB)

Create insert the value into dbname

func (*DB) Database

func (db *DB) Database(dbname string) *DB

Database 创建一个指向指定数据库的新 DB 实例。 参数 dbname 是要使用的新数据库名称。 返回值是新的 DB 实例,用于操作指定的数据库。

使用示例: newDB := db.Database("newdatabase")

func (*DB) Delete

func (db *DB) Delete(conds ...interface{}) (tx *DB)

Delete 删除记录 db.model(&User).delete(1) 匹配 _id=1 db.model(&User).delete([]int{1,2,3}) 匹配 _id IN (1,2,3) db.model(&User).delete("name = ?","myname") 匹配 name=myname db.delete(&User{Id:1}) 根据结构体中的_id字段删除记录

func (*DB) Errorf

func (db *DB) Errorf(format interface{}, args ...interface{}) *DB

Errorf 为数据库实例设置格式化错误信息。 参数 format 是错误格式化字符串或错误对象。 参数 args 是格式化参数。 返回值是当前 DB 实例,方便链式调用。

使用示例: db.Errorf("操作失败: %v", err)

func (*DB) Find

func (db *DB) Find(val any, where ...any) (tx *DB)

Find 仅仅满足 GORM习惯

func (*DB) First added in v1.1.0

func (db *DB) First(val any, where ...any) (tx *DB)

First 获取第一条记录(主键升序)

func (*DB) Inc added in v1.1.0

func (db *DB) Inc(key string, val int) (tx *DB)

func (*DB) IncludeZeroValue added in v1.1.0

func (db *DB) IncludeZeroValue() (tx *DB)

IncludeZeroValue 设置Update Updates 时包含零值 使用 Save 时自动包含零值

func (*DB) IsHealthy added in v1.2.3

func (db *DB) IsHealthy() bool

func (*DB) Last added in v1.1.0

func (db *DB) Last(val any, where ...any) (tx *DB)

Last 获取最后一条记录(主键降序)

func (*DB) Limit

func (db *DB) Limit(limit int) (tx *DB)

func (*DB) Model

func (db *DB) Model(value any, modify ...bool) (tx *DB)

Model specify the model you would like to run db operations

// update all users's name to `hello`
db.model(&User{}).Update("name", "hello")
// if user's primary key is non-blank, will use it as condition, then will only update the user's name to `hello`
db.model(&user).Update("name", "hello")

func (*DB) Multiple

func (db *DB) Multiple() (tx *DB)

Multiple 强制批量更新

func (*DB) ObjectID added in v0.0.3

func (db *DB) ObjectID() primitive.ObjectID

func (*DB) Omit

func (db *DB) Omit(columns ...string) (tx *DB)

Omit specify fields that you want to ignore when creating, updating and querying

func (*DB) Order

func (db *DB) Order(key string, value int) (tx *DB)

Order specify order when retrieve records from dbname Order 排序方式 1 和 -1 来指定排序的方式,其中 1 为升序排列,而 -1 是用于降序排列。

func (*DB) Page

func (db *DB) Page(paging *Paging, where ...any) (tx *DB)

Page 分页查询

func (*DB) PageUpdateField added in v1.2.6

func (db *DB) PageUpdateField(field string) (tx *DB)

func (*DB) Query added in v1.1.0

func (db *DB) Query(val any, where ...any) (tx *DB)

Query get records that match given conditions value must be a pointer to a slice

func (*DB) Range added in v1.2.1

func (db *DB) Range(f func(Cursor) bool) (tx *DB)

Range 遍历

func (*DB) Save added in v1.1.0

func (db *DB) Save(values any, conds ...any) (tx *DB)

func (*DB) Select

func (db *DB) Select(columns ...string) (tx *DB)

Select specify fields that you want when querying, creating, updating

func (*DB) Session

func (db *DB) Session(session *Session) *DB

Session 创建一个新的数据库会话。 参数 session 包含会话配置,如数据库名称、上下文等。 返回值是新的 DB 实例,用于执行会话相关的操作。

使用示例:

sessionDB := db.Session(&cosmo.Session{
    DBName: "newdatabase",
    Context: ctx,
})

func (*DB) Set

func (db *DB) Set(key string, val any) (tx *DB)

func (*DB) SetColumn

func (db *DB) SetColumn(data map[string]interface{}) (err error)

SetColumn set column's value to model

stmt.SetColumn("Name", "jinzhu") // Hooks Method

func (*DB) Start

func (db *DB) Start(dbname string, address interface{}) (err error)

Start 初始化数据库连接并启动连接池。 参数 dbname 是要使用的数据库名称。 参数 address 可以是 MongoDB 连接字符串或 *PoolManager 实例。 返回值是可能的错误信息。

使用示例: err := db.Start("mydatabase", "mongodb://localhost:27017") 或 pool := cosmo.NewPoolManager("mongodb://localhost:27017") err := db.Start("mydatabase", pool)

func (*DB) Table

func (db *DB) Table(name string) (tx *DB)

func (*DB) Take added in v1.1.0

func (db *DB) Take(val any, where ...any) (tx *DB)

Take 获取一条记录,没有指定排序字段

func (*DB) Update

func (db *DB) Update(values any, conds ...any) (tx *DB)

func (*DB) UpdateAndModify added in v1.2.2

func (db *DB) UpdateAndModify() (tx *DB)

UpdateAndModify 更新单行数据(update,save)时同时更新model

func (*DB) Updates added in v1.1.0

func (db *DB) Updates(values any, conds ...any) (tx *DB)

Updates 更新多列 Updates 方法支持 struct 和 map[string]interface{} 参数。当使用 struct 更新时,默认情况下只会更新非零值的字段 如果您想要在更新时选择、忽略某些字段,您可以使用 Select、Omit 自动关闭 updateAndModify

func (*DB) Upsert added in v0.0.3

func (db *DB) Upsert() (tx *DB)

Upsert update时如果不存在自动insert update 存在 $setOnInsert 时同样自动设置Upsert

func (*DB) Where

func (db *DB) Where(query interface{}, args ...interface{}) (tx *DB)

Where 查询条件 参考 query包

func (*DB) WithContext

func (db *DB) WithContext(ctx context.Context) *DB

WithContext 为当前数据库实例设置新的上下文。 参数 ctx 是要设置的上下文对象。 返回值是新的 DB 实例,包含更新后的上下文。

使用示例: ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) defer cancel() dbWithCtx := db.WithContext(ctx)

type ModelBulkWriteFilter added in v1.1.0

type ModelBulkWriteFilter interface {
	BulkWriteFilter(up update.Update)
}

type Paging

type Paging struct {
	//order  []bson.E    //排序
	Rows   interface{} `json:"rows"`
	Page   int         `json:"page"`             //当前页
	Size   int         `json:"size"`             //每页大小
	Total  int         `json:"total"`            //总页码数
	Record int         `json:"record"`           //总记录数
	Update int64       `json:"update,omitempty"` //最后更新时间
}

Paging 分页

func (*Paging) Init added in v0.0.5

func (this *Paging) Init(size int)

func (*Paging) Offset

func (this *Paging) Offset() int

func (*Paging) Options

func (this *Paging) Options() *options.FindOptions

Options 转换成FindOptions

func (*Paging) Range added in v1.1.0

func (this *Paging) Range(page int, handle func(int))

Range 遍历第N页的索引下标

func (*Paging) Result added in v0.0.5

func (this *Paging) Result(r int)

type Session

type Session struct {
	DBName string
	//DryRun                   bool
	//PrepareStmt              bool
	//NewDB     bool
	//SkipHooks bool
	//SkipDefaultTransaction   bool
	//DisableNestedTransaction bool
	//AllowGlobalUpdate        bool
	//FullSaveAssociations     bool
	//QueryFields              bool
	Context context.Context
}

Session session config when create session with Session() method

type Statement

type Statement struct {
	*DB // 数据库连接实例

	Clause  *clause.Query   // 查询条件构建器
	Paging  *Paging         // 分页信息
	Context context.Context // 操作上下文
	// contains filtered or unexported fields
}

Statement 表示一个MongoDB数据库操作语句 用于构建和执行查询、插入、更新、删除等操作 包含操作所需的所有信息,如查询条件、排序、分页、更新字段等

func NewStatement

func NewStatement(db *DB) *Statement

NewStatement 创建一个新的Statement实例 参数 db: 数据库连接实例 返回值: 初始化的Statement实例

func (*Statement) DBName

func (stmt *Statement) DBName(name string) string

DBName 将结构体字段名转换为数据库字段名 参数 name: 结构体字段名 返回值: 对应的数据库字段名

func (*Statement) GetIncludeZeroValue added in v1.2.2

func (stmt *Statement) GetIncludeZeroValue() bool

GetIncludeZeroValue 获取是否包含零值的设置 返回值: 更新时是否包含零值字段

func (*Statement) GetReflectValue added in v1.2.2

func (stmt *Statement) GetReflectValue() reflect.Value

GetReflectValue 获取模型的反射值 返回值: 模型对象的反射值

func (*Statement) GetSchema added in v1.2.2

func (stmt *Statement) GetSchema() *schema.Schema

GetSchema 获取模型的schema信息 返回值: 模型的元数据信息

func (*Statement) GetSelector added in v1.2.2

func (stmt *Statement) GetSelector() *update.Selector

GetSelector 获取更新字段选择器 返回值: 更新时的字段选择器

func (*Statement) GetValue added in v1.2.2

func (stmt *Statement) GetValue() any

GetValue 获取结果存储对象 返回值: 用于存储查询结果或写入数据的对象

func (*Statement) Order

func (stmt *Statement) Order() (order bson.D)

Order 生成MongoDB排序条件 将内部的排序映射转换为MongoDB的bson.D格式 返回值: 排序条件

func (*Statement) Parse

func (stmt *Statement) Parse() (tx *DB)

Parse 解析模型并初始化Statement 处理模型的反射信息、schema映射和表名 返回值: 数据库实例,包含可能的错误信息

Directories

Path Synopsis
Package clause 提供了 MongoDB 查询条件构建的功能,支持各种查询操作符和复杂条件组合。
Package clause 提供了 MongoDB 查询条件构建的功能,支持各种查询操作符和复杂条件组合。
update 包提供MongoDB更新操作的相关功能,包括更新条件构建和字段选择
update 包提供MongoDB更新操作的相关功能,包括更新条件构建和字段选择

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL