orm

package
v1.0.8 Latest Latest
Warning

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

Go to latest
Published: Nov 4, 2023 License: Apache-2.0 Imports: 18 Imported by: 0

README

beego orm的优化版,参照: https://beego.me/docs/mvc/model/overview.md

Documentation

Index

Constants

View Source
const (
	// ExprSep define the expression separation
	ExprSep = "__"
	// HintRouterMaster define the router hint for `force master`
	HintRouterMaster = `{"router":"m"} `
)
View Source
const (
	TagTypeNoArgs       = 1
	TagTypeWithArgs     = 2
	TagTypeOptionalArgs = 3
)
View Source
const (
	ColAdd operator = iota
	ColSub
	ColMul
	ColDiv
)

define Col operations

Variables

View Source
var (
	// ErrMissPK indicates missing pk error
	ErrMissPK = errors.New("missed pk value")

	// ErrTxHasBegan indicates tx already begin
	ErrTxHasBegan = errors.New("<Ormer.Begin> transaction already begin")

	// ErrTxDone indicates tx already done
	ErrTxDone = errors.New("<Ormer.Commit/Rollback> transaction not begin")

	// ErrMultiRows indicates multi rows returned
	ErrMultiRows = errors.New("<QuerySeter> return multi rows")

	// ErrNoRows indicates no row found
	ErrNoRows = errors.New("<QuerySeter> no row found")

	// ErrStmtClosed indicates stmt already closed
	ErrStmtClosed = errors.New("<QuerySeter> stmt already closed")

	// ErrTableSuffixNotSameInBatchInsert indicates table suffix not same in batch insertion
	ErrTableSuffixNotSameInBatchInsert = errors.New("<Ormer> table suffix not same in batch insert")

	// ErrNotImplement indicates function not implemented
	ErrNotImplement = errors.New("have not implement")
)
View Source
var (
	Debug            = false
	DebugSQLBuilder  = false
	DefaultRowsLimit = 1000
	DefaultTimeLoc   = time.Local
)

Define common vars

View Source
var DefaultLimit = 1000

DefaultLimit the default limit batch size, if zero, then limit is disabled

Functions

func BootStrap

func BootStrap()

BootStrap bootrap models. make all model parsed and can not add more models

func ColValue

func ColValue(op operator, value interface{}) interface{}

ColValue do the field raw changes. e.g Nums = Nums + 10. usage:

Params{
	"Nums": ColValue(Col_Add, 10),
}

func ErrNoTableSuffix

func ErrNoTableSuffix(table string) error

ErrNoTableSuffix indicates not table suffix is provided for sharded model

func IsEmptyValue

func IsEmptyValue(v reflect.Value) bool

IsEmptyValue check the value is zero

func RegisterDB

func RegisterDB(dbName, driverName, dataSource string, params ...interface{})

RegisterDB Setting the database connect params. Use the database driver self dataSource args.

func RegisterModel

func RegisterModel(db string, models ...interface{})

RegisterModel register models

func RegisterModelWithPrefix

func RegisterModelWithPrefix(prefix, db string, models ...interface{})

RegisterModelWithPrefix register models with a prefix

func RegisterModelWithSuffix

func RegisterModelWithSuffix(suffix, db string, models ...interface{})

RegisterModelWithSuffix register models with a suffix

func ResetModelCache

func ResetModelCache()

ResetModelCache Clean model cache. Then you can re-RegisterModel. Common use this api for test case.

func SetConnMaxLifetime

func SetConnMaxLifetime(dbName string, d time.Duration)

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

func SetDefaultLogger

func SetDefaultLogger(l *zap.Logger)

SetDefaultLogger set the orm logger

func SetDefaultLoggerTag

func SetDefaultLoggerTag(tag zap.Field)

SetDefaultLoggerTag set the logger tag

func SetMaxIdleConns

func SetMaxIdleConns(dbName string, maxIdleConns int)

SetMaxIdleConns Change the max idle conns for *sql.DB, use specify database alias name

func SetMaxOpenConns

func SetMaxOpenConns(dbName string, maxOpenConns int)

SetMaxOpenConns Change the max open conns for *sql.DB, use specify database alias name

func ToInt64

func ToInt64(value interface{}) (d int64)

ToInt64 interface to int64

func ToStr

func ToStr(value interface{}, args ...int) (s string)

ToStr interface to string

Types

type Condition

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

Condition struct. work for WHERE conditions.

func NewCondition

func NewCondition() *Condition

NewCondition return new condition struct

func (Condition) And

func (c Condition) And(expr string, args ...interface{}) *Condition

And add expression to condition

func (*Condition) AndCond

func (c *Condition) AndCond(cond *Condition) *Condition

AndCond combine a condition to current condition

func (Condition) AndNot

func (c Condition) AndNot(expr string, args ...interface{}) *Condition

AndNot add NOT expression to condition

func (*Condition) AndNotCond

func (c *Condition) AndNotCond(cond *Condition) *Condition

AndNotCond combine a AND NOT condition to current condition

func (*Condition) GetWhereSQL

func (c *Condition) GetWhereSQL(mi *modelInfo, cond *sqlbuilder.Cond) string

GetWhereSQL return the where expr

func (*Condition) IsEmpty

func (c *Condition) IsEmpty() bool

IsEmpty check the condition arguments are empty or not.

func (Condition) Or

func (c Condition) Or(expr string, args ...interface{}) *Condition

Or add OR expression to condition

func (*Condition) OrCond

func (c *Condition) OrCond(cond *Condition) *Condition

OrCond combine a OR condition to current condition

func (Condition) OrNot

func (c Condition) OrNot(expr string, args ...interface{}) *Condition

OrNot add OR NOT expression to condition

func (*Condition) OrNotCond

func (c *Condition) OrNotCond(cond *Condition) *Condition

OrNotCond combine a OR NOT condition to current condition

type DynamicFielder

type DynamicFielder interface {
	NewDynamicField(fieldName string) interface{}
}

DynamicFielder is the dynamic fielder interface Struct which implement this interface will have dynamic field support

type Inserter

type Inserter interface {
	Insert(interface{}) (int64, error)
	Close() error
}

Inserter insert prepared statement

type JSONValue

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

JSONValue is the json wrapper

func (*JSONValue) Scan

func (jv *JSONValue) Scan(value interface{}) error

Scan implements sql.Scanner interface

func (*JSONValue) Value

func (jv *JSONValue) Value() (driver.Value, error)

Value implements sql.Valuer interface

type Ormer

type Ormer interface {
	// Read data to model
	// for example:
	//	this will find User by Id field
	// 	u = &User{Id: user.Id}
	// 	err = Ormer.Read(u)
	//	this will find User by UserName field
	// 	u = &User{UserName: "astaxie", Password: "pass"}
	//	err = Ormer.Read(u, "UserName")
	Read(md interface{}, cols ...string) error
	// ReadForUpdate Like Read(), but with "FOR UPDATE" clause, useful in transaction.
	// Some databases are not support this feature.
	ReadForUpdate(md interface{}, cols ...string) error
	// Insert model data to database
	// for example:
	//  user := new(User)
	//  id, err = Ormer.Insert(user)
	//  user must a pointer and Insert will set user's pk field
	Insert(interface{}) (int64, error)
	// InsertMulti insert some models to database
	InsertMulti(bulk int, mds interface{}) (int64, error)
	// Update model to database.
	// cols set the columns those want to update.
	// find model by Id(pk) field and update columns specified by fields, if cols is null then update all columns
	Update(md interface{}, cols ...string) (int64, error)
	// Delete delete model in database
	Delete(md interface{}, cols ...string) (int64, error)
	// QueryTable return a QuerySeter for table operations.
	// table name can be string or struct.
	// e.g. QueryTable(&user{}) or QueryTable((*User)(nil)),
	QueryTable(ptrStruct interface{}) QuerySetter
	// Using switch to another registered database driver by given name.
	Using(name string)
	// Begin begin transaction
	// for example:
	// 	o := NewOrm(logger)
	// 	err := o.Begin()
	// 	...
	// 	err = o.Rollback()
	Begin() error
	// Commit  transaction
	Commit() error
	// Rollback transaction
	Rollback() error
	// Raw return a raw query seter for raw sql string.
	// for example:
	//	 ormer.Raw("UPDATE `user` SET `user_name` = ? WHERE `user_name` = ?", "slene", "testing").Exec()
	//	// update user testing's name to slene
	Raw(query string, args ...interface{}) RawQueryer
	// RollbackIfNotCommitted as its name explains.
	RollbackIfNotCommitted()
}

Ormer define the orm interface

func NewOrm

func NewOrm(logger *zap.Logger) Ormer

NewOrm create a new orm object.

type Params

type Params map[string]interface{}

Params stores the Params

type ParamsList

type ParamsList []interface{}

ParamsList stores paramslist

type QuerySetter

type QuerySetter interface {
	// WithSuffix specifies the table suffix
	WithSuffix(tableSuffix string) QuerySetter
	// Distinct Set Distinct
	// for example:
	//  o.QueryTable("policy").Filter("Groups__Group__Users__User", user).
	//    Distinct().
	//    All(&permissions)
	Distinct() QuerySetter
	// Filter add condition expression to QuerySetter.
	// for example:
	//	filter by UserName == 'slene'
	//	qs.Filter("UserName", "slene")
	//	sql : left outer join profile on t0.id1==t1.id2 where t1.age == 28
	//	Filter("profile__Age", 28)
	// 	 // time compare
	//	qs.Filter("created", time.Now())
	Filter(string, ...interface{}) QuerySetter
	// Exclude add NOT condition to querySeter.
	// have the same usage as Filter
	Exclude(string, ...interface{}) QuerySetter
	// SetCond set condition to QuerySetter.
	// sql's where condition
	//	cond := orm.NewCondition()
	//	cond1 := cond.And("profile__isnull", false).AndNot("status__in", 1).Or("profile__age__gt", 2000)
	//	//sql-> WHERE T0.`profile_id` IS NOT NULL AND NOT T0.`Status` IN (?) OR T1.`age` >  2000
	//	num, err := qs.SetCond(cond1).Count()
	SetCond(*Condition) QuerySetter
	// GetCond get condition from QuerySetter.
	// sql's where condition
	//  cond := orm.NewCondition()
	//  cond = cond.And("profile__isnull", false).AndNot("status__in", 1)
	//  qs = qs.SetCond(cond)
	//  cond = qs.GetCond()
	//  cond := cond.Or("profile__age__gt", 2000)
	//  //sql-> WHERE T0.`profile_id` IS NOT NULL AND NOT T0.`Status` IN (?) OR T1.`age` >  2000
	//  num, err := qs.SetCond(cond).Count()
	GetCond() *Condition
	// GroupBy add GROUP BY expression
	// for example:
	//	qs.GroupBy("id")
	GroupBy(exprs ...string) QuerySetter
	// OrderBy add ORDER expression.
	// "column" means ASC, "-column" means DESC.
	// for example:
	//	qs.OrderBy("-status")
	OrderBy(exprs ...string) QuerySetter
	// Offset add OFFSET value
	Offset(offset int) QuerySetter
	// Limit add LIMIT value.
	Limit(limit int) QuerySetter
	// ForUpdate for update
	ForUpdate() QuerySetter
	// Count return QuerySetter execution result number
	// for example:
	//	num, err = qs.Filter("profile__age__gt", 28).Count()
	Count() (int64, error)
	// Exist check result empty or not after QuerySetter executed
	// the same as QuerySetter.Count > 0
	Exist() (bool, error)
	// Update execute update with parameters
	// for example:
	//	num, err = qs.Filter("user_name", "slene").Update(Params{
	//		"Nums": ColValue(Col_Minus, 50),
	//	}) // user slene's Nums will minus 50
	//	num, err = qs.Filter("UserName", "slene").Update(Params{
	//		"user_name": "slene2"
	//	}) // user slene's  name will change to slene2
	Update(values Params) (int64, error)
	// Delete delete from table
	//for example:
	//	num ,err = qs.Filter("user_name__in", "testing1", "testing2").Delete()
	// 	//delete two user  who's name is testing1 or testing2
	Delete() (int64, error)
	// PrepareInsert return a insert queryer.
	// it can be used in times.
	// example:
	// 	i,err := sq.PrepareInsert()
	// 	num, err = i.Insert(&user1) // user table will add one record user1 at once
	//	num, err = i.Insert(&user2) // user table will add one record user2 at once
	//	err = i.Close() //don't forget call Close
	PrepareInsert() (Inserter, error)
	// All query all data and map to containers.
	// cols means the columns when querying.
	// for example:
	//	var users []*User
	//	qs.All(&users) // users[0],users[1],users[2] ...
	All(container interface{}, cols ...string) error
	// One query one row data and map to containers.
	// cols means the columns when querying.
	// for example:
	//	var user User
	//	qs.One(&user) //user.UserName == "slene"
	One(container interface{}, cols ...string) error
}

QuerySetter is the advanced query interface.

type RawQueryer

type RawQueryer interface {
	// Exec execute sql and get result
	Exec() (sql.Result, error)

	// QueryRow query data and map to container
	QueryRow(containers ...interface{}) error

	// QueryRows query data rows and map to container
	QueryRows(container interface{}) error

	// SetArgs set args
	SetArgs(...interface{}) RawQueryer

	// Prepare return prepared raw statement for used in times.
	// for example:
	// 	pre, err := dORM.Raw("INSERT INTO tag (name) VALUES (?)").Prepare()
	// 	r, err := pre.Exec("name1") // INSERT INTO tag (name) VALUES (`name1`)
	Prepare() (RawStmtQueryer, error)
}

RawQueryer raw query seter create From Ormer.Raw for example:

sql := fmt.Sprintf("SELECT %sid%s,%sname%s FROM %suser%s WHERE id = ?",Q,Q,Q,Q,Q,Q)
rs := Ormer.Raw(sql, 1)

type RawStmtQueryer

type RawStmtQueryer interface {
	Close() error
	Exec(args ...interface{}) (sql.Result, error)
	Query(args ...interface{}) (*sql.Rows, error)
	QueryRow(args ...interface{}) *sql.Row
}

RawStmtQueryer statement querier

type StmtQueryer

type StmtQueryer interface {
	Close() error
	ExecContext(ctx context.Context, args ...interface{}) (sql.Result, error)
	QueryContext(ctx context.Context, args ...interface{}) (*sql.Rows, error)
	QueryRowContext(ctx context.Context, args ...interface{}) *sql.Row
}

StmtQueryer statement querier

type StrTo

type StrTo string

StrTo is the target string

func (*StrTo) Bool

func (f *StrTo) Bool() (bool, error)

Bool string to bool

func (*StrTo) Clear

func (f *StrTo) Clear()

Clear string

func (*StrTo) Exist

func (f *StrTo) Exist() bool

Exist check string exist

func (*StrTo) Float32

func (f *StrTo) Float32() (float32, error)

Float32 string to float32

func (*StrTo) Float64

func (f *StrTo) Float64() (float64, error)

Float64 string to float64

func (*StrTo) Int

func (f *StrTo) Int() (int, error)

Int string to int

func (*StrTo) Int16

func (f *StrTo) Int16() (int16, error)

Int16 string to int16

func (*StrTo) Int32

func (f *StrTo) Int32() (int32, error)

Int32 string to int32

func (*StrTo) Int64

func (f *StrTo) Int64() (int64, error)

Int64 string to int64

func (*StrTo) Int8

func (f *StrTo) Int8() (int8, error)

Int8 string to int8

func (*StrTo) Set

func (f *StrTo) Set(v string)

Set string

func (*StrTo) String

func (f *StrTo) String() string

String string to string

func (*StrTo) Uint

func (f *StrTo) Uint() (uint, error)

Uint string to uint

func (*StrTo) Uint16

func (f *StrTo) Uint16() (uint16, error)

Uint16 string to uint16

func (*StrTo) Uint32

func (f *StrTo) Uint32() (uint32, error)

Uint32 string to uint31

func (*StrTo) Uint64

func (f *StrTo) Uint64() (uint64, error)

Uint64 string to uint64

func (*StrTo) Uint8

func (f *StrTo) Uint8() (uint8, error)

Uint8 string to uint8

Directories

Path Synopsis
Package sqlbuilder is a flexible and powerful tool to build SQL string and associated args.
Package sqlbuilder is a flexible and powerful tool to build SQL string and associated args.

Jump to

Keyboard shortcuts

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