otter-space-sdk/pkg/database/tag.go

82 lines
2.0 KiB
Go
Raw Normal View History

package database
import (
"context"
"errors"
otterError "git.anthrove.art/Anthrove/otter-space-sdk/v2/pkg/error"
"git.anthrove.art/Anthrove/otter-space-sdk/v2/pkg/models"
"gorm.io/gorm"
)
func CreateTag(ctx context.Context, tagName models.TagName, tagType models.TagType) (models.Tag, error) {
if client == nil {
return models.Tag{}, &otterError.Database{Reason: otterError.DatabaseIsNotConnected}
}
tag := models.Tag{
Name: tagName,
Type: tagType,
}
result := client.WithContext(ctx).Create(&tag)
if result.Error != nil {
if errors.Is(result.Error, gorm.ErrDuplicatedKey) {
return models.Tag{}, &otterError.Database{Reason: otterError.DuplicateKey}
}
return models.Tag{}, result.Error
}
return tag, nil
}
func CreateTagInBatch(ctx context.Context, tags []models.Tag, batchSize int) error {
if client == nil {
return &otterError.Database{Reason: otterError.DatabaseIsNotConnected}
}
if tags == nil {
return &otterError.EntityValidationFailed{Reason: otterError.TagListIsEmpty}
}
if len(tags) == 0 {
return &otterError.EntityValidationFailed{Reason: otterError.TagListIsEmpty}
}
if batchSize == 0 {
return &otterError.EntityValidationFailed{Reason: otterError.BatchSizeIsEmpty}
}
result := client.WithContext(ctx).CreateInBatches(&tags, batchSize)
if result.Error != nil {
if errors.Is(result.Error, gorm.ErrDuplicatedKey) {
return &otterError.Database{Reason: otterError.DuplicateKey}
}
return result.Error
}
return nil
}
func DeleteTag(ctx context.Context, tagName models.TagName) error {
var tag models.Tag
if client == nil {
return &otterError.Database{Reason: otterError.DatabaseIsNotConnected}
}
if len(tagName) == 0 {
return &otterError.EntityValidationFailed{Reason: otterError.TagNameIsEmpty}
}
result := client.WithContext(ctx).Delete(&tag, tagName)
if result.Error != nil {
if errors.Is(result.Error, gorm.ErrRecordNotFound) {
return &otterError.Database{Reason: otterError.NoDataFound}
}
return result.Error
}
return nil
}