72 lines
1.5 KiB
Go
72 lines
1.5 KiB
Go
package gmodel
|
|
|
|
import (
|
|
"context"
|
|
"fusenapi/utils/handler"
|
|
|
|
"gorm.io/gorm"
|
|
)
|
|
|
|
// TODO: 使用model的属性做你想做的
|
|
|
|
func (p *FsResourcesModel) CreateOrUpdate(ctx context.Context, req *FsResources) (resp *FsResources, err error) {
|
|
rowBuilder := p.db.Table(p.name).WithContext(ctx)
|
|
if req.ResourceId != "" {
|
|
err = rowBuilder.Save(req).Error
|
|
} else {
|
|
err = rowBuilder.Create(req).Error
|
|
}
|
|
return req, err
|
|
}
|
|
|
|
func (m *FsResourcesModel) FindOneByQuery(ctx context.Context, rowBuilder *gorm.DB, filterMap map[string]string) (*FsResources, error) {
|
|
var resp FsResources
|
|
|
|
if filterMap != nil {
|
|
rowBuilder = rowBuilder.Scopes(handler.FilterData(filterMap))
|
|
}
|
|
|
|
result := rowBuilder.WithContext(ctx).Limit(1).Find(&resp)
|
|
if result.Error != nil {
|
|
return nil, result.Error
|
|
} else {
|
|
return &resp, nil
|
|
}
|
|
}
|
|
|
|
func (m *FsResourcesModel) RowSelectBuilder(selectData []string) *gorm.DB {
|
|
var rowBuilder = m.db.Table(m.name)
|
|
|
|
if selectData != nil {
|
|
rowBuilder = rowBuilder.Select(selectData)
|
|
} else {
|
|
rowBuilder = rowBuilder.Select("*")
|
|
}
|
|
return rowBuilder
|
|
}
|
|
|
|
// 事务
|
|
func (m *FsResourcesModel) Trans(ctx context.Context, fn func(ctx context.Context, connGorm *gorm.DB) error) error {
|
|
tx := m.db.Table(m.name).WithContext(ctx).Begin()
|
|
defer func() {
|
|
if r := recover(); r != nil {
|
|
tx.Rollback()
|
|
}
|
|
}()
|
|
|
|
if err := tx.Error; err != nil {
|
|
return err
|
|
}
|
|
|
|
if err := fn(ctx, tx); err != nil {
|
|
tx.Rollback()
|
|
return err
|
|
}
|
|
|
|
return tx.Commit().Error
|
|
}
|
|
|
|
func (m *FsResourcesModel) TableName() string {
|
|
return m.name
|
|
}
|