gorm/chainable_api.go

289 lines
8.1 KiB
Go
Raw Permalink Normal View History

2020-01-29 14:22:44 +03:00
package gorm
2020-02-04 03:56:15 +03:00
import (
"fmt"
"regexp"
2020-02-16 08:45:27 +03:00
"strings"
2020-02-04 03:56:15 +03:00
2020-06-02 04:16:07 +03:00
"gorm.io/gorm/clause"
"gorm.io/gorm/utils"
2020-02-04 03:56:15 +03:00
)
2020-01-30 10:14:48 +03:00
2020-01-29 14:22:44 +03:00
// 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")
2020-03-09 15:37:01 +03:00
func (db *DB) Model(value interface{}) (tx *DB) {
2020-01-29 14:22:44 +03:00
tx = db.getInstance()
2020-01-29 22:03:06 +03:00
tx.Statement.Model = value
2020-01-29 14:22:44 +03:00
return
}
2020-01-30 10:14:48 +03:00
// Clauses Add clauses
2020-03-09 15:37:01 +03:00
func (db *DB) Clauses(conds ...clause.Expression) (tx *DB) {
2020-01-30 10:14:48 +03:00
tx = db.getInstance()
var whereConds []interface{}
for _, cond := range conds {
if c, ok := cond.(clause.Interface); ok {
tx.Statement.AddClause(c)
2020-06-14 06:46:17 +03:00
} else if optimizer, ok := cond.(StatementModifier); ok {
optimizer.ModifyStatement(tx.Statement)
2020-01-30 10:14:48 +03:00
} else {
whereConds = append(whereConds, cond)
}
}
if len(whereConds) > 0 {
tx.Statement.AddClause(clause.Where{Exprs: tx.Statement.BuildCondition(whereConds[0], whereConds[1:]...)})
2020-01-30 10:14:48 +03:00
}
return
}
2020-07-19 16:30:24 +03:00
var tableRegexp = regexp.MustCompile(`(?i).+? AS (\w+)\s*(?:$|,)`)
2020-01-29 14:22:44 +03:00
// Table specify the table you would like to run db operations
2020-07-19 16:30:24 +03:00
func (db *DB) Table(name string, args ...interface{}) (tx *DB) {
2020-01-29 14:22:44 +03:00
tx = db.getInstance()
2020-07-19 16:30:24 +03:00
if strings.Contains(name, " ") || strings.Contains(name, "`") || len(args) > 0 {
tx.Statement.TableExpr = &clause.Expr{SQL: name, Vars: args}
if results := tableRegexp.FindStringSubmatch(name); len(results) == 2 {
tx.Statement.Table = results[1]
return
}
2020-07-19 16:30:24 +03:00
} else if tables := strings.Split(name, "."); len(tables) == 2 {
tx.Statement.TableExpr = &clause.Expr{SQL: tx.Statement.Quote(name)}
tx.Statement.Table = tables[1]
return
}
2020-01-29 22:03:06 +03:00
tx.Statement.Table = name
2020-01-29 14:22:44 +03:00
return
}
2020-06-05 14:19:08 +03:00
// Distinct specify distinct fields that you want querying
func (db *DB) Distinct(args ...interface{}) (tx *DB) {
tx = db.getInstance()
tx.Statement.Distinct = true
2020-06-05 14:19:08 +03:00
if len(args) > 0 {
tx = tx.Select(args[0], args[1:]...)
}
return
2020-06-05 14:19:08 +03:00
}
2020-01-29 14:22:44 +03:00
// Select specify fields that you want when querying, creating, updating
2020-03-09 15:37:01 +03:00
func (db *DB) Select(query interface{}, args ...interface{}) (tx *DB) {
2020-01-29 14:22:44 +03:00
tx = db.getInstance()
2020-02-16 08:45:27 +03:00
switch v := query.(type) {
case []string:
tx.Statement.Selects = v
for _, arg := range args {
switch arg := arg.(type) {
case string:
tx.Statement.Selects = append(tx.Statement.Selects, arg)
case []string:
tx.Statement.Selects = append(tx.Statement.Selects, arg...)
default:
tx.AddError(fmt.Errorf("unsupported select args %v %v", query, args))
return
}
}
2020-08-18 13:58:53 +03:00
delete(tx.Statement.Clauses, "SELECT")
2020-02-16 08:45:27 +03:00
case string:
if strings.Count(v, "?") >= len(args) && len(args) > 0 {
tx.Statement.AddClause(clause.Select{
Distinct: db.Statement.Distinct,
Expression: clause.Expr{SQL: v, Vars: args},
})
} else {
2020-10-09 06:52:12 +03:00
tx.Statement.Selects = []string{v}
2020-02-16 08:45:27 +03:00
for _, arg := range args {
switch arg := arg.(type) {
case string:
tx.Statement.Selects = append(tx.Statement.Selects, arg)
case []string:
tx.Statement.Selects = append(tx.Statement.Selects, arg...)
default:
tx.Statement.AddClause(clause.Select{
Distinct: db.Statement.Distinct,
2020-02-16 08:45:27 +03:00
Expression: clause.Expr{SQL: v, Vars: args},
})
return
}
}
2020-08-18 13:58:53 +03:00
delete(tx.Statement.Clauses, "SELECT")
2020-02-16 08:45:27 +03:00
}
default:
tx.AddError(fmt.Errorf("unsupported select args %v %v", query, args))
}
2020-01-29 14:22:44 +03:00
return
}
// Omit specify fields that you want to ignore when creating, updating and querying
2020-03-09 15:37:01 +03:00
func (db *DB) Omit(columns ...string) (tx *DB) {
2020-01-29 14:22:44 +03:00
tx = db.getInstance()
2020-02-16 08:45:27 +03:00
2020-02-19 07:53:46 +03:00
if len(columns) == 1 && strings.ContainsRune(columns[0], ',') {
2020-08-27 14:15:40 +03:00
tx.Statement.Omits = strings.FieldsFunc(columns[0], utils.IsValidDBNameChar)
2020-02-16 08:45:27 +03:00
} else {
tx.Statement.Omits = columns
}
2020-01-29 14:22:44 +03:00
return
}
2020-03-12 03:39:42 +03:00
// Where add conditions
2020-03-09 15:37:01 +03:00
func (db *DB) Where(query interface{}, args ...interface{}) (tx *DB) {
2020-01-29 14:22:44 +03:00
tx = db.getInstance()
if conds := tx.Statement.BuildCondition(query, args...); len(conds) > 0 {
2020-06-01 05:02:20 +03:00
tx.Statement.AddClause(clause.Where{Exprs: conds})
}
2020-01-29 14:22:44 +03:00
return
}
2020-03-12 03:39:42 +03:00
// Not add NOT conditions
2020-03-09 15:37:01 +03:00
func (db *DB) Not(query interface{}, args ...interface{}) (tx *DB) {
2020-01-29 14:22:44 +03:00
tx = db.getInstance()
if conds := tx.Statement.BuildCondition(query, args...); len(conds) > 0 {
2020-06-01 05:02:20 +03:00
tx.Statement.AddClause(clause.Where{Exprs: []clause.Expression{clause.Not(conds...)}})
}
2020-01-29 14:22:44 +03:00
return
}
// Or add OR conditions
2020-03-09 15:37:01 +03:00
func (db *DB) Or(query interface{}, args ...interface{}) (tx *DB) {
2020-01-29 14:22:44 +03:00
tx = db.getInstance()
if conds := tx.Statement.BuildCondition(query, args...); len(conds) > 0 {
2020-07-05 07:23:45 +03:00
tx.Statement.AddClause(clause.Where{Exprs: []clause.Expression{clause.Or(clause.And(conds...))}})
2020-06-01 05:02:20 +03:00
}
2020-01-29 14:22:44 +03:00
return
}
// Joins specify Joins conditions
2020-03-08 14:12:33 +03:00
// db.Joins("Account").Find(&user)
2020-01-29 14:22:44 +03:00
// db.Joins("JOIN emails ON emails.user_id = users.id AND emails.email = ?", "jinzhu@example.org").Find(&user)
2020-03-09 15:37:01 +03:00
func (db *DB) Joins(query string, args ...interface{}) (tx *DB) {
2020-01-29 14:22:44 +03:00
tx = db.getInstance()
2020-08-23 05:40:37 +03:00
tx.Statement.Joins = append(tx.Statement.Joins, join{Name: query, Conds: args})
2020-01-29 14:22:44 +03:00
return
}
// Group specify the group method on the find
2020-03-09 15:37:01 +03:00
func (db *DB) Group(name string) (tx *DB) {
2020-01-29 14:22:44 +03:00
tx = db.getInstance()
2020-08-27 14:15:40 +03:00
fields := strings.FieldsFunc(name, utils.IsValidDBNameChar)
2020-03-08 13:05:22 +03:00
tx.Statement.AddClause(clause.GroupBy{
Columns: []clause.Column{{Name: name, Raw: len(fields) != 1}},
2020-03-08 13:05:22 +03:00
})
2020-01-29 14:22:44 +03:00
return
}
// Having specify HAVING conditions for GROUP BY
2020-03-09 15:37:01 +03:00
func (db *DB) Having(query interface{}, args ...interface{}) (tx *DB) {
2020-01-29 14:22:44 +03:00
tx = db.getInstance()
2020-03-08 13:05:22 +03:00
tx.Statement.AddClause(clause.GroupBy{
Having: tx.Statement.BuildCondition(query, args...),
2020-03-08 13:05:22 +03:00
})
2020-01-29 14:22:44 +03:00
return
}
// Order specify order when retrieve records from database
// db.Order("name DESC")
2020-09-01 10:50:53 +03:00
// db.Order(clause.OrderByColumn{Column: clause.Column{Name: "name"}, Desc: true})
2020-03-09 15:37:01 +03:00
func (db *DB) Order(value interface{}) (tx *DB) {
2020-01-29 14:22:44 +03:00
tx = db.getInstance()
2020-02-04 03:56:15 +03:00
switch v := value.(type) {
2020-02-07 18:45:35 +03:00
case clause.OrderByColumn:
2020-02-16 08:45:27 +03:00
tx.Statement.AddClause(clause.OrderBy{
2020-02-07 18:45:35 +03:00
Columns: []clause.OrderByColumn{v},
2020-02-04 03:56:15 +03:00
})
default:
2020-02-16 08:45:27 +03:00
tx.Statement.AddClause(clause.OrderBy{
2020-02-07 18:45:35 +03:00
Columns: []clause.OrderByColumn{{
2020-02-04 03:56:15 +03:00
Column: clause.Column{Name: fmt.Sprint(value), Raw: true},
}},
})
}
2020-01-29 14:22:44 +03:00
return
}
// Limit specify the number of records to be retrieved
2020-03-09 15:37:01 +03:00
func (db *DB) Limit(limit int) (tx *DB) {
2020-01-29 14:22:44 +03:00
tx = db.getInstance()
2020-03-04 18:56:42 +03:00
tx.Statement.AddClause(clause.Limit{Limit: limit})
2020-01-29 14:22:44 +03:00
return
}
// Offset specify the number of records to skip before starting to return the records
2020-03-09 15:37:01 +03:00
func (db *DB) Offset(offset int) (tx *DB) {
2020-01-29 14:22:44 +03:00
tx = db.getInstance()
2020-03-04 18:56:42 +03:00
tx.Statement.AddClause(clause.Limit{Offset: offset})
2020-01-29 14:22:44 +03:00
return
}
2020-03-09 10:32:55 +03:00
// Scopes pass current database connection to arguments `func(DB) DB`, which could be used to add conditions dynamically
2020-01-29 14:22:44 +03:00
// func AmountGreaterThan1000(db *gorm.DB) *gorm.DB {
// return db.Where("amount > ?", 1000)
// }
//
// func OrderStatus(status []string) func (db *gorm.DB) *gorm.DB {
// return func (db *gorm.DB) *gorm.DB {
// return db.Scopes(AmountGreaterThan1000).Where("status in (?)", status)
// }
// }
//
// db.Scopes(AmountGreaterThan1000, OrderStatus([]string{"paid", "shipped"})).Find(&orders)
2021-02-25 15:06:26 +03:00
func (db *DB) Scopes(funcs ...func(*DB) *DB) (tx *DB) {
tx = db.getInstance()
tx.Statement.scopes = append(tx.Statement.scopes, funcs...)
return tx
2020-01-29 14:22:44 +03:00
}
// Preload preload associations with given conditions
// db.Preload("Orders", "state NOT IN (?)", "cancelled").Find(&users)
2020-04-15 04:14:24 +03:00
func (db *DB) Preload(query string, args ...interface{}) (tx *DB) {
2020-01-29 14:22:44 +03:00
tx = db.getInstance()
2020-04-15 04:14:24 +03:00
if tx.Statement.Preloads == nil {
tx.Statement.Preloads = map[string][]interface{}{}
}
tx.Statement.Preloads[query] = args
2020-01-29 14:22:44 +03:00
return
}
2020-05-28 08:12:56 +03:00
func (db *DB) Attrs(attrs ...interface{}) (tx *DB) {
2020-01-29 14:22:44 +03:00
tx = db.getInstance()
2020-05-28 08:12:56 +03:00
tx.Statement.attrs = attrs
2020-01-29 14:22:44 +03:00
return
}
2020-05-28 08:12:56 +03:00
func (db *DB) Assign(attrs ...interface{}) (tx *DB) {
2020-01-29 14:22:44 +03:00
tx = db.getInstance()
2020-05-28 08:12:56 +03:00
tx.Statement.assigns = attrs
2020-01-29 14:22:44 +03:00
return
}
2020-03-09 15:37:01 +03:00
func (db *DB) Unscoped() (tx *DB) {
2020-01-29 14:22:44 +03:00
tx = db.getInstance()
2020-05-29 02:35:45 +03:00
tx.Statement.Unscoped = true
2020-01-29 14:22:44 +03:00
return
}
2020-03-09 15:37:01 +03:00
func (db *DB) Raw(sql string, values ...interface{}) (tx *DB) {
2020-01-29 14:22:44 +03:00
tx = db.getInstance()
2020-02-22 15:57:29 +03:00
tx.Statement.SQL = strings.Builder{}
2020-07-10 07:28:24 +03:00
if strings.Contains(sql, "@") {
clause.NamedExpr{SQL: sql, Vars: values}.Build(tx.Statement)
} else {
clause.Expr{SQL: sql, Vars: values}.Build(tx.Statement)
}
2020-01-29 14:22:44 +03:00
return
}