From dc83eb6be3737881c9aaf53ca291d50a7b018ced Mon Sep 17 00:00:00 2001 From: Matrix-X Date: Sun, 14 Aug 2022 16:08:48 +0800 Subject: [PATCH] feature(database): model add UpsertModelsOnUniqueID and InsertModelsOnUniqueID --- authorization/rbac/models/permission.go | 4 +-- database/model.go | 36 ++++++++++++++++++++++--- 2 files changed, 35 insertions(+), 5 deletions(-) diff --git a/authorization/rbac/models/permission.go b/authorization/rbac/models/permission.go index 391e8f1..031b9c3 100644 --- a/authorization/rbac/models/permission.go +++ b/authorization/rbac/models/permission.go @@ -73,14 +73,14 @@ func (mdl *Permission) GetForeignValue() string { func (mdl *Permission) GetComposedUniqueID() string { - strKey := *mdl.ModuleID + "-" + mdl.Action + "-" + mdl.SubjectValue + strKey := mdl.Action + "-" + mdl.SubjectValue //fmt2.Dump(strKey) hashKey := security.HashStringData(strKey) return hashKey } -func (mdl *Permission) CheckPermissionModuleNameAvailable(db *gorm.DB) (err error) { +func (mdl *Permission) CheckPermissionNameAvailable(db *gorm.DB) (err error) { result := db. //Debug(). diff --git a/database/model.go b/database/model.go index a6dee67..87a8860 100644 --- a/database/model.go +++ b/database/model.go @@ -6,6 +6,7 @@ import ( "github.com/ArtisanCloud/PowerLibs/v2/object" "github.com/google/uuid" "gorm.io/gorm" + "gorm.io/gorm/clause" "gorm.io/gorm/schema" "math" "reflect" @@ -103,9 +104,6 @@ func (mdl *PowerModel) GetForeignReferValue() string { // --------------------------------------------------------------------------------------------------------------------- // PowerCompactModel // --------------------------------------------------------------------------------------------------------------------- -func (mdl *PowerCompactModel) GetID() int32 { - return mdl.ID -} func (mdl *PowerCompactModel) GetTableName(needFull bool) string { return "" @@ -115,6 +113,9 @@ func (mdl *PowerCompactModel) GetPowerModel() ModelInterface { return mdl } +func (mdl *PowerCompactModel) GetID() int32 { + return mdl.ID +} func (mdl *PowerCompactModel) GetUUID() string { return "" } @@ -247,6 +248,35 @@ func GetAllList(db *gorm.DB, conditions *map[string]interface{}, return nil } +func InsertModelsOnUniqueID(db *gorm.DB, mdl interface{}, uniqueName string, models interface{}) error { + + result := db.Model(mdl). + Debug(). + Clauses(clause.OnConflict{ + Columns: []clause.Column{{Name: uniqueName}}, + DoNothing: true, + }).Create(models) + + return result.Error +} + +func UpsertModelsOnUniqueID(db *gorm.DB, mdl interface{}, uniqueName string, + models interface{}, fieldsToUpdate []string) error { + + if len(fieldsToUpdate) <= 0 { + fieldsToUpdate = GetModelFields(mdl) + } + + result := db.Model(mdl). + Debug(). + Clauses(clause.OnConflict{ + Columns: []clause.Column{{Name: uniqueName}}, + DoUpdates: clause.AssignmentColumns(fieldsToUpdate), + }).Create(models) + + return result.Error +} + /** * model methods */