2024-08-10 22:13:46 +00:00
|
|
|
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"
|
|
|
|
)
|
|
|
|
|
2024-08-10 22:24:02 +00:00
|
|
|
func CreateTag(ctx context.Context, tagName models.TagName, tagType models.TagType) (models.Tag, error) {
|
2024-08-10 22:13:46 +00:00
|
|
|
|
|
|
|
if client == nil {
|
2024-08-10 22:24:02 +00:00
|
|
|
return models.Tag{}, &otterError.Database{Reason: otterError.DatabaseIsNotConnected}
|
2024-08-10 22:13:46 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
tag := models.Tag{
|
|
|
|
Name: tagName,
|
|
|
|
Type: tagType,
|
|
|
|
}
|
|
|
|
|
|
|
|
result := client.WithContext(ctx).Create(&tag)
|
|
|
|
if result.Error != nil {
|
|
|
|
if errors.Is(result.Error, gorm.ErrDuplicatedKey) {
|
2024-08-10 22:24:02 +00:00
|
|
|
return models.Tag{}, &otterError.Database{Reason: otterError.DuplicateKey}
|
2024-08-10 22:13:46 +00:00
|
|
|
}
|
2024-08-10 22:24:02 +00:00
|
|
|
return models.Tag{}, result.Error
|
2024-08-10 22:13:46 +00:00
|
|
|
}
|
|
|
|
|
2024-08-10 22:24:02 +00:00
|
|
|
return tag, nil
|
2024-08-10 22:13:46 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
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
|
|
|
|
}
|