2020-01-29 14:22:44 +03:00
|
|
|
package gorm
|
|
|
|
|
|
|
|
import (
|
|
|
|
"database/sql"
|
2020-05-28 08:12:56 +03:00
|
|
|
"errors"
|
2020-06-19 13:30:04 +03:00
|
|
|
"fmt"
|
2020-03-08 08:24:08 +03:00
|
|
|
"reflect"
|
2020-02-22 15:57:29 +03:00
|
|
|
"strings"
|
2023-03-10 12:42:38 +03:00
|
|
|
"sync"
|
|
|
|
"sync/atomic"
|
2020-02-04 03:56:15 +03:00
|
|
|
|
2020-06-02 04:16:07 +03:00
|
|
|
"gorm.io/gorm/clause"
|
2020-09-27 07:25:38 +03:00
|
|
|
"gorm.io/gorm/logger"
|
2020-08-13 13:38:39 +03:00
|
|
|
"gorm.io/gorm/schema"
|
2020-06-30 18:06:48 +03:00
|
|
|
"gorm.io/gorm/utils"
|
2020-01-29 14:22:44 +03:00
|
|
|
)
|
|
|
|
|
2022-09-09 06:16:41 +03:00
|
|
|
// Create inserts value, returning the inserted data's primary key in value's id
|
2020-03-09 15:37:01 +03:00
|
|
|
func (db *DB) Create(value interface{}) (tx *DB) {
|
2020-12-02 09:59:50 +03:00
|
|
|
if db.CreateBatchSize > 0 {
|
|
|
|
return db.CreateInBatches(value, db.CreateBatchSize)
|
|
|
|
}
|
|
|
|
|
2020-02-03 05:40:03 +03:00
|
|
|
tx = db.getInstance()
|
|
|
|
tx.Statement.Dest = value
|
2021-05-17 10:34:24 +03:00
|
|
|
return tx.callbacks.Create().Execute(tx)
|
2020-02-03 05:40:03 +03:00
|
|
|
}
|
|
|
|
|
2022-09-09 06:16:41 +03:00
|
|
|
// CreateInBatches inserts value in batches of batchSize
|
2020-11-16 16:42:30 +03:00
|
|
|
func (db *DB) CreateInBatches(value interface{}, batchSize int) (tx *DB) {
|
|
|
|
reflectValue := reflect.Indirect(reflect.ValueOf(value))
|
|
|
|
|
|
|
|
switch reflectValue.Kind() {
|
|
|
|
case reflect.Slice, reflect.Array:
|
2020-12-02 09:59:50 +03:00
|
|
|
var rowsAffected int64
|
2020-11-16 16:42:30 +03:00
|
|
|
tx = db.getInstance()
|
2021-01-18 06:43:42 +03:00
|
|
|
|
2023-03-23 09:02:35 +03:00
|
|
|
// the reflection length judgment of the optimized value
|
|
|
|
reflectLen := reflectValue.Len()
|
|
|
|
|
2021-01-18 06:43:42 +03:00
|
|
|
callFc := func(tx *DB) error {
|
2021-03-08 05:20:04 +03:00
|
|
|
for i := 0; i < reflectLen; i += batchSize {
|
2020-11-16 16:42:30 +03:00
|
|
|
ends := i + batchSize
|
2021-03-08 05:20:04 +03:00
|
|
|
if ends > reflectLen {
|
|
|
|
ends = reflectLen
|
2020-11-16 16:42:30 +03:00
|
|
|
}
|
|
|
|
|
2020-12-02 09:59:50 +03:00
|
|
|
subtx := tx.getInstance()
|
|
|
|
subtx.Statement.Dest = reflectValue.Slice(i, ends).Interface()
|
|
|
|
subtx.callbacks.Create().Execute(subtx)
|
|
|
|
if subtx.Error != nil {
|
|
|
|
return subtx.Error
|
|
|
|
}
|
|
|
|
rowsAffected += subtx.RowsAffected
|
|
|
|
}
|
|
|
|
return nil
|
2021-01-18 06:43:42 +03:00
|
|
|
}
|
|
|
|
|
2023-03-23 09:02:35 +03:00
|
|
|
if tx.SkipDefaultTransaction || reflectLen <= batchSize {
|
2021-01-18 06:43:42 +03:00
|
|
|
tx.AddError(callFc(tx.Session(&Session{})))
|
|
|
|
} else {
|
|
|
|
tx.AddError(tx.Transaction(callFc))
|
|
|
|
}
|
|
|
|
|
2020-12-02 09:59:50 +03:00
|
|
|
tx.RowsAffected = rowsAffected
|
2020-11-16 16:42:30 +03:00
|
|
|
default:
|
2020-12-02 09:59:50 +03:00
|
|
|
tx = db.getInstance()
|
|
|
|
tx.Statement.Dest = value
|
2021-05-17 10:34:24 +03:00
|
|
|
tx = tx.callbacks.Create().Execute(tx)
|
2020-11-16 16:42:30 +03:00
|
|
|
}
|
|
|
|
return
|
|
|
|
}
|
|
|
|
|
2022-09-09 06:16:41 +03:00
|
|
|
// Save updates value in database. If value doesn't contain a matching primary key, value is inserted.
|
2020-03-09 15:37:01 +03:00
|
|
|
func (db *DB) Save(value interface{}) (tx *DB) {
|
2020-01-29 14:22:44 +03:00
|
|
|
tx = db.getInstance()
|
2020-03-08 08:24:08 +03:00
|
|
|
tx.Statement.Dest = value
|
|
|
|
|
2020-06-09 19:02:14 +03:00
|
|
|
reflectValue := reflect.Indirect(reflect.ValueOf(value))
|
2022-04-08 09:23:25 +03:00
|
|
|
for reflectValue.Kind() == reflect.Ptr || reflectValue.Kind() == reflect.Interface {
|
|
|
|
reflectValue = reflect.Indirect(reflectValue)
|
|
|
|
}
|
|
|
|
|
2020-06-09 19:02:14 +03:00
|
|
|
switch reflectValue.Kind() {
|
|
|
|
case reflect.Slice, reflect.Array:
|
2020-11-16 15:22:08 +03:00
|
|
|
if _, ok := tx.Statement.Clauses["ON CONFLICT"]; !ok {
|
|
|
|
tx = tx.Clauses(clause.OnConflict{UpdateAll: true})
|
|
|
|
}
|
2021-06-18 10:38:20 +03:00
|
|
|
tx = tx.callbacks.Create().Execute(tx.Set("gorm:update_track_time", true))
|
2020-06-09 19:02:14 +03:00
|
|
|
case reflect.Struct:
|
|
|
|
if err := tx.Statement.Parse(value); err == nil && tx.Statement.Schema != nil {
|
2020-08-29 18:02:19 +03:00
|
|
|
for _, pf := range tx.Statement.Schema.PrimaryFields {
|
2022-02-16 10:30:43 +03:00
|
|
|
if _, isZero := pf.ValueOf(tx.Statement.Context, reflectValue); isZero {
|
2021-05-17 10:34:24 +03:00
|
|
|
return tx.callbacks.Create().Execute(tx)
|
2020-05-24 15:44:37 +03:00
|
|
|
}
|
2020-03-08 08:24:08 +03:00
|
|
|
}
|
2020-06-06 17:52:08 +03:00
|
|
|
}
|
2020-03-08 08:24:08 +03:00
|
|
|
|
2020-06-09 19:02:14 +03:00
|
|
|
fallthrough
|
|
|
|
default:
|
2020-08-30 05:12:49 +03:00
|
|
|
selectedUpdate := len(tx.Statement.Selects) != 0
|
|
|
|
// when updating, use all fields including those zero-value fields
|
|
|
|
if !selectedUpdate {
|
2020-06-09 19:02:14 +03:00
|
|
|
tx.Statement.Selects = append(tx.Statement.Selects, "*")
|
|
|
|
}
|
|
|
|
|
2023-03-02 12:22:42 +03:00
|
|
|
updateTx := tx.callbacks.Update().Execute(tx.Session(&Session{Initialized: true}))
|
2020-08-30 05:12:49 +03:00
|
|
|
|
2023-03-02 12:22:42 +03:00
|
|
|
if updateTx.Error == nil && updateTx.RowsAffected == 0 && !updateTx.DryRun && !selectedUpdate {
|
2023-03-23 06:18:57 +03:00
|
|
|
return tx.Clauses(clause.OnConflict{UpdateAll: true}).Create(value)
|
2020-08-30 05:12:49 +03:00
|
|
|
}
|
2023-03-02 12:22:42 +03:00
|
|
|
|
|
|
|
return updateTx
|
2020-05-23 18:50:48 +03:00
|
|
|
}
|
2020-06-09 19:02:14 +03:00
|
|
|
|
2020-01-29 14:22:44 +03:00
|
|
|
return
|
|
|
|
}
|
|
|
|
|
2022-09-09 06:16:41 +03:00
|
|
|
// First finds the first record ordered by primary key, matching given conditions conds
|
2020-05-26 16:30:17 +03:00
|
|
|
func (db *DB) First(dest interface{}, conds ...interface{}) (tx *DB) {
|
2020-06-08 17:32:35 +03:00
|
|
|
tx = db.Limit(1).Order(clause.OrderByColumn{
|
2020-02-04 03:56:15 +03:00
|
|
|
Column: clause.Column{Table: clause.CurrentTable, Name: clause.PrimaryKey},
|
|
|
|
})
|
2020-03-07 08:43:20 +03:00
|
|
|
if len(conds) > 0 {
|
2021-01-19 11:37:49 +03:00
|
|
|
if exprs := tx.Statement.BuildCondition(conds[0], conds[1:]...); len(exprs) > 0 {
|
|
|
|
tx.Statement.AddClause(clause.Where{Exprs: exprs})
|
|
|
|
}
|
2020-03-07 08:43:20 +03:00
|
|
|
}
|
2020-03-03 09:18:12 +03:00
|
|
|
tx.Statement.RaiseErrorOnNotFound = true
|
2020-05-26 16:30:17 +03:00
|
|
|
tx.Statement.Dest = dest
|
2021-05-17 10:34:24 +03:00
|
|
|
return tx.callbacks.Query().Execute(tx)
|
2020-01-29 14:22:44 +03:00
|
|
|
}
|
|
|
|
|
2022-09-09 06:16:41 +03:00
|
|
|
// Take finds the first record returned by the database in no specified order, matching given conditions conds
|
2020-05-26 16:30:17 +03:00
|
|
|
func (db *DB) Take(dest interface{}, conds ...interface{}) (tx *DB) {
|
2020-06-08 17:32:35 +03:00
|
|
|
tx = db.Limit(1)
|
2020-03-07 08:43:20 +03:00
|
|
|
if len(conds) > 0 {
|
2021-01-19 11:37:49 +03:00
|
|
|
if exprs := tx.Statement.BuildCondition(conds[0], conds[1:]...); len(exprs) > 0 {
|
|
|
|
tx.Statement.AddClause(clause.Where{Exprs: exprs})
|
|
|
|
}
|
2020-03-07 08:43:20 +03:00
|
|
|
}
|
2020-03-03 09:18:12 +03:00
|
|
|
tx.Statement.RaiseErrorOnNotFound = true
|
2020-05-26 16:30:17 +03:00
|
|
|
tx.Statement.Dest = dest
|
2021-05-17 10:34:24 +03:00
|
|
|
return tx.callbacks.Query().Execute(tx)
|
2020-01-29 14:22:44 +03:00
|
|
|
}
|
|
|
|
|
2022-09-09 06:16:41 +03:00
|
|
|
// Last finds the last record ordered by primary key, matching given conditions conds
|
2020-05-26 16:30:17 +03:00
|
|
|
func (db *DB) Last(dest interface{}, conds ...interface{}) (tx *DB) {
|
2020-06-08 17:32:35 +03:00
|
|
|
tx = db.Limit(1).Order(clause.OrderByColumn{
|
2020-02-23 18:28:35 +03:00
|
|
|
Column: clause.Column{Table: clause.CurrentTable, Name: clause.PrimaryKey},
|
2020-03-04 06:32:36 +03:00
|
|
|
Desc: true,
|
2020-02-23 18:28:35 +03:00
|
|
|
})
|
2020-03-07 08:43:20 +03:00
|
|
|
if len(conds) > 0 {
|
2021-01-19 11:37:49 +03:00
|
|
|
if exprs := tx.Statement.BuildCondition(conds[0], conds[1:]...); len(exprs) > 0 {
|
|
|
|
tx.Statement.AddClause(clause.Where{Exprs: exprs})
|
|
|
|
}
|
2020-03-07 08:43:20 +03:00
|
|
|
}
|
2020-03-03 09:18:12 +03:00
|
|
|
tx.Statement.RaiseErrorOnNotFound = true
|
2020-05-26 16:30:17 +03:00
|
|
|
tx.Statement.Dest = dest
|
2021-05-17 10:34:24 +03:00
|
|
|
return tx.callbacks.Query().Execute(tx)
|
2020-01-29 14:22:44 +03:00
|
|
|
}
|
|
|
|
|
2022-09-09 06:16:41 +03:00
|
|
|
// Find finds all records matching given conditions conds
|
2020-05-26 16:30:17 +03:00
|
|
|
func (db *DB) Find(dest interface{}, conds ...interface{}) (tx *DB) {
|
2020-01-29 14:22:44 +03:00
|
|
|
tx = db.getInstance()
|
2020-03-07 08:43:20 +03:00
|
|
|
if len(conds) > 0 {
|
2021-01-19 11:37:49 +03:00
|
|
|
if exprs := tx.Statement.BuildCondition(conds[0], conds[1:]...); len(exprs) > 0 {
|
|
|
|
tx.Statement.AddClause(clause.Where{Exprs: exprs})
|
|
|
|
}
|
2020-03-07 08:43:20 +03:00
|
|
|
}
|
2020-05-26 16:30:17 +03:00
|
|
|
tx.Statement.Dest = dest
|
2021-05-17 10:34:24 +03:00
|
|
|
return tx.callbacks.Query().Execute(tx)
|
2020-01-29 14:22:44 +03:00
|
|
|
}
|
|
|
|
|
2022-09-09 06:16:41 +03:00
|
|
|
// FindInBatches finds all records in batches of batchSize
|
2020-11-17 06:19:04 +03:00
|
|
|
func (db *DB) FindInBatches(dest interface{}, batchSize int, fc func(tx *DB, batch int) error) *DB {
|
|
|
|
var (
|
|
|
|
tx = db.Order(clause.OrderByColumn{
|
|
|
|
Column: clause.Column{Table: clause.CurrentTable, Name: clause.PrimaryKey},
|
2020-11-17 10:41:17 +03:00
|
|
|
}).Session(&Session{})
|
2020-11-17 06:19:04 +03:00
|
|
|
queryDB = tx
|
|
|
|
rowsAffected int64
|
|
|
|
batch int
|
|
|
|
)
|
2020-06-10 10:36:29 +03:00
|
|
|
|
2022-04-17 04:58:33 +03:00
|
|
|
// user specified offset or limit
|
|
|
|
var totalSize int
|
|
|
|
if c, ok := tx.Statement.Clauses["LIMIT"]; ok {
|
|
|
|
if limit, ok := c.Expression.(clause.Limit); ok {
|
2022-10-07 15:14:14 +03:00
|
|
|
if limit.Limit != nil {
|
|
|
|
totalSize = *limit.Limit
|
|
|
|
}
|
2022-04-17 04:58:33 +03:00
|
|
|
|
|
|
|
if totalSize > 0 && batchSize > totalSize {
|
|
|
|
batchSize = totalSize
|
|
|
|
}
|
|
|
|
|
|
|
|
// reset to offset to 0 in next batch
|
|
|
|
tx = tx.Offset(-1).Session(&Session{})
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2020-06-10 10:36:29 +03:00
|
|
|
for {
|
2020-11-17 06:19:04 +03:00
|
|
|
result := queryDB.Limit(batchSize).Find(dest)
|
2020-06-10 10:36:29 +03:00
|
|
|
rowsAffected += result.RowsAffected
|
|
|
|
batch++
|
|
|
|
|
|
|
|
if result.Error == nil && result.RowsAffected != 0 {
|
2022-07-18 13:06:45 +03:00
|
|
|
fcTx := result.Session(&Session{NewDB: true})
|
|
|
|
fcTx.RowsAffected = result.RowsAffected
|
|
|
|
tx.AddError(fc(fcTx, batch))
|
2021-03-22 09:11:07 +03:00
|
|
|
} else if result.Error != nil {
|
|
|
|
tx.AddError(result.Error)
|
2020-06-10 10:36:29 +03:00
|
|
|
}
|
|
|
|
|
|
|
|
if tx.Error != nil || int(result.RowsAffected) < batchSize {
|
|
|
|
break
|
|
|
|
}
|
2021-06-10 05:21:28 +03:00
|
|
|
|
2022-04-17 04:58:33 +03:00
|
|
|
if totalSize > 0 {
|
|
|
|
if totalSize <= int(rowsAffected) {
|
|
|
|
break
|
|
|
|
}
|
|
|
|
if totalSize/batchSize == batch {
|
|
|
|
batchSize = totalSize % batchSize
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2021-06-10 05:21:28 +03:00
|
|
|
// Optimize for-break
|
|
|
|
resultsValue := reflect.Indirect(reflect.ValueOf(dest))
|
|
|
|
if result.Statement.Schema.PrioritizedPrimaryField == nil {
|
|
|
|
tx.AddError(ErrPrimaryKeyRequired)
|
|
|
|
break
|
|
|
|
}
|
|
|
|
|
2022-11-21 05:49:27 +03:00
|
|
|
primaryValue, zero := result.Statement.Schema.PrioritizedPrimaryField.ValueOf(tx.Statement.Context, resultsValue.Index(resultsValue.Len()-1))
|
|
|
|
if zero {
|
|
|
|
tx.AddError(ErrPrimaryKeyRequired)
|
|
|
|
break
|
|
|
|
}
|
2021-06-10 05:21:28 +03:00
|
|
|
queryDB = tx.Clauses(clause.Gt{Column: clause.Column{Table: clause.CurrentTable, Name: clause.PrimaryKey}, Value: primaryValue})
|
2020-06-10 10:36:29 +03:00
|
|
|
}
|
|
|
|
|
|
|
|
tx.RowsAffected = rowsAffected
|
2020-11-17 06:19:04 +03:00
|
|
|
return tx
|
2020-06-10 10:36:29 +03:00
|
|
|
}
|
|
|
|
|
2022-04-01 03:35:16 +03:00
|
|
|
func (db *DB) assignInterfacesToValue(values ...interface{}) {
|
2020-08-13 13:38:39 +03:00
|
|
|
for _, value := range values {
|
|
|
|
switch v := value.(type) {
|
|
|
|
case []clause.Expression:
|
|
|
|
for _, expr := range v {
|
|
|
|
if eq, ok := expr.(clause.Eq); ok {
|
|
|
|
switch column := eq.Column.(type) {
|
|
|
|
case string:
|
2022-04-01 03:35:16 +03:00
|
|
|
if field := db.Statement.Schema.LookUpField(column); field != nil {
|
|
|
|
db.AddError(field.Set(db.Statement.Context, db.Statement.ReflectValue, eq.Value))
|
2020-08-13 13:38:39 +03:00
|
|
|
}
|
|
|
|
case clause.Column:
|
2022-04-01 03:35:16 +03:00
|
|
|
if field := db.Statement.Schema.LookUpField(column.Name); field != nil {
|
|
|
|
db.AddError(field.Set(db.Statement.Context, db.Statement.ReflectValue, eq.Value))
|
2020-08-13 13:38:39 +03:00
|
|
|
}
|
|
|
|
}
|
2020-10-19 09:49:42 +03:00
|
|
|
} else if andCond, ok := expr.(clause.AndConditions); ok {
|
2022-04-01 03:35:16 +03:00
|
|
|
db.assignInterfacesToValue(andCond.Exprs)
|
2020-05-28 08:12:56 +03:00
|
|
|
}
|
2020-08-13 13:38:39 +03:00
|
|
|
}
|
|
|
|
case clause.Expression, map[string]string, map[interface{}]interface{}, map[string]interface{}:
|
2022-04-01 03:35:16 +03:00
|
|
|
if exprs := db.Statement.BuildCondition(value); len(exprs) > 0 {
|
|
|
|
db.assignInterfacesToValue(exprs)
|
2021-01-19 11:37:49 +03:00
|
|
|
}
|
2020-08-13 13:38:39 +03:00
|
|
|
default:
|
2022-04-01 03:35:16 +03:00
|
|
|
if s, err := schema.Parse(value, db.cacheStore, db.NamingStrategy); err == nil {
|
2020-08-13 13:38:39 +03:00
|
|
|
reflectValue := reflect.Indirect(reflect.ValueOf(value))
|
|
|
|
switch reflectValue.Kind() {
|
|
|
|
case reflect.Struct:
|
|
|
|
for _, f := range s.Fields {
|
|
|
|
if f.Readable {
|
2022-04-01 03:35:16 +03:00
|
|
|
if v, isZero := f.ValueOf(db.Statement.Context, reflectValue); !isZero {
|
|
|
|
if field := db.Statement.Schema.LookUpField(f.Name); field != nil {
|
|
|
|
db.AddError(field.Set(db.Statement.Context, db.Statement.ReflectValue, v))
|
2020-08-13 13:38:39 +03:00
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
2020-05-28 08:12:56 +03:00
|
|
|
}
|
2020-08-13 13:38:39 +03:00
|
|
|
} else if len(values) > 0 {
|
2022-04-01 03:35:16 +03:00
|
|
|
if exprs := db.Statement.BuildCondition(values[0], values[1:]...); len(exprs) > 0 {
|
|
|
|
db.assignInterfacesToValue(exprs)
|
2021-01-19 11:37:49 +03:00
|
|
|
}
|
2020-08-13 13:38:39 +03:00
|
|
|
return
|
2020-05-28 08:12:56 +03:00
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
2022-02-28 12:12:09 +03:00
|
|
|
|
2022-09-09 06:16:41 +03:00
|
|
|
// FirstOrInit finds the first matching record, otherwise if not found initializes a new instance with given conds.
|
|
|
|
// Each conds must be a struct or map.
|
2022-12-23 11:51:01 +03:00
|
|
|
//
|
|
|
|
// FirstOrInit never modifies the database. It is often used with Assign and Attrs.
|
|
|
|
//
|
|
|
|
// // assign an email if the record is not found
|
|
|
|
// db.Where(User{Name: "non_existing"}).Attrs(User{Email: "fake@fake.org"}).FirstOrInit(&user)
|
|
|
|
// // user -> User{Name: "non_existing", Email: "fake@fake.org"}
|
|
|
|
//
|
|
|
|
// // assign email regardless of if record is found
|
|
|
|
// db.Where(User{Name: "jinzhu"}).Assign(User{Email: "fake@fake.org"}).FirstOrInit(&user)
|
|
|
|
// // user -> User{Name: "jinzhu", Age: 20, Email: "fake@fake.org"}
|
2020-05-28 08:12:56 +03:00
|
|
|
func (db *DB) FirstOrInit(dest interface{}, conds ...interface{}) (tx *DB) {
|
2020-11-16 06:20:13 +03:00
|
|
|
queryTx := db.Limit(1).Order(clause.OrderByColumn{
|
|
|
|
Column: clause.Column{Table: clause.CurrentTable, Name: clause.PrimaryKey},
|
|
|
|
})
|
|
|
|
|
2022-04-26 12:16:48 +03:00
|
|
|
if tx = queryTx.Find(dest, conds...); tx.RowsAffected == 0 {
|
2020-05-28 08:12:56 +03:00
|
|
|
if c, ok := tx.Statement.Clauses["WHERE"]; ok {
|
|
|
|
if where, ok := c.Expression.(clause.Where); ok {
|
2020-08-13 13:38:39 +03:00
|
|
|
tx.assignInterfacesToValue(where.Exprs)
|
2020-05-28 08:12:56 +03:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
// initialize with attrs, conds
|
|
|
|
if len(tx.Statement.attrs) > 0 {
|
2020-08-13 13:38:39 +03:00
|
|
|
tx.assignInterfacesToValue(tx.Statement.attrs...)
|
2020-05-28 08:12:56 +03:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
// initialize with attrs, conds
|
|
|
|
if len(tx.Statement.assigns) > 0 {
|
2020-08-13 13:38:39 +03:00
|
|
|
tx.assignInterfacesToValue(tx.Statement.assigns...)
|
2020-05-28 08:12:56 +03:00
|
|
|
}
|
2020-01-29 14:22:44 +03:00
|
|
|
return
|
|
|
|
}
|
|
|
|
|
2022-09-09 06:16:41 +03:00
|
|
|
// FirstOrCreate finds the first matching record, otherwise if not found creates a new instance with given conds.
|
|
|
|
// Each conds must be a struct or map.
|
2022-12-23 11:51:01 +03:00
|
|
|
//
|
|
|
|
// Using FirstOrCreate in conjunction with Assign will result in an update to the database even if the record exists.
|
|
|
|
//
|
|
|
|
// // assign an email if the record is not found
|
|
|
|
// result := db.Where(User{Name: "non_existing"}).Attrs(User{Email: "fake@fake.org"}).FirstOrCreate(&user)
|
|
|
|
// // user -> User{Name: "non_existing", Email: "fake@fake.org"}
|
|
|
|
// // result.RowsAffected -> 1
|
|
|
|
//
|
|
|
|
// // assign email regardless of if record is found
|
|
|
|
// result := db.Where(User{Name: "jinzhu"}).Assign(User{Email: "fake@fake.org"}).FirstOrCreate(&user)
|
|
|
|
// // user -> User{Name: "jinzhu", Age: 20, Email: "fake@fake.org"}
|
|
|
|
// // result.RowsAffected -> 1
|
2020-05-28 11:10:10 +03:00
|
|
|
func (db *DB) FirstOrCreate(dest interface{}, conds ...interface{}) (tx *DB) {
|
2022-04-26 12:16:48 +03:00
|
|
|
tx = db.getInstance()
|
|
|
|
queryTx := db.Session(&Session{}).Limit(1).Order(clause.OrderByColumn{
|
2020-11-16 06:20:13 +03:00
|
|
|
Column: clause.Column{Table: clause.CurrentTable, Name: clause.PrimaryKey},
|
|
|
|
})
|
2020-05-28 11:10:10 +03:00
|
|
|
|
2022-12-01 15:25:53 +03:00
|
|
|
result := queryTx.Find(dest, conds...)
|
|
|
|
if result.Error != nil {
|
|
|
|
tx.Error = result.Error
|
|
|
|
return tx
|
|
|
|
}
|
2020-05-28 11:10:10 +03:00
|
|
|
|
2022-12-01 15:25:53 +03:00
|
|
|
if result.RowsAffected == 0 {
|
|
|
|
if c, ok := result.Statement.Clauses["WHERE"]; ok {
|
|
|
|
if where, ok := c.Expression.(clause.Where); ok {
|
|
|
|
result.assignInterfacesToValue(where.Exprs)
|
2021-11-03 08:39:52 +03:00
|
|
|
}
|
2022-12-01 15:25:53 +03:00
|
|
|
}
|
2020-05-28 11:10:10 +03:00
|
|
|
|
2022-12-01 15:25:53 +03:00
|
|
|
// initialize with attrs, conds
|
|
|
|
if len(db.Statement.attrs) > 0 {
|
|
|
|
result.assignInterfacesToValue(db.Statement.attrs...)
|
|
|
|
}
|
|
|
|
|
|
|
|
// initialize with attrs, conds
|
|
|
|
if len(db.Statement.assigns) > 0 {
|
|
|
|
result.assignInterfacesToValue(db.Statement.assigns...)
|
|
|
|
}
|
|
|
|
|
|
|
|
return tx.Create(dest)
|
|
|
|
} else if len(db.Statement.assigns) > 0 {
|
|
|
|
exprs := tx.Statement.BuildCondition(db.Statement.assigns[0], db.Statement.assigns[1:]...)
|
|
|
|
assigns := map[string]interface{}{}
|
|
|
|
for _, expr := range exprs {
|
|
|
|
if eq, ok := expr.(clause.Eq); ok {
|
|
|
|
switch column := eq.Column.(type) {
|
|
|
|
case string:
|
|
|
|
assigns[column] = eq.Value
|
|
|
|
case clause.Column:
|
|
|
|
assigns[column.Name] = eq.Value
|
2020-05-28 11:10:10 +03:00
|
|
|
}
|
|
|
|
}
|
2021-11-03 08:39:52 +03:00
|
|
|
}
|
2022-12-01 15:25:53 +03:00
|
|
|
|
|
|
|
return tx.Model(dest).Updates(assigns)
|
2020-05-28 11:10:10 +03:00
|
|
|
}
|
2022-12-01 15:25:53 +03:00
|
|
|
|
2021-11-03 08:39:52 +03:00
|
|
|
return tx
|
2020-01-29 14:22:44 +03:00
|
|
|
}
|
|
|
|
|
2022-09-09 06:16:41 +03:00
|
|
|
// Update updates column with value using callbacks. Reference: https://gorm.io/docs/update.html#Update-Changed-Fields
|
2020-03-09 15:37:01 +03:00
|
|
|
func (db *DB) Update(column string, value interface{}) (tx *DB) {
|
2020-01-29 14:22:44 +03:00
|
|
|
tx = db.getInstance()
|
2020-03-07 08:43:20 +03:00
|
|
|
tx.Statement.Dest = map[string]interface{}{column: value}
|
2021-05-17 10:34:24 +03:00
|
|
|
return tx.callbacks.Update().Execute(tx)
|
2020-01-29 14:22:44 +03:00
|
|
|
}
|
|
|
|
|
2022-09-09 06:16:41 +03:00
|
|
|
// Updates updates attributes using callbacks. values must be a struct or map. Reference: https://gorm.io/docs/update.html#Update-Changed-Fields
|
2020-03-09 15:37:01 +03:00
|
|
|
func (db *DB) Updates(values interface{}) (tx *DB) {
|
2020-01-29 14:22:44 +03:00
|
|
|
tx = db.getInstance()
|
2020-03-07 08:43:20 +03:00
|
|
|
tx.Statement.Dest = values
|
2021-05-17 10:34:24 +03:00
|
|
|
return tx.callbacks.Update().Execute(tx)
|
2020-01-29 14:22:44 +03:00
|
|
|
}
|
|
|
|
|
2020-03-09 15:37:01 +03:00
|
|
|
func (db *DB) UpdateColumn(column string, value interface{}) (tx *DB) {
|
2020-01-29 14:22:44 +03:00
|
|
|
tx = db.getInstance()
|
2020-03-07 08:43:20 +03:00
|
|
|
tx.Statement.Dest = map[string]interface{}{column: value}
|
2020-11-17 12:49:43 +03:00
|
|
|
tx.Statement.SkipHooks = true
|
2021-05-17 10:34:24 +03:00
|
|
|
return tx.callbacks.Update().Execute(tx)
|
2020-01-29 14:22:44 +03:00
|
|
|
}
|
|
|
|
|
2020-03-09 15:37:01 +03:00
|
|
|
func (db *DB) UpdateColumns(values interface{}) (tx *DB) {
|
2020-01-29 14:22:44 +03:00
|
|
|
tx = db.getInstance()
|
2020-03-07 08:43:20 +03:00
|
|
|
tx.Statement.Dest = values
|
2020-11-17 12:49:43 +03:00
|
|
|
tx.Statement.SkipHooks = true
|
2021-05-17 10:34:24 +03:00
|
|
|
return tx.callbacks.Update().Execute(tx)
|
2020-01-29 14:22:44 +03:00
|
|
|
}
|
|
|
|
|
2022-09-09 06:16:41 +03:00
|
|
|
// Delete deletes value matching given conditions. If value contains primary key it is included in the conditions. If
|
|
|
|
// value includes a deleted_at field, then Delete performs a soft delete instead by setting deleted_at with the current
|
2022-08-11 06:38:04 +03:00
|
|
|
// time if null.
|
2020-03-09 15:37:01 +03:00
|
|
|
func (db *DB) Delete(value interface{}, conds ...interface{}) (tx *DB) {
|
2020-01-29 14:22:44 +03:00
|
|
|
tx = db.getInstance()
|
2020-03-08 09:51:52 +03:00
|
|
|
if len(conds) > 0 {
|
2021-01-19 11:37:49 +03:00
|
|
|
if exprs := tx.Statement.BuildCondition(conds[0], conds[1:]...); len(exprs) > 0 {
|
|
|
|
tx.Statement.AddClause(clause.Where{Exprs: exprs})
|
|
|
|
}
|
2020-03-08 09:51:52 +03:00
|
|
|
}
|
|
|
|
tx.Statement.Dest = value
|
2021-05-17 10:34:24 +03:00
|
|
|
return tx.callbacks.Delete().Execute(tx)
|
2020-01-29 14:22:44 +03:00
|
|
|
}
|
|
|
|
|
2020-05-24 06:32:59 +03:00
|
|
|
func (db *DB) Count(count *int64) (tx *DB) {
|
2020-01-29 14:22:44 +03:00
|
|
|
tx = db.getInstance()
|
2020-05-24 06:32:59 +03:00
|
|
|
if tx.Statement.Model == nil {
|
|
|
|
tx.Statement.Model = tx.Statement.Dest
|
2020-08-19 15:30:39 +03:00
|
|
|
defer func() {
|
|
|
|
tx.Statement.Model = nil
|
|
|
|
}()
|
2020-05-24 06:32:59 +03:00
|
|
|
}
|
2020-06-05 14:19:08 +03:00
|
|
|
|
2020-12-06 09:04:37 +03:00
|
|
|
if selectClause, ok := db.Statement.Clauses["SELECT"]; ok {
|
|
|
|
defer func() {
|
2021-07-13 16:17:43 +03:00
|
|
|
tx.Statement.Clauses["SELECT"] = selectClause
|
2020-12-06 09:04:37 +03:00
|
|
|
}()
|
|
|
|
} else {
|
|
|
|
defer delete(tx.Statement.Clauses, "SELECT")
|
|
|
|
}
|
|
|
|
|
2020-06-05 14:19:08 +03:00
|
|
|
if len(tx.Statement.Selects) == 0 {
|
2021-06-11 16:51:18 +03:00
|
|
|
tx.Statement.AddClause(clause.Select{Expression: clause.Expr{SQL: "count(*)"}})
|
2021-01-18 14:43:04 +03:00
|
|
|
} else if !strings.HasPrefix(strings.TrimSpace(strings.ToLower(tx.Statement.Selects[0])), "count(") {
|
2021-06-11 16:51:18 +03:00
|
|
|
expr := clause.Expr{SQL: "count(*)"}
|
2020-06-23 03:51:01 +03:00
|
|
|
|
|
|
|
if len(tx.Statement.Selects) == 1 {
|
2020-08-03 05:30:25 +03:00
|
|
|
dbName := tx.Statement.Selects[0]
|
2020-12-06 09:04:37 +03:00
|
|
|
fields := strings.FieldsFunc(dbName, utils.IsValidDBNameChar)
|
2021-08-20 12:37:21 +03:00
|
|
|
if len(fields) == 1 || (len(fields) == 3 && (strings.ToUpper(fields[1]) == "AS" || fields[1] == ".")) {
|
2020-12-06 09:04:37 +03:00
|
|
|
if tx.Statement.Parse(tx.Statement.Model) == nil {
|
|
|
|
if f := tx.Statement.Schema.LookUpField(dbName); f != nil {
|
|
|
|
dbName = f.DBName
|
|
|
|
}
|
2020-06-23 03:51:01 +03:00
|
|
|
}
|
2020-08-03 05:30:25 +03:00
|
|
|
|
2020-12-06 09:04:37 +03:00
|
|
|
if tx.Statement.Distinct {
|
|
|
|
expr = clause.Expr{SQL: "COUNT(DISTINCT(?))", Vars: []interface{}{clause.Column{Name: dbName}}}
|
2021-09-16 06:17:54 +03:00
|
|
|
} else if dbName != "*" {
|
2020-12-06 09:04:37 +03:00
|
|
|
expr = clause.Expr{SQL: "COUNT(?)", Vars: []interface{}{clause.Column{Name: dbName}}}
|
|
|
|
}
|
2020-08-03 05:30:25 +03:00
|
|
|
}
|
2020-06-05 14:19:08 +03:00
|
|
|
}
|
2020-06-23 03:51:01 +03:00
|
|
|
|
|
|
|
tx.Statement.AddClause(clause.Select{Expression: expr})
|
2020-06-05 14:19:08 +03:00
|
|
|
}
|
|
|
|
|
2020-10-22 06:28:43 +03:00
|
|
|
if orderByClause, ok := db.Statement.Clauses["ORDER BY"]; ok {
|
|
|
|
if _, ok := db.Statement.Clauses["GROUP BY"]; !ok {
|
2021-07-13 16:17:43 +03:00
|
|
|
delete(tx.Statement.Clauses, "ORDER BY")
|
2020-10-22 06:28:43 +03:00
|
|
|
defer func() {
|
2021-07-13 16:17:43 +03:00
|
|
|
tx.Statement.Clauses["ORDER BY"] = orderByClause
|
2020-10-22 06:28:43 +03:00
|
|
|
}()
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2020-05-24 06:32:59 +03:00
|
|
|
tx.Statement.Dest = count
|
2021-05-17 10:34:24 +03:00
|
|
|
tx = tx.callbacks.Query().Execute(tx)
|
2021-11-29 15:14:23 +03:00
|
|
|
|
2023-03-23 06:19:53 +03:00
|
|
|
if _, ok := db.Statement.Clauses["GROUP BY"]; ok || tx.RowsAffected != 1 {
|
2020-06-23 17:41:41 +03:00
|
|
|
*count = tx.RowsAffected
|
2020-05-24 06:32:59 +03:00
|
|
|
}
|
2021-11-29 15:14:23 +03:00
|
|
|
|
2020-01-29 14:22:44 +03:00
|
|
|
return
|
|
|
|
}
|
|
|
|
|
2020-03-09 15:37:01 +03:00
|
|
|
func (db *DB) Row() *sql.Row {
|
2021-06-18 10:38:20 +03:00
|
|
|
tx := db.getInstance().Set("rows", false)
|
2021-05-17 10:34:24 +03:00
|
|
|
tx = tx.callbacks.Row().Execute(tx)
|
2020-09-18 16:34:44 +03:00
|
|
|
row, ok := tx.Statement.Dest.(*sql.Row)
|
|
|
|
if !ok && tx.DryRun {
|
|
|
|
db.Logger.Error(tx.Statement.Context, ErrDryRunModeUnsupported.Error())
|
|
|
|
}
|
|
|
|
return row
|
2020-02-03 05:40:03 +03:00
|
|
|
}
|
|
|
|
|
2020-03-09 15:37:01 +03:00
|
|
|
func (db *DB) Rows() (*sql.Rows, error) {
|
2021-06-18 10:38:20 +03:00
|
|
|
tx := db.getInstance().Set("rows", true)
|
2021-05-17 10:34:24 +03:00
|
|
|
tx = tx.callbacks.Row().Execute(tx)
|
2020-09-18 16:34:44 +03:00
|
|
|
rows, ok := tx.Statement.Dest.(*sql.Rows)
|
|
|
|
if !ok && tx.DryRun && tx.Error == nil {
|
|
|
|
tx.Error = ErrDryRunModeUnsupported
|
|
|
|
}
|
|
|
|
return rows, tx.Error
|
2020-02-03 05:40:03 +03:00
|
|
|
}
|
|
|
|
|
2022-09-09 06:16:41 +03:00
|
|
|
// Scan scans selected value to the struct dest
|
2020-03-09 15:37:01 +03:00
|
|
|
func (db *DB) Scan(dest interface{}) (tx *DB) {
|
2020-10-22 12:32:39 +03:00
|
|
|
config := *db.Config
|
|
|
|
currentLogger, newLogger := config.Logger, logger.Recorder.New()
|
|
|
|
config.Logger = newLogger
|
|
|
|
|
2020-01-30 10:14:48 +03:00
|
|
|
tx = db.getInstance()
|
2020-10-22 12:32:39 +03:00
|
|
|
tx.Config = &config
|
|
|
|
|
2021-11-29 09:23:10 +03:00
|
|
|
if rows, err := tx.Rows(); err == nil {
|
2020-09-02 11:14:26 +03:00
|
|
|
if rows.Next() {
|
|
|
|
tx.ScanRows(rows, dest)
|
2021-01-14 11:01:23 +03:00
|
|
|
} else {
|
|
|
|
tx.RowsAffected = 0
|
2023-05-17 05:15:41 +03:00
|
|
|
tx.AddError(rows.Err())
|
2020-09-02 11:14:26 +03:00
|
|
|
}
|
2021-12-02 05:39:24 +03:00
|
|
|
tx.AddError(rows.Close())
|
2020-09-02 11:14:26 +03:00
|
|
|
}
|
2020-09-27 07:25:38 +03:00
|
|
|
|
|
|
|
currentLogger.Trace(tx.Statement.Context, newLogger.BeginAt, func() (string, int64) {
|
|
|
|
return newLogger.SQL, tx.RowsAffected
|
|
|
|
}, tx.Error)
|
|
|
|
tx.Logger = currentLogger
|
2020-01-30 10:14:48 +03:00
|
|
|
return
|
|
|
|
}
|
|
|
|
|
2022-09-09 06:16:41 +03:00
|
|
|
// Pluck queries a single column from a model, returning in the slice dest. E.g.:
|
2022-11-21 05:49:27 +03:00
|
|
|
//
|
|
|
|
// var ages []int64
|
|
|
|
// db.Model(&users).Pluck("age", &ages)
|
2020-05-31 13:51:43 +03:00
|
|
|
func (db *DB) Pluck(column string, dest interface{}) (tx *DB) {
|
|
|
|
tx = db.getInstance()
|
2020-06-05 14:19:08 +03:00
|
|
|
if tx.Statement.Model != nil {
|
|
|
|
if tx.Statement.Parse(tx.Statement.Model) == nil {
|
|
|
|
if f := tx.Statement.Schema.LookUpField(column); f != nil {
|
|
|
|
column = f.DBName
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
2020-06-09 10:34:55 +03:00
|
|
|
|
2020-12-06 09:04:37 +03:00
|
|
|
if len(tx.Statement.Selects) != 1 {
|
|
|
|
fields := strings.FieldsFunc(column, utils.IsValidDBNameChar)
|
|
|
|
tx.Statement.AddClauseIfNotExists(clause.Select{
|
|
|
|
Distinct: tx.Statement.Distinct,
|
|
|
|
Columns: []clause.Column{{Name: column, Raw: len(fields) != 1}},
|
|
|
|
})
|
|
|
|
}
|
2020-06-09 10:34:55 +03:00
|
|
|
tx.Statement.Dest = dest
|
2021-05-17 10:34:24 +03:00
|
|
|
return tx.callbacks.Query().Execute(tx)
|
2020-05-31 13:51:43 +03:00
|
|
|
}
|
|
|
|
|
2020-05-26 18:13:05 +03:00
|
|
|
func (db *DB) ScanRows(rows *sql.Rows, dest interface{}) error {
|
|
|
|
tx := db.getInstance()
|
2020-09-11 10:01:02 +03:00
|
|
|
if err := tx.Statement.Parse(dest); !errors.Is(err, schema.ErrUnsupportedDataType) {
|
|
|
|
tx.AddError(err)
|
|
|
|
}
|
2020-05-26 18:13:05 +03:00
|
|
|
tx.Statement.Dest = dest
|
2020-09-02 11:14:26 +03:00
|
|
|
tx.Statement.ReflectValue = reflect.ValueOf(dest)
|
|
|
|
for tx.Statement.ReflectValue.Kind() == reflect.Ptr {
|
2021-09-17 09:04:19 +03:00
|
|
|
elem := tx.Statement.ReflectValue.Elem()
|
|
|
|
if !elem.IsValid() {
|
|
|
|
elem = reflect.New(tx.Statement.ReflectValue.Type().Elem())
|
|
|
|
tx.Statement.ReflectValue.Set(elem)
|
|
|
|
}
|
|
|
|
tx.Statement.ReflectValue = elem
|
2020-09-02 11:14:26 +03:00
|
|
|
}
|
2021-10-26 17:36:37 +03:00
|
|
|
Scan(rows, tx, ScanInitialized)
|
2020-05-26 18:13:05 +03:00
|
|
|
return tx.Error
|
2020-01-30 10:14:48 +03:00
|
|
|
}
|
|
|
|
|
2022-09-09 06:16:41 +03:00
|
|
|
// Connection uses a db connection to execute an arbitrary number of commands in fc. When finished, the connection is
|
|
|
|
// returned to the connection pool.
|
2022-01-07 04:49:56 +03:00
|
|
|
func (db *DB) Connection(fc func(tx *DB) error) (err error) {
|
|
|
|
if db.Error != nil {
|
|
|
|
return db.Error
|
|
|
|
}
|
|
|
|
|
|
|
|
tx := db.getInstance()
|
|
|
|
sqlDB, err := tx.DB()
|
|
|
|
if err != nil {
|
|
|
|
return
|
|
|
|
}
|
|
|
|
|
|
|
|
conn, err := sqlDB.Conn(tx.Statement.Context)
|
|
|
|
if err != nil {
|
|
|
|
return
|
|
|
|
}
|
|
|
|
|
|
|
|
defer conn.Close()
|
|
|
|
tx.Statement.ConnPool = conn
|
2022-01-07 05:04:35 +03:00
|
|
|
return fc(tx)
|
2022-01-07 04:49:56 +03:00
|
|
|
}
|
|
|
|
|
2023-03-10 12:42:38 +03:00
|
|
|
var (
|
|
|
|
savepointIdx int64
|
|
|
|
savepointNamePool = &sync.Pool{
|
|
|
|
New: func() interface{} {
|
|
|
|
return fmt.Sprintf("gorm_%d", atomic.AddInt64(&savepointIdx, 1))
|
|
|
|
},
|
|
|
|
}
|
|
|
|
)
|
|
|
|
|
2022-09-09 06:16:41 +03:00
|
|
|
// Transaction start a transaction as a block, return error will rollback, otherwise to commit. Transaction executes an
|
|
|
|
// arbitrary number of commands in fc within a transaction. On success the changes are committed; if an error occurs
|
|
|
|
// they are rolled back.
|
2020-03-09 15:37:01 +03:00
|
|
|
func (db *DB) Transaction(fc func(tx *DB) error, opts ...*sql.TxOptions) (err error) {
|
2020-01-29 14:22:44 +03:00
|
|
|
panicked := true
|
|
|
|
|
2020-06-19 13:30:04 +03:00
|
|
|
if committer, ok := db.Statement.ConnPool.(TxCommitter); ok && committer != nil {
|
|
|
|
// nested transaction
|
2020-12-16 14:33:35 +03:00
|
|
|
if !db.DisableNestedTransaction {
|
2023-03-10 12:42:38 +03:00
|
|
|
poolName := savepointNamePool.Get()
|
|
|
|
defer savepointNamePool.Put(poolName)
|
|
|
|
err = db.SavePoint(poolName.(string)).Error
|
2022-01-07 05:04:35 +03:00
|
|
|
if err != nil {
|
|
|
|
return
|
|
|
|
}
|
|
|
|
|
2020-12-16 14:33:35 +03:00
|
|
|
defer func() {
|
|
|
|
// Make sure to rollback when panic, Block error or Commit error
|
|
|
|
if panicked || err != nil {
|
2023-03-10 12:42:38 +03:00
|
|
|
db.RollbackTo(poolName.(string))
|
2020-12-16 14:33:35 +03:00
|
|
|
}
|
|
|
|
}()
|
|
|
|
}
|
2022-05-17 09:13:41 +03:00
|
|
|
err = fc(db.Session(&Session{NewDB: db.clone == 1}))
|
2020-06-19 13:30:04 +03:00
|
|
|
} else {
|
|
|
|
tx := db.Begin(opts...)
|
2022-01-07 05:04:35 +03:00
|
|
|
if tx.Error != nil {
|
|
|
|
return tx.Error
|
|
|
|
}
|
2020-06-19 13:30:04 +03:00
|
|
|
|
|
|
|
defer func() {
|
|
|
|
// Make sure to rollback when panic, Block error or Commit error
|
|
|
|
if panicked || err != nil {
|
|
|
|
tx.Rollback()
|
|
|
|
}
|
|
|
|
}()
|
|
|
|
|
2022-01-07 05:04:35 +03:00
|
|
|
if err = fc(tx); err == nil {
|
|
|
|
panicked = false
|
|
|
|
return tx.Commit().Error
|
2020-06-19 13:30:04 +03:00
|
|
|
}
|
2020-01-29 14:22:44 +03:00
|
|
|
}
|
|
|
|
|
|
|
|
panicked = false
|
|
|
|
return
|
|
|
|
}
|
|
|
|
|
2022-09-09 06:16:41 +03:00
|
|
|
// Begin begins a transaction with any transaction options opts
|
2020-06-05 05:08:22 +03:00
|
|
|
func (db *DB) Begin(opts ...*sql.TxOptions) *DB {
|
|
|
|
var (
|
2020-06-19 07:38:03 +03:00
|
|
|
// clone statement
|
2022-02-20 03:33:12 +03:00
|
|
|
tx = db.getInstance().Session(&Session{Context: db.Statement.Context, NewDB: db.clone == 1})
|
2020-06-05 05:08:22 +03:00
|
|
|
opt *sql.TxOptions
|
2022-07-07 10:06:48 +03:00
|
|
|
err error
|
2020-06-05 05:08:22 +03:00
|
|
|
)
|
|
|
|
|
|
|
|
if len(opts) > 0 {
|
|
|
|
opt = opts[0]
|
|
|
|
}
|
2020-02-23 18:28:35 +03:00
|
|
|
|
2022-07-07 10:06:48 +03:00
|
|
|
switch beginner := tx.Statement.ConnPool.(type) {
|
|
|
|
case TxBeginner:
|
|
|
|
tx.Statement.ConnPool, err = beginner.BeginTx(tx.Statement.Context, opt)
|
|
|
|
case ConnPoolBeginner:
|
|
|
|
tx.Statement.ConnPool, err = beginner.BeginTx(tx.Statement.Context, opt)
|
|
|
|
default:
|
|
|
|
err = ErrInvalidTransaction
|
|
|
|
}
|
|
|
|
|
|
|
|
if err != nil {
|
|
|
|
tx.AddError(err)
|
|
|
|
}
|
|
|
|
|
|
|
|
return tx
|
2020-01-29 14:22:44 +03:00
|
|
|
}
|
|
|
|
|
2022-09-09 06:16:41 +03:00
|
|
|
// Commit commits the changes in a transaction
|
2020-03-09 15:37:01 +03:00
|
|
|
func (db *DB) Commit() *DB {
|
2020-08-17 07:16:42 +03:00
|
|
|
if committer, ok := db.Statement.ConnPool.(TxCommitter); ok && committer != nil && !reflect.ValueOf(committer).IsNil() {
|
2020-06-05 05:08:22 +03:00
|
|
|
db.AddError(committer.Commit())
|
2020-02-23 18:28:35 +03:00
|
|
|
} else {
|
|
|
|
db.AddError(ErrInvalidTransaction)
|
|
|
|
}
|
|
|
|
return db
|
2020-01-29 14:22:44 +03:00
|
|
|
}
|
|
|
|
|
2022-09-09 06:16:41 +03:00
|
|
|
// Rollback rollbacks the changes in a transaction
|
2020-03-09 15:37:01 +03:00
|
|
|
func (db *DB) Rollback() *DB {
|
2020-06-05 05:08:22 +03:00
|
|
|
if committer, ok := db.Statement.ConnPool.(TxCommitter); ok && committer != nil {
|
2020-08-17 07:16:42 +03:00
|
|
|
if !reflect.ValueOf(committer).IsNil() {
|
|
|
|
db.AddError(committer.Rollback())
|
|
|
|
}
|
2020-02-23 18:28:35 +03:00
|
|
|
} else {
|
|
|
|
db.AddError(ErrInvalidTransaction)
|
|
|
|
}
|
|
|
|
return db
|
2020-01-29 14:22:44 +03:00
|
|
|
}
|
|
|
|
|
2020-06-19 13:30:04 +03:00
|
|
|
func (db *DB) SavePoint(name string) *DB {
|
|
|
|
if savePointer, ok := db.Dialector.(SavePointerDialectorInterface); ok {
|
2020-07-16 06:27:04 +03:00
|
|
|
db.AddError(savePointer.SavePoint(db, name))
|
2020-06-19 13:30:04 +03:00
|
|
|
} else {
|
|
|
|
db.AddError(ErrUnsupportedDriver)
|
|
|
|
}
|
|
|
|
return db
|
|
|
|
}
|
|
|
|
|
|
|
|
func (db *DB) RollbackTo(name string) *DB {
|
|
|
|
if savePointer, ok := db.Dialector.(SavePointerDialectorInterface); ok {
|
2020-07-16 06:27:04 +03:00
|
|
|
db.AddError(savePointer.RollbackTo(db, name))
|
2020-06-19 13:30:04 +03:00
|
|
|
} else {
|
|
|
|
db.AddError(ErrUnsupportedDriver)
|
|
|
|
}
|
|
|
|
return db
|
|
|
|
}
|
|
|
|
|
2022-09-09 06:16:41 +03:00
|
|
|
// Exec executes raw sql
|
2020-03-09 15:37:01 +03:00
|
|
|
func (db *DB) Exec(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)
|
|
|
|
}
|
|
|
|
|
2021-05-17 10:34:24 +03:00
|
|
|
return tx.callbacks.Raw().Execute(tx)
|
2020-01-29 14:22:44 +03:00
|
|
|
}
|