From de86cf889d350a55fb271c4eedbf2873c2392dd3 Mon Sep 17 00:00:00 2001 From: fulldump Date: Wed, 25 Jan 2023 02:02:18 +0100 Subject: [PATCH] feat: optimize patch, do not persist if diff is empty --- collection/collection.go | 4 ++++ collection/collection_test.go | 37 +++++++++++++++++++++++++++++++++++ 2 files changed, 41 insertions(+) diff --git a/collection/collection.go b/collection/collection.go index a9625df..00fe550 100644 --- a/collection/collection.go +++ b/collection/collection.go @@ -415,6 +415,10 @@ func (c *Collection) patchByRow(row *Row, patch interface{}, persist bool) error return fmt.Errorf("cannot diff: %w", err) } + if len(diff) == 2 { // diff == '{}' + return nil + } + // index update err = indexRemove(c.Indexes, row) if err != nil { diff --git a/collection/collection_test.go b/collection/collection_test.go index 7afeb8b..d1677b9 100644 --- a/collection/collection_test.go +++ b/collection/collection_test.go @@ -4,7 +4,9 @@ import ( "encoding/json" "errors" "fmt" + "io" "io/ioutil" + "os" "strconv" "sync" "testing" @@ -346,6 +348,41 @@ func TestPersistenceUpdate(t *testing.T) { }) } +func TestPersistenceUpdate_TwiceOptimization(t *testing.T) { + Environment(func(filename string) { + + // Setup + c, _ := OpenCollection(filename) + c.Index("my-index", &IndexMapOptions{ + Field: "id", + }) + row, _ := c.Insert(map[string]interface{}{"id": "1", "name": "Pablo"}) + + // Run + for i := 0; i < 10; i++ { + c.Patch(row, map[string]interface{}{"name": "Jaime"}) + } + c.Close() + + // Check + numPatchCommands := 0 + f, _ := os.Open(filename) + d := json.NewDecoder(f) + for { + c := Command{} + if decodeErr := d.Decode(&c); decodeErr == io.EOF { + break + } + + if c.Name == "patch" { + numPatchCommands++ + } + } + + AssertEqual(numPatchCommands, 1) + }) +} + type MockIndex struct { AddRowCallback func(row *Row) error RemoveRowCallback func(row *Row) error