50 lines
1.3 KiB
Go
50 lines
1.3 KiB
Go
package repository
|
|
|
|
import (
|
|
"context"
|
|
|
|
"github.com/Caknoooo/go-gin-clean-starter/database/entities"
|
|
"gorm.io/gorm"
|
|
"gorm.io/gorm/clause"
|
|
)
|
|
|
|
type SequenceRepository interface {
|
|
GetOrCreateSequence(ctx context.Context, tx *gorm.DB, clientId, entityType, period string) (*entities.SequenceEntity, error)
|
|
UpdateSequence(ctx context.Context, tx *gorm.DB, seq *entities.SequenceEntity) error
|
|
}
|
|
|
|
type sequenceRepository struct {
|
|
db *gorm.DB
|
|
}
|
|
|
|
func NewSequenceRepository(db *gorm.DB) SequenceRepository {
|
|
return &sequenceRepository{db: db}
|
|
}
|
|
|
|
func (r *sequenceRepository) GetOrCreateSequence(ctx context.Context, tx *gorm.DB, clientId, entityType, period string) (*entities.SequenceEntity, error) {
|
|
if tx == nil {
|
|
tx = r.db
|
|
}
|
|
var seq entities.SequenceEntity
|
|
err := tx.WithContext(ctx).
|
|
Clauses(clause.Locking{Strength: "UPDATE"}).
|
|
Where("client_id = ? AND entity_type = ? AND period = ?", clientId, entityType, period).
|
|
FirstOrCreate(&seq, entities.SequenceEntity{
|
|
ClientID: clientId,
|
|
EntityType: entityType,
|
|
Period: period,
|
|
CurrentSeq: 0,
|
|
}).Error
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
return &seq, nil
|
|
}
|
|
|
|
func (r *sequenceRepository) UpdateSequence(ctx context.Context, tx *gorm.DB, seq *entities.SequenceEntity) error {
|
|
if tx == nil {
|
|
tx = r.db
|
|
}
|
|
return tx.WithContext(ctx).Model(seq).Update("current_seq", seq.CurrentSeq).Error
|
|
}
|