db

package
v1.0.2 Latest Latest
Warning

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

Go to latest
Published: Aug 12, 2026 License: Apache-2.0 Imports: 11 Imported by: 0

Documentation

Overview

Package db 提供 MongoDB 连接的 wire provider(公共基础设施)。 各服务在 wire 装配时直接复用 MongoSet,无需重复实现连接逻辑。

Index

Constants

This section is empty.

Variables

MongoSet 公共 provider 集合,各服务 wire 装配时引入。

Functions

func EnsureIndexesFromFile

func EnsureIndexesFromFile(db *mongo.Database, filePath string) error

EnsureIndexesFromFile 按 JSON 索引清单同步集合索引:

  • 创建清单中缺失的索引;
  • 删除集合中不在清单里的索引(清单是唯一事实来源),但保留系统索引 _id_。

清单格式(数组):

[
  { "collection": "Directory", "indexes": [
    { "name": "idx_x", "keys": [{"f":"tenant_id","v":1}, {"f":"domain","v":1}], "unique": true }
  ]}
]

func NewClient

func NewClient() (*mongo.Client, error)

NewClient wire provider:连接 MongoDB(读 gobase 配置),返回连接好的 client。

func NewDatabase

func NewDatabase(client *mongo.Client) (*mongo.Database, error)

NewDatabase wire provider:根据 client 返回库实例。

func WithTransaction

func WithTransaction(client *mongo.Client, ctx context.Context, fn func(ctx context.Context) error) error

WithTransaction 在 MongoDB 事务中执行 fn。

用法:跨多个集合/仓储的批量写(如"删除目录域连带删用户/组织")需要 要么全成功要么全回滚时,用此函数包裹;fn 收到的 ctx 为事务会话上下文, 各仓储方法传入它即可自动进入同一事务(前提是各仓储复用同一个 client)。

注意:多文档事务要求 MongoDB 副本集(replica set),standalone 会报错。

Types

type CollectionIndexes

type CollectionIndexes struct {
	Collection string      `json:"collection"`
	Indexes    []IndexSpec `json:"indexes"`
}

CollectionIndexes 一个集合的索引清单

type IndexSpec

type IndexSpec struct {
	Keys                    []KeyVal `json:"keys"`                              // [{"f":"tenant_id","v":1}, {"f":"domain","v":1}](有序)
	Unique                  bool     `json:"unique,omitempty"`                  // 是否唯一索引
	Name                    string   `json:"name,omitempty"`                    // 索引名,缺省由 mongo 自动命名
	PartialFilterExpression bson.M   `json:"partialFilterExpression,omitempty"` // 部分索引过滤条件(如 {"is_deleted": false},配合假删除)
}

IndexSpec 单个索引定义(对应 JSON 中一个索引)

type KeyVal

type KeyVal struct {
	Field string `json:"f"`
	Value any    `json:"v"`
}

KeyVal 索引键(保序):Field 字段名,Value 为 1/-1(排序方向)或 "text" 等字符串

Jump to

Keyboard shortcuts

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