Skip to content

Commit

Permalink
Add ReplaceById()
Browse files Browse the repository at this point in the history
  • Loading branch information
ostafen committed Apr 25, 2022
1 parent f45ee6d commit 45d429a
Show file tree
Hide file tree
Showing 2 changed files with 40 additions and 0 deletions.
25 changes: 25 additions & 0 deletions db_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -236,6 +236,31 @@ func TestUpdateById(t *testing.T) {
})
}

func TestReplaceById(t *testing.T) {
runCloverTest(t, todosPath, func(t *testing.T, db *c.DB) {
doc, err := db.Query("todos").FindFirst()
require.NoError(t, err)

err = db.Query("todos").ReplaceById("invalid-id", doc)
require.Error(t, c.ErrDocumentNotExist)

id := doc.ObjectId()
newDoc := c.NewDocument()
newDoc.Set("hello", "clover")

err = db.Query("todos").ReplaceById(id, newDoc)
require.Error(t, err)

newDoc.Set("_id", id)
err = db.Query("todos").ReplaceById(id, newDoc)
require.NoError(t, err)

doc, err = db.Query("todos").FindById(id)
require.NoError(t, err)
require.Equal(t, doc, newDoc)
})
}

func TestInsertAndDelete(t *testing.T) {
runCloverTest(t, todosPath, func(t *testing.T, db *c.DB) {
criteria := c.Field("completed").Eq(true)
Expand Down
15 changes: 15 additions & 0 deletions query.go
Original file line number Diff line number Diff line change
@@ -1,5 +1,9 @@
package clover

import (
"fmt"
)

// Query represents a generic query which is submitted to a specific collection.
type Query struct {
engine StorageEngine
Expand Down Expand Up @@ -163,6 +167,17 @@ func (q *Query) UpdateById(docId string, updateMap map[string]interface{}) error
})
}

// ReplaceById replaces the document with the specified id with the one provided.
// If no document exists, an ErrDocumentNotExist is returned.
func (q *Query) ReplaceById(docId string, doc *Document) error {
if doc.ObjectId() != docId {
return fmt.Errorf("the id of the document must match the one supplied")
}
return q.engine.UpdateById(q.collection, docId, func(_ *Document) *Document {
return doc
})
}

// DeleteById removes the document with the given id from the underlying collection, provided that such a document exists and satisfies the underlying query.
func (q *Query) DeleteById(id string) error {
return q.engine.DeleteById(q.collection, id)
Expand Down

0 comments on commit 45d429a

Please sign in to comment.