feat(persistence): add PropertyRepository.PutIfAbsent

This commit is contained in:
Deluan 2026-09-26 00:57:00 -04:00
commit 5688283d78
4 changed files with 24 additions and 0 deletions

View file

@ -4,6 +4,7 @@ import "context"
type PropertyRepository interface {
Put(ctx context.Context, id string, value string) error
PutIfAbsent(ctx context.Context, id string, value string) error
Get(ctx context.Context, id string) (string, error)
Delete(ctx context.Context, id string) error
DefaultGet(ctx context.Context, id string, defaultValue string) (string, error)

View file

@ -34,6 +34,12 @@ func (r propertyRepository) Put(ctx context.Context, id string, value string) er
return err
}
func (r propertyRepository) PutIfAbsent(ctx context.Context, id string, value string) error {
insert := Insert(r.tableName).Columns("id", "value").Values(id, value).Options("OR IGNORE")
_, err := r.executeSQL(ctx, insert)
return err
}
func (r propertyRepository) Get(ctx context.Context, id string) (string, error) {
sel := Select("value").From(r.tableName).Where(Eq{"id": id})
resp := struct {

View file

@ -33,4 +33,10 @@ var _ = Describe("Property Repository", func() {
It("returns a default value if property does not exist", func() {
Expect(pr.DefaultGet(ctx, "2", "default")).To(Equal("default"))
})
It("PutIfAbsent inserts once and never overwrites", func() {
Expect(pr.PutIfAbsent(ctx, "pia", "first")).To(Succeed())
Expect(pr.PutIfAbsent(ctx, "pia", "second")).To(Succeed())
Expect(pr.Get(ctx, "pia")).To(Equal("first"))
})
})

View file

@ -27,6 +27,17 @@ func (p *MockedPropertyRepo) Put(_ context.Context, id string, value string) err
return nil
}
func (p *MockedPropertyRepo) PutIfAbsent(_ context.Context, id string, value string) error {
if p.Error != nil {
return p.Error
}
p.init()
if _, ok := p.Data[id]; !ok {
p.Data[id] = value
}
return nil
}
func (p *MockedPropertyRepo) Get(_ context.Context, id string) (string, error) {
if p.Error != nil {
return "", p.Error