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

82 lines
1.9 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) error {
if client == nil {
return &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 &otterError.Database{Reason: otterError.DuplicateKey}
}
return result.Error
}
return 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
}