From 5688283d7818032af965b21d8d9b4ac8b186e774 Mon Sep 17 00:00:00 2001 From: Deluan Date: Sat, 26 Sep 2026 00:57:00 -0400 Subject: [PATCH] feat(persistence): add PropertyRepository.PutIfAbsent --- model/properties.go | 1 + persistence/property_repository.go | 6 ++++++ persistence/property_repository_test.go | 6 ++++++ tests/mock_property_repo.go | 11 +++++++++++ 4 files changed, 24 insertions(+) diff --git a/model/properties.go b/model/properties.go index 24b56db26..11edf8a20 100644 --- a/model/properties.go +++ b/model/properties.go @@ -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) diff --git a/persistence/property_repository.go b/persistence/property_repository.go index 29bb2b564..87d97491c 100644 --- a/persistence/property_repository.go +++ b/persistence/property_repository.go @@ -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 { diff --git a/persistence/property_repository_test.go b/persistence/property_repository_test.go index 880b315ec..0f4f9ebe5 100644 --- a/persistence/property_repository_test.go +++ b/persistence/property_repository_test.go @@ -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")) + }) }) diff --git a/tests/mock_property_repo.go b/tests/mock_property_repo.go index 949f894c1..f86aa434d 100644 --- a/tests/mock_property_repo.go +++ b/tests/mock_property_repo.go @@ -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