repo.go 2.06 KB
Newer Older
hujiebin's avatar
hujiebin committed
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79
package model

import (
	"fmt"
	"git.hilo.cn/hilo-common/resource/mysql"
	"gorm.io/gorm"
	"gorm.io/gorm/clause"
	"hilo-group/myerr"
	"time"
)

func Persistent(db *gorm.DB, t mysql.EntityI) error {
	if t == nil {
		return nil
	}
	if t.IsLazyLoad() {
		return nil
	}
	//删除
	if t.CheckDel() {
		tx := db.Delete(t)
		if err := tx.Error; err != nil {
			return myerr.WrapErr(err)
		}
		if tx.RowsAffected == 0 {
			return myerr.NewWaring("gorm delete.RowsAffected = 0")
		}
		//增加缓存行为记录(删除)

	} else if t.GetID() == 0 {
		//新增
		if t.CheckOnDuplicateKeyUPDATE() {
			if err := db.Set("gorm:insert_option", fmt.Sprintf("ON DUPLICATE KEY UPDATE `created_time` = '%s'", time.Now())).Create(t).Error; err != nil {
				return myerr.WrapErr(err)
			}
		} else if t.CheckOnDuplicateKeyIGNORE() {
			if err := db.Clauses(clause.Insert{Modifier: "IGNORE"}).Create(t).Error; err != nil {
				return myerr.WrapErr(err)
			}
		} else {
			if err := db.Create(t).Error; err != nil {
				return myerr.WrapErr(err)
			}
		}
		//增加缓存行为记录(新增)
	} else {
		//fixme: 更新条件,目前是互斥的,应该改成且。
		//更新
		if t.CheckUpdateVersion() {
			//版本号。乐观锁更新,注意,空值不更新
			tx := db.Model(t).Where("version = ? ", t.GetUpdateVersionBefore()).Updates(t)
			if err := tx.Error; err != nil {
				return myerr.WrapErr(err)
			}
			if tx.RowsAffected == 0 {
				return myerr.NewWaring("gorm version update.RowsAffected = 0")
			}
		} else if t.CheckUpdateCondition() {
			//条件更新
			tx := db.Model(t).Where(t.GetUpdateCondition()).Updates(t)
			if err := tx.Error; err != nil {
				return myerr.WrapErr(err)
			}
			if tx.RowsAffected == 0 {
				return myerr.NewWaring("gorm condition update.RowsAffected = 0")
			}
		} else if len(t.GetOmit()) > 0 {
			if err := db.Model(t).Omit(t.GetOmit()...).Save(t).Error; err != nil {
				return myerr.WrapErr(err)
			}
		} else {
			if err := db.Model(t).Save(t).Error; err != nil {
				return myerr.WrapErr(err)
			}
		}
		//增加缓存行为记录(更新)
	}
	return nil
}