mongodb

package
v0.2.4 Latest Latest
Warning

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

Go to latest
Published: Sep 8, 2023 License: Apache-2.0 Imports: 33 Imported by: 0

Documentation

Index

Constants

View Source
const (
	OrmTagForStruct    = "orm"
	OrmTagForTable     = "table"
	OrmTagForWith      = "with"
	OrmTagForWithWhere = "where"
	OrmTagForWithOrder = "order"
	OrmTagForDo        = "do"
)
View Source
const (
	DefaultGroupName = "default" // Default group name.
)
View Source
const HookName = "mongodb"

Variables

This section is empty.

Functions

func AddConfigNode

func AddConfigNode(group string, node ConfigNode)

AddConfigNode adds one node configuration to configuration of given group.

func AddDefaultConfigGroup

func AddDefaultConfigGroup(nodes ConfigGroup)

AddDefaultConfigGroup adds multiple node configurations to configuration of default group.

func AddDefaultConfigNode

func AddDefaultConfigNode(node ConfigNode)

AddDefaultConfigNode adds one node configuration to configuration of default group.

func ConvertDataForRecord

func ConvertDataForRecord(ctx context.Context, value interface{}) (map[string]interface{}, error)

ConvertDataForRecord is a very important function, which does converting for any data that will be inserted into table/collection as a record.

The parameter `value` should be type of *map/map/*struct/struct. It supports embedded struct definition for struct.

func ConvertDataForRecordValue

func ConvertDataForRecordValue(ctx context.Context, value interface{}) (interface{}, error)

func DataToMapDeep

func DataToMapDeep(value interface{}) map[string]interface{}

DataToMapDeep converts `value` to map type recursively(if attribute struct is embedded). The parameter `value` should be type of *map/map/*struct/struct. It supports embedded struct definition for struct.

func GetCollection

func GetCollection(ctx context.Context, collectionName string, opts ...*options.CollectionOptions) *mongo.Collection

func GetDatabaseInstance

func GetDatabaseInstance(ctx context.Context) *mongo.Database

func GetDefaultGroup

func GetDefaultGroup() string

GetDefaultGroup returns the { name of default configuration.

func IsConfigured

func IsConfigured() bool

IsConfigured checks and returns whether the database configured. It returns true if any configuration exists.

func SetConfig

func SetConfig(config Config)

SetConfig sets the global configuration for package. It will overwrite the old configuration of package.

func SetConfigGroup

func SetConfigGroup(group string, nodes ConfigGroup)

SetConfigGroup sets the configuration for given group.

func SetDefaultGroup

func SetDefaultGroup(name string)

SetDefaultGroup sets the group name for default configuration.

func TestConnectivity

func TestConnectivity(ctx context.Context) error

Types

type Config

type Config map[string]ConfigGroup

Config is the configuration management object.

type ConfigGroup

type ConfigGroup []ConfigNode

ConfigGroup is a slice of configuration node for specified named group.

func GetConfig

func GetConfig(group string) ConfigGroup

GetConfig retrieves and returns the configuration of given group.

type ConfigNode

type ConfigNode struct {
	Host                 string        `json:"host"`                 // Host of server, ip or domain like: 127.0.0.1, localhost
	Port                 string        `json:"port"`                 // Port, it's commonly 3306.
	User                 string        `json:"user"`                 // Authentication username.
	Pass                 string        `json:"pass"`                 // Authentication password.
	Name                 string        `json:"name"`                 // Default used database name.
	Type                 string        `json:"type"`                 // Database type: mysql, sqlite, mssql, pgsql, oracle.
	Link                 string        `json:"link"`                 // (Optional) Custom link information for all configuration in one single string.
	Extra                string        `json:"extra"`                // (Optional) Extra configuration according the registered third-party database driver.
	Role                 string        `json:"role"`                 // (Optional, "master" in default) Node role, used for master-slave mode: master, slave.
	Debug                bool          `json:"debug"`                // (Optional) Debug mode enables debug information logging and output.
	Prefix               string        `json:"prefix"`               // (Optional) Table prefix.
	DryRun               bool          `json:"dryRun"`               // (Optional) Dry run, which does SELECT but no INSERT/UPDATE/DELETE statements.
	Weight               int           `json:"weight"`               // (Optional) Weight for load balance calculating, it's useless if there's just one node.
	Charset              string        `json:"charset"`              // (Optional, "utf8mb4" in default) Custom charset when operating on database.
	Protocol             string        `json:"protocol"`             // (Optional, "tcp" in default) See net.Dial for more information which networks are available.
	Timezone             string        `json:"timezone"`             // (Optional) Sets the time zone for displaying and interpreting time stamps.
	Namespace            string        `json:"namespace"`            // (Optional) Namespace for some databases. Eg, in pgsql, the `Name` acts as the `catalog`, the `NameSpace` acts as the `schema`.
	MaxIdleConnCount     int           `json:"maxIdle"`              // (Optional) Max idle connection configuration for underlying connection pool.
	MaxOpenConnCount     int           `json:"maxOpen"`              // (Optional) Max open connection configuration for underlying connection pool.
	MaxConnLifeTime      time.Duration `json:"maxLifeTime"`          // (Optional) Max amount of time a connection may be idle before being closed.
	QueryTimeout         time.Duration `json:"queryTimeout"`         // (Optional) Max query time for per dql.
	ExecTimeout          time.Duration `json:"execTimeout"`          // (Optional) Max exec time for dml.
	TranTimeout          time.Duration `json:"tranTimeout"`          // (Optional) Max exec time for a transaction.
	PrepareTimeout       time.Duration `json:"prepareTimeout"`       // (Optional) Max exec time for prepare operation.
	CreatedAt            string        `json:"createdAt"`            // (Optional) The filed name of table for automatic-filled created datetime.
	UpdatedAt            string        `json:"updatedAt"`            // (Optional) The filed name of table for automatic-filled updated datetime.
	DeletedAt            string        `json:"deletedAt"`            // (Optional) The filed name of table for automatic-filled updated datetime.
	TimeMaintainDisabled bool          `json:"timeMaintainDisabled"` // (Optional) Disable the automatic time maintaining feature.
}

ConfigNode is configuration for one node.

type Core

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

Core is the base struct for database management.

func (*Core) GetCache

func (c *Core) GetCache() *gcache.Cache

GetCache returns the internal cache object.

func (*Core) GetConfig

func (c *Core) GetConfig() *ConfigNode

GetConfig returns the current used node configuration.

func (*Core) GetDebug

func (c *Core) GetDebug() bool

GetDebug returns the debug value.

func (*Core) GetDryRun

func (c *Core) GetDryRun() bool

GetDryRun returns the DryRun value.

func (*Core) GetGroup

func (c *Core) GetGroup() string

GetGroup returns the group string configured.

func (*Core) GetLogger

func (c *Core) GetLogger() glog.ILogger

GetLogger returns the (logger) of the orm.

func (*Core) GetPrefix

func (c *Core) GetPrefix() string

GetPrefix returns the table prefix string configured.

func (*Core) GetSchema

func (c *Core) GetSchema() string

GetSchema returns the schema configured.

func (*Core) SetDebug

func (c *Core) SetDebug(debug bool)

SetDebug enables/disables the debug mode.

func (*Core) SetDryRun

func (c *Core) SetDryRun(enabled bool)

SetDryRun enables/disables the DryRun feature.

func (*Core) SetLogger

func (c *Core) SetLogger(logger glog.ILogger)

SetLogger sets the logger for orm.

func (*Core) SetMaxConnLifeTime

func (c *Core) SetMaxConnLifeTime(d time.Duration)

SetMaxConnLifeTime sets the maximum amount of time a connection may be reused.

Expired connections may be closed lazily before reuse.

If d <= 0, connections are not closed due to a connection's age.

func (*Core) SetMaxIdleConnCount

func (c *Core) SetMaxIdleConnCount(n int)

SetMaxIdleConnCount sets the maximum number of connections in the idle connection pool.

If MaxOpenConns is greater than 0 but less than the new MaxIdleConns, then the new MaxIdleConns will be reduced to match the MaxOpenConns limit.

If n <= 0, no idle connections are retained.

The default max idle connections is currently 2. This may change in a future release.

func (*Core) SetMaxOpenConnCount

func (c *Core) SetMaxOpenConnCount(n int)

SetMaxOpenConnCount sets the maximum number of open connections to the database.

If MaxIdleConns is greater than 0 and the new MaxOpenConns is less than MaxIdleConns, then MaxIdleConns will be reduced to match the new MaxOpenConns limit.

If n <= 0, then there is no limit on the number of open connections. The default is 0 (unlimited).

type List

type List = []Map // List is type of map array.

type Map

type Map = map[string]interface{} // Map is alias of map[string]interface{}, which is the most common usage map type.

type Model

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

func NewModel

func NewModel(ctx context.Context, collectionName string) *Model

func (*Model) Builder

func (m *Model) Builder() *WhereBuilder

Builder creates and returns a WhereBuilder.

func (*Model) Count

func (m *Model) Count(ctx context.Context) (int64, error)

func (*Model) Data

func (m *Model) Data(ctx context.Context, data ...interface{}) *Model

Data sets the operation data for the model. The parameter `data` can be type of string/map/gmap/slice/struct/*struct, etc. Note that, it uses shallow value copying for `data` if `data` is type of map/slice to avoid changing it inside function. Eg: Data("uid=10000") Data("uid", 10000) Data("uid=? AND name=?", 10000, "john") Data(g.Map{"uid": 10000, "name":"john"}) Data(g.Slice{g.Map{"uid": 10000, "name":"john"}, g.Map{"uid": 20000, "name":"smith"}).

func (*Model) Delete

func (m *Model) Delete(ctx context.Context,
	opts ...*options.DeleteOptions) (*mongo.DeleteResult, error)

func (*Model) Fields

func (m *Model) Fields(fields ...string) *Model

Fields appends `fields` to the operation fields of the model

Also see FieldsEx.

reference: https://www.mongodb.com/docs/drivers/go/current/fundamentals/crud/read-operations/project/#include-a-field

func (*Model) FieldsEx

func (m *Model) FieldsEx(fields ...string) *Model

FieldsEx appends `fields` to the excluded operation fields of the model

Also see Fields.

reference: https://www.mongodb.com/docs/drivers/go/current/fundamentals/crud/read-operations/project/#exclude-a-field

func (*Model) InsertOne

func (m *Model) InsertOne(ctx context.Context, document interface{},
	opts ...*options.InsertOneOptions) (*mongo.InsertOneResult, error)

func (*Model) OmitNilData

func (m *Model) OmitNilData() *Model

OmitNilData sets optionOmitNilData option for the model, which automatically filers the Data parameters for `nil` values.

func (*Model) Save

func (m *Model) Save(ctx context.Context, document interface{},
	opts ...*options.UpdateOptions) (*mongo.UpdateResult, error)

func (*Model) Scan

func (m *Model) Scan(ctx context.Context, pointer interface{}) error

func (*Model) WhereBetween

func (m *Model) WhereBetween(key string, min, max interface{}) *Model

func (*Model) WhereEq

func (m *Model) WhereEq(key string, value interface{}) *Model

func (*Model) WhereGT

func (m *Model) WhereGT(key string, value interface{}) *Model

func (*Model) WhereGTE

func (m *Model) WhereGTE(key string, value interface{}) *Model

func (*Model) WhereIn

func (m *Model) WhereIn(key string, value ...interface{}) *Model

func (*Model) WhereLT

func (m *Model) WhereLT(key string, value interface{}) *Model

func (*Model) WhereLTE

func (m *Model) WhereLTE(key string, value interface{}) *Model

func (*Model) WhereLike

func (m *Model) WhereLike(key string, like string) *Model

func (*Model) WhereNE

func (m *Model) WhereNE(key string, value interface{}) *Model

func (*Model) WhereNotBetween

func (m *Model) WhereNotBetween(key string, min, max interface{}) *Model

func (*Model) WhereNotIn

func (m *Model) WhereNotIn(key string, value ...interface{}) *Model

func (*Model) WhereNotLike

func (m *Model) WhereNotLike(key string, like string) *Model

func (*Model) WhereNotNull

func (m *Model) WhereNotNull(key ...string) *Model

func (*Model) WhereNull

func (m *Model) WhereNull(key ...string) *Model

func (*Model) WherePri

func (m *Model) WherePri(args []string) *Model

WherePri does the same logic as Model.Where except that if the parameter `where` is a single condition like int/string/float/slice, it treats the condition as the primary key value. That is, if primary key is "id" and given `where` parameter as "123", the WherePri function treats the condition as "id=123", but Model.Where treats the condition as string "123".

type MongoResult

type MongoResult struct {
	InsertedID   string
	AffectedRows int64
}

type Raw

type Raw bson.Raw // Raw is a raw sql that will not be treated as argument but as a direct sql part.

type Record

type Record map[string]Value // Record is the row record of the table.

func (Record) GMap

func (r Record) GMap() *gmap.StrAnyMap

GMap converts `r` to a gmap.

func (Record) IsEmpty

func (r Record) IsEmpty() bool

IsEmpty checks and returns whether `r` is empty.

func (Record) Json

func (r Record) Json() string

Json converts `r` to JSON format content.

func (Record) Map

func (r Record) Map() Map

Map converts `r` to map[string]interface{}.

func (Record) Struct

func (r Record) Struct(pointer interface{}) error

Struct converts `r` to a struct. Note that the parameter `pointer` should be type of *struct/**struct.

Note that it returns sql.ErrNoRows if `r` is empty.

func (Record) Xml

func (r Record) Xml(rootTag ...string) string

Xml converts `r` to XML format content.

type Result

type Result []Record // Result is the row record array.

func (Result) Array

func (r Result) Array(field ...string) []Value

Array retrieves and returns specified column values as slice. The parameter `field` is optional is the column field is only one. The default `field` is the first field name of the first item in `Result` if parameter `field` is not given.

func (Result) Chunk

func (r Result) Chunk(size int) []Result

Chunk splits a Result into multiple Results, the size of each array is determined by `size`. The last chunk may contain less than size elements.

func (Result) IsEmpty

func (r Result) IsEmpty() bool

IsEmpty checks and returns whether `r` is empty.

func (Result) Json

func (r Result) Json() string

Json converts `r` to JSON format content.

func (Result) Len

func (r Result) Len() int

Len returns the length of result list.

func (Result) List

func (r Result) List() List

List converts `r` to a List.

func (Result) MapKeyInt

func (r Result) MapKeyInt(key string) map[int]Map

MapKeyInt converts `r` to a map[int]Map of which key is specified by `key`.

func (Result) MapKeyStr

func (r Result) MapKeyStr(key string) map[string]Map

MapKeyStr converts `r` to a map[string]Map of which key is specified by `key`.

func (Result) MapKeyUint

func (r Result) MapKeyUint(key string) map[uint]Map

MapKeyUint converts `r` to a map[uint]Map of which key is specified by `key`.

func (Result) MapKeyValue

func (r Result) MapKeyValue(key string) map[string]Value

MapKeyValue converts `r` to a map[string]Value of which key is specified by `key`. Note that the item value may be type of slice.

func (Result) RecordKeyInt

func (r Result) RecordKeyInt(key string) map[int]Record

RecordKeyInt converts `r` to a map[int]Record of which key is specified by `key`.

func (Result) RecordKeyStr

func (r Result) RecordKeyStr(key string) map[string]Record

RecordKeyStr converts `r` to a map[string]Record of which key is specified by `key`.

func (Result) RecordKeyUint

func (r Result) RecordKeyUint(key string) map[uint]Record

RecordKeyUint converts `r` to a map[uint]Record of which key is specified by `key`.

func (Result) Size

func (r Result) Size() int

Size is alias of function Len.

func (Result) Structs

func (r Result) Structs(pointer interface{}) (err error)

Structs converts `r` to struct slice. Note that the parameter `pointer` should be type of *[]struct/*[]*struct.

func (Result) Xml

func (r Result) Xml(rootTag ...string) string

Xml converts `r` to XML format content.

type Value

type Value = *gvar.Var // Value is the field value type.

type WhereBuilder

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

WhereBuilder holds multiple where conditions in a group.

func (*WhereBuilder) Clone

func (b *WhereBuilder) Clone() *WhereBuilder

Clone clones and returns a WhereBuilder that is a copy of current one.

type WhereHolder

type WhereHolder struct {
	Type     string        // Type of this holder.
	Operator int           // Operator for this holder.
	Where    interface{}   // Where parameter, which can commonly be type of string/map/struct.
	Args     []interface{} // Arguments for where parameter.
	Prefix   string        // Field prefix, eg: "user.", "order.".
}

WhereHolder is the holder for where condition preparing.

Directories

Path Synopsis
internal
reflection
Package reflection provides some reflection functions for internal usage.
Package reflection provides some reflection functions for internal usage.

Jump to

Keyboard shortcuts

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