85 lines
2.0 KiB
Go
85 lines
2.0 KiB
Go
package gmodel
|
|
|
|
import (
|
|
"context"
|
|
"errors"
|
|
"fusenapi/utils/handlers"
|
|
|
|
"gorm.io/gorm"
|
|
)
|
|
|
|
// TODO: 使用model的属性做你想做的
|
|
|
|
func (p *FsResourceModel) FindOneById(ctx context.Context, resourceId string) (*FsResource, error) {
|
|
var resp FsResource
|
|
result := p.db.Table(p.name).WithContext(ctx).Where("resource_id =?", resourceId).Take(&resp)
|
|
if result.Error != nil {
|
|
// 检查 ErrRecordNotFound 错误
|
|
if !errors.Is(result.Error, gorm.ErrRecordNotFound) {
|
|
return nil, result.Error
|
|
}
|
|
}
|
|
return &resp, nil
|
|
}
|
|
|
|
func (p *FsResourceModel) Create(ctx context.Context, req *FsResource) (resp *FsResource, err error) {
|
|
err = p.db.Table(p.name).WithContext(ctx).Create(req).Error
|
|
return req, err
|
|
}
|
|
|
|
func (p *FsResourceModel) Update(ctx context.Context, req *FsResource) (resp *FsResource, err error) {
|
|
err = p.db.Table(p.name).WithContext(ctx).Where("resource_id =?", req.ResourceId).Save(req).Error
|
|
return req, err
|
|
}
|
|
|
|
func (m *FsResourceModel) FindOneByQuery(ctx context.Context, rowBuilder *gorm.DB, filterMap map[string]string) (*FsResource, error) {
|
|
var resp FsResource
|
|
|
|
if filterMap != nil {
|
|
rowBuilder = rowBuilder.Scopes(handlers.FilterData(filterMap))
|
|
}
|
|
|
|
result := rowBuilder.WithContext(ctx).Limit(1).Find(&resp)
|
|
if result.Error != nil {
|
|
return nil, result.Error
|
|
} else {
|
|
return &resp, nil
|
|
}
|
|
}
|
|
|
|
func (m *FsResourceModel) 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 *FsResourceModel) 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 *FsResourceModel) TableName() string {
|
|
return m.name
|
|
}
|