Documentation
¶
Index ¶
- Constants
- Variables
- func BootStrap()
- func ColValue(op operator, value any) any
- func ErrNoTableSuffix(table string) error
- func RegisterDB(dbName, driverName, dataSource string, params ...any)
- func RegisterModel(db string, models ...any)
- func RegisterModelWithPrefix(prefix, db string, models ...any)
- func RegisterModelWithSuffix(suffix, db string, models ...any)
- func ResetModelCache()
- func SetConnMaxLifetime(dbName string, d time.Duration)
- func SetDefaultLogger(l *zap.Logger)
- func SetDefaultLoggerTag(tag zap.Field)
- func SetMaxIdleConns(dbName string, maxIdleConns int)
- func SetMaxOpenConns(dbName string, maxOpenConns int)
- func ToInt64(value any) (d int64)
- func ToStr(value any, args ...int) (s string)
- type Condition
- func (c Condition) And(expr string, args ...any) *Condition
- func (c *Condition) AndCond(cond *Condition) *Condition
- func (c Condition) AndNot(expr string, args ...any) *Condition
- func (c *Condition) AndNotCond(cond *Condition) *Condition
- func (c *Condition) GetWhereSQL(mi *modelInfo, cond *sqlbuilder.Cond) string
- func (c *Condition) IsEmpty() bool
- func (c Condition) Or(expr string, args ...any) *Condition
- func (c *Condition) OrCond(cond *Condition) *Condition
- func (c Condition) OrNot(expr string, args ...any) *Condition
- func (c *Condition) OrNotCond(cond *Condition) *Condition
- type DynamicFielder
- type Inserter
- type JSONValue
- type Ormer
- type Params
- type ParamsList
- type QuerySetter
- type RawQueryer
- type RawStmtQueryer
- type StmtQueryer
- type StrTo
- func (f *StrTo) Bool() (bool, error)
- func (f *StrTo) Clear()
- func (f *StrTo) Exist() bool
- func (f *StrTo) Float32() (float32, error)
- func (f *StrTo) Float64() (float64, error)
- func (f *StrTo) Int() (int, error)
- func (f *StrTo) Int16() (int16, error)
- func (f *StrTo) Int32() (int32, error)
- func (f *StrTo) Int64() (int64, error)
- func (f *StrTo) Int8() (int8, error)
- func (f *StrTo) Set(v string)
- func (f *StrTo) String() string
- func (f *StrTo) Uint() (uint, error)
- func (f *StrTo) Uint16() (uint16, error)
- func (f *StrTo) Uint32() (uint32, error)
- func (f *StrTo) Uint64() (uint64, error)
- func (f *StrTo) Uint8() (uint8, error)
Constants ¶
const ( // ExprSep define the expression separation ExprSep = "__" // HintRouterMaster define the router hint for `force master` HintRouterMaster = `{"router":"m"} ` )
const ( TagTypeNoArgs = 1 TagTypeWithArgs = 2 TagTypeOptionalArgs = 3 )
const ( ColAdd operator = iota ColSub ColMul ColDiv )
define Col operations
Variables ¶
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") )
var ( Debug = false DebugSQLBuilder = false DefaultRowsLimit = 1000 DefaultTimeLoc = time.Local )
Define common vars
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 ¶
ColValue do the field raw changes. e.g Nums = Nums + 10. usage:
Params{
"Nums": ColValue(Col_Add, 10),
}
func ErrNoTableSuffix ¶
ErrNoTableSuffix indicates not table suffix is provided for sharded model
func RegisterDB ¶
RegisterDB Setting the database connect params. Use the database driver self dataSource args.
func RegisterModelWithPrefix ¶
RegisterModelWithPrefix register models with a prefix
func RegisterModelWithSuffix ¶
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 ¶
SetConnMaxLifetime sets the maximum amount of time a connection may be reused.
func SetDefaultLoggerTag ¶
SetDefaultLoggerTag set the logger tag
func SetMaxIdleConns ¶
SetMaxIdleConns Change the max idle conns for *sql.DB, use specify database alias name
func SetMaxOpenConns ¶
SetMaxOpenConns Change the max open conns for *sql.DB, use specify database alias name
Types ¶
type Condition ¶
type Condition struct {
// contains filtered or unexported fields
}
Condition struct. work for WHERE conditions.
func (*Condition) AndNotCond ¶
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
type DynamicFielder ¶
DynamicFielder is the dynamic fielder interface Struct which implement this interface will have dynamic field support
type JSONValue ¶
type JSONValue struct {
// contains filtered or unexported fields
}
JSONValue is the json wrapper
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 any, cols ...string) error
// ReadForUpdate Like Read(), but with "FOR UPDATE" clause, useful in transaction.
// Some databases are not support this feature.
ReadForUpdate(md any, 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(any) (int64, error)
// InsertMulti insert some models to database
InsertMulti(bulk int, mds any) (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 any, cols ...string) (int64, error)
// Delete delete model in database
Delete(md any, 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 any) 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 ...any) RawQueryer
// RollbackIfNotCommitted as its name explains.
RollbackIfNotCommitted()
}
Ormer define the orm interface
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, ...any) QuerySetter
// Exclude add NOT condition to querySeter.
// have the same usage as Filter
Exclude(string, ...any) 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 any, 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 any, 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 ...any) error
// QueryRows query data rows and map to container
QueryRows(container any) error
// SetArgs set args
SetArgs(...any) 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 ...any) (sql.Result, error)
Query(args ...any) (*sql.Rows, error)
QueryRow(args ...any) *sql.Row
}
RawStmtQueryer statement querier
type StmtQueryer ¶
type StmtQueryer interface {
Close() error
ExecContext(ctx context.Context, args ...any) (sql.Result, error)
QueryContext(ctx context.Context, args ...any) (*sql.Rows, error)
QueryRowContext(ctx context.Context, args ...any) *sql.Row
}
StmtQueryer statement querier
Source Files
¶
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. |