cosmo

package module
v0.0.1 Latest Latest
Warning

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

Go to latest
Published: Aug 24, 2022 License: Apache-2.0 Imports: 15 Imported by: 7

README

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

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

Documentation

Index

Constants

View Source
const (
	MongoTagName     = "BuildUpdate"
	MongoPrimaryKey  = "_id"
	MongoSetOnInsert = "$setOnInsert"
)
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")
)
View Source
var Options = schema.New()

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:最邻近节点,读操作在最邻近的成员,可能是主节点或者从节点。

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

func (this *BulkWrite) Save() (result *mongo.BulkWriteResult, err error)

func (*BulkWrite) Update

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

type Config

type Config struct {
	Logger  logger.Interface
	Plugins map[string]Plugin
	// contains filtered or unexported fields
}

Config GORM config

func (*Config) AfterInitialize

func (c *Config) AfterInitialize(db *DB) error

func (*Config) Register

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

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

type DB

type DB struct {
	*Config

	Error        error
	Statement    *Statement
	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 interface{}) (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(msg interface{}, args ...interface{}) error

Errorf add error to db

func (*DB) Find

func (db *DB) Find(dest interface{}, conds ...interface{}) (tx *DB)

Find find records that match given conditions dest must be a pointer to a slice

func (*DB) Get

func (db *DB) Get(key string) (val interface{}, ok bool)

Get get value with key from current db instance's context

func (*DB) Limit

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

Limit specify the number of records to be retrieved

func (*DB) Merge

func (db *DB) Merge(i interface{}) error

Merge 只更新Model,不会修改数据库 db.Model(m).Merge(i) 参数支持 Struct,map[string]interface{}

func (*DB) Model

func (db *DB) Model(value interface{}) (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) Offset

func (db *DB) Offset(offset int) (tx *DB)

Offset specify the number of records to skip before starting to return the records

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(page, size int) (tx *DB)

Page 分页设置 page-当前页,size-每页大小

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

func (db *DB) Set(key string, value interface{}) *DB

Set store value with key into current db instance's context

func (*DB) SetColumn

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

SetColumn set column's value

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)

Table specify the table you would like to run db operations 使用TABLE 时select,order,Omit 中必须使用数据库字段名称

func (*DB) Update

func (db *DB) Update(values interface{}, conds ...interface{}) (tx *DB)

func (*DB) Use

func (db *DB) Use(plugin Plugin) error

func (*DB) View

func (db *DB) View(paging *values.Paging, conds ...interface{}) (tx *DB)

View 分页查询

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 ExecuteHandle

type ExecuteHandle func(db *DB) error

type Paging

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

分页

func (*Paging) Limit

func (this *Paging) Limit(limit int)

func (*Paging) Offset

func (this *Paging) Offset(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) Page

func (this *Paging) Page(page, size int)

Page 设置分页,page当前页,size每页大小 相当于同时设置limit offset

type Plugin

type Plugin interface {
	Name() string
	Initialize(*DB) error
}

Plugin GORM plugin interface

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
	Logger  logger.Interface
	NowTime func() time.Time
}

Session session config when create session with Session() method

type Statement

type Statement struct {
	*DB
	Dest         interface{}
	Table        string
	Model        interface{}
	ReflectValue reflect.Value
	//ReflectModel reflect.Value
	Omits   []string // omit columns
	Selects []string // selected columns
	Context context.Context
	Clause  *clause.Query
	// 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) Projection

func (stmt *Statement) Projection() map[string]int

Projection 不能同时使用Select和Omit 优先Select生效 可以使用model属性名或者数据库字段名

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