feat(be): add GetByProjectFlockKandangIDForUpdate method to lock chickin rows and prevent race conditions

This commit is contained in:
aguhh18
2025-12-31 10:27:15 +07:00
parent 0fc560b91c
commit c60c40af03
3 changed files with 51 additions and 16 deletions
@@ -16,6 +16,7 @@ type ProjectChickinRepository interface {
GetPendingByProjectFlockKandangID(ctx context.Context, projectFlockKandangID uint) ([]entity.ProjectChickin, error)
GetTotalPendingUsageQtyByProjectFlockKandangID(ctx context.Context, projectFlockKandangID uint) (float64, error)
GetTotalChickinQtyByProjectFlockID(ctx context.Context, projectFlockID uint) (float64, error)
GetByProjectFlockKandangIDForUpdate(ctx context.Context, projectFlockKandangID uint) ([]entity.ProjectChickin, error)
}
type ChickinRepositoryImpl struct {
@@ -64,6 +65,20 @@ func (r *ChickinRepositoryImpl) GetByProjectFlockKandangID(ctx context.Context,
return chickins, nil
}
// GetByProjectFlockKandangIDForUpdate locks chickin rows to prevent race condition
func (r *ChickinRepositoryImpl) GetByProjectFlockKandangIDForUpdate(ctx context.Context, projectFlockKandangID uint) ([]entity.ProjectChickin, error) {
var chickins []entity.ProjectChickin
err := r.db.WithContext(ctx).
Where("project_flock_kandang_id = ?", projectFlockKandangID).
Order("created_at DESC").
Find(&chickins).
Error
if err != nil {
return nil, err
}
return chickins, nil
}
func (r *ChickinRepositoryImpl) GetPendingByProjectFlockKandangID(ctx context.Context, projectFlockKandangID uint) ([]entity.ProjectChickin, error) {
var chickins []entity.ProjectChickin
err := r.db.WithContext(ctx).