cosmo

package module
v1.0.2 Latest Latest
Warning

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

Go to latest
Published: Mar 28, 2024 License: Apache-2.0 Imports: 14 Imported by: 1

README

仿造GORM接口的MongoDB数据库操作,使用方法参考GORM文档

https://gorm.io/zh_CN/docs/create.html

查找

db.Find(&struct{},where)

db.Model(&struct{}).Find(&map{},where)

使用Omit排除部分columns db.Omit(columns ...string).Find(&struct{},where)

使用Select选定部分columns,只返回选定字段值 db.Select(columns ...string).Find(&struct{},where)

更新

更新所有非空字段: db.Update(&struct{},where)

更新MAP中所有值: db.Model(&struct{}).Update(&map{},where)

排除Omit中的字段: db.Omit(columns ...string).Update(&struct{},where)

只更新Select的字段: db.Select(columns ...string).Update(&struct{},where)

更新并同步内存数据

更新,并将修改后的结果同步更新到Model(&struct{})中,可以配合Omit,Select 排除/选定字段
db.Model(&struct{},true).Update(&map{}|&struct{},where)

Documentation

Index

Constants

View Source
const (
	MongoTagName     = "BuildUpdate"
	MongoPrimaryKey  = "_id"
	MongoSetOnInsert = "$setOnInsert"
)
View Source
const DBNameUpdate = "update"
View Source
const DefaultPageSize = 100

Variables

View Source
var (
	ErrInvalidConfig = errors.New("invalid config")
	// ErrInvalidTransaction invalid transaction when you are trying to `Commit` or `Rollback`
	ErrInvalidTransaction = errors.New("invalid transaction")
	// ErrNotImplemented not implemented
	ErrNotImplemented = errors.New("not implemented")
	// ErrMissingWhereClause missing where clause
	ErrMissingWhereClause = errors.New("WHERE conditions required")
	// ErrUnsupportedRelation unsupported relations
	ErrUnsupportedRelation = errors.New("unsupported relations")
	// ErrPrimaryKeyRequired primary keys required
	ErrPrimaryKeyRequired = errors.New("primary key required")
	// ErrModelValueRequired model value required
	ErrModelValueRequired = errors.New("model value required")
	// ErrInvalidData unsupported data
	ErrInvalidData = errors.New("unsupported data")
	// ErrUnsupportedDriver unsupported driver
	ErrUnsupportedDriver = errors.New("unsupported driver")
	// ErrRegistered registered
	ErrRegistered = errors.New("registered")
	// ErrInvalidField invalid field
	ErrInvalidField = errors.New("invalid field")
	// ErrEmptySlice empty slice found
	ErrEmptySlice = errors.New("empty slice found")
	// ErrDryRunModeUnsupported dry run mode unsupported
	ErrDryRunModeUnsupported = errors.New("dry run mode unsupported")
	// ErrInvalidDB invalid db
	ErrInvalidDB = errors.New("invalid db")
	// ErrInvalidValue invalid value
	ErrInvalidValue = errors.New("invalid value, should be pointer to struct or slice")
	ErrInvalidModel = errors.New("invalid model, should be pointer to struct or struct")
	// ErrInvalidValueOfLength invalid values do not match length
	ErrInvalidValueOfLength = errors.New("invalid association values, length doesn't match")

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

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

Functions

func NewClient

func NewClient(address string, opts ...*options.ClientOptions) (client *mongo.Client, err error)

NewClient

uri实例 mongodb://[username:password@]host1[:port1][,host2[:port2],...[,hostN[:portN]]][/[dbname][?options]]

mongodb:// 前缀,代表这是一个Connection String

username:password@ 如果启用了鉴权,需要指定用户密码

hostX:portX 多个 mongos 的地址列表

/dbname 鉴权时,用户帐号所属的数据库

?options 指定额外的连接选项

read preference

1)primary : 主节点,默认模式,读操作只在主节点,如果主节点不可用,报错或者抛出异常。

2)primaryPreferred:首选主节点,大多情况下读操作在主节点,如果主节点不可用,如故障转移,读操作在从节点。

3)secondary:从节点,读操作只在从节点, 如果从节点不可用,报错或者抛出异常。

4)secondaryPreferred:首选从节点,大多情况下读操作在从节点,特殊情况(如单主节点架构)读操作在主节点。

5)nearest:最邻近节点,读操作在最邻近的成员,可能是主节点或者从节点。

func NewClientOptions added in v0.0.3

func NewClientOptions() *options.ClientOptions

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() (err error)

func (*BulkWrite) Update

func (this *BulkWrite) Update(data interface{}, where ...interface{})

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 DB

type DB struct {
	*Config

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

DB GORM DB definition

func New

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

New address uri || *mongo.Client

func (*DB) AutoMigrator

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

AutoMigrator returns migrator Sparse

func (*DB) BulkWrite

func (db *DB) BulkWrite(model interface{}) *BulkWrite

BulkWrite 批量写入

func (*DB) Close

func (db *DB) Close() (err error)

func (*DB) Collection

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

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 新数据库

func (*DB) Delete

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

Delete 删除记录 db.delete(&User{Id:1,name:"myname"}) 匹配 _id=1 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

func (*DB) Errorf

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

Errorf add error to db

func (*DB) Find

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

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

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

func (*DB) Page

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

Page 分页查询

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 create new db session

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)

func (*DB) Table

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

func (*DB) Update

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

func (*DB) Upsert added in v0.0.3

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

Upsert update时如果不存在自动insert

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 change current instance db's context to ctx

type Paging

type Paging struct {
	Rows   interface{} `json:"rows"`
	Page   int         `json:"page"`   //当前页
	Size   int         `json:"size"`   //每页大小
	Total  int         `json:"total"`  //总页码数
	Record int         `json:"record"` //总记录数
	Update int64       `json:"update"` //最后更新时间
	// contains filtered or unexported fields
}

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) Order

func (this *Paging) Order(key string, sort int)

Order 排序方式 1 和 -1 来指定排序的方式,其中 1 为升序排列,而 -1 是用于降序排列。

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

	Context context.Context
	Clause  *clause.Query
	Paging  *Paging
	// contains filtered or unexported fields
}

Statement statement

func NewStatement

func NewStatement(db *DB) *Statement

func (*Statement) DBName

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

DBName 将对象字段转换成数据库字段

func (*Statement) Order

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

Order 排序

func (*Statement) Parse

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

Parse Parse model to schema

func (*Statement) Schema

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

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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