Skip to content

Commit

Permalink
Write all fields including zero-value in gorm (#125)
Browse files Browse the repository at this point in the history
  • Loading branch information
seaneganx authored Apr 21, 2021
1 parent 8f657f1 commit 48a3101
Show file tree
Hide file tree
Showing 2 changed files with 43 additions and 3 deletions.
5 changes: 2 additions & 3 deletions server/gorm/client.go
Original file line number Diff line number Diff line change
Expand Up @@ -79,7 +79,6 @@ func NewClient(ctx context.Context, gormDBName, gormConfig string) (*Client, err
mylock()
clientCount++
clientTotal++
//log.Printf("CREATING CLIENT (%d/%d %d)", clientCount, clientTotal, getGID())
switch gormDBName {
case "sqlite3":
db, err := gorm.Open(sqlite.Open(gormConfig), config())
Expand Down Expand Up @@ -128,7 +127,6 @@ func (c *Client) Close() {
}

func (c *Client) close() {
// log.Printf("CLOSING (%d) %d", clientCount, getGID())
clientCount--
sqlDB, _ := c.db.DB()
sqlDB.Close()
Expand Down Expand Up @@ -213,7 +211,8 @@ func (c *Client) Put(ctx context.Context, k storage.Key, v interface{}) (storage
}
c.db.Transaction(
func(tx *gorm.DB) error {
rowsAffected := tx.Model(v).Where("key = ?", k.(*Key).Name).Updates(v).RowsAffected
// Update all fields from model: https://gorm.io/docs/update.html#Update-Selected-Fields
rowsAffected := tx.Model(v).Select("*").Where("key = ?", k.(*Key).Name).Updates(v).RowsAffected
if rowsAffected == 0 {
err := tx.Create(v).Error
if err != nil {
Expand Down
41 changes: 41 additions & 0 deletions server/gorm/gorm_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -22,8 +22,49 @@ import (

"github.com/apigee/registry/server/models"
"github.com/apigee/registry/server/storage"
"github.com/google/go-cmp/cmp"
"google.golang.org/protobuf/testing/protocmp"
)

func TestFieldClearing(t *testing.T) {
ctx := context.TODO()

c, err := NewClient(ctx, "sqlite3", "/tmp/testing.db")
if err != nil {
t.Fatalf("NewClient returned error: %s", err)
}
defer c.Close()
c.reset()

original := &models.Project{
ProjectID: "my-project",
Description: "My Project",
}

k := c.NewKey(storage.ProjectEntityName, original.Name())
if _, err := c.Put(ctx, k, original); err != nil {
t.Fatalf("Setup: Put(%q, %+v) returned error: %s", k, original, err)
}

update := &models.Project{
ProjectID: original.ProjectID,
Description: "",
}

if _, err := c.Put(ctx, k, update); err != nil {
t.Fatalf("Put(%q, %+v) returned error: %s", k, update, err)
}

got := new(models.Project)
if err := c.Get(ctx, k, got); err != nil {
t.Fatalf("Get(%q) returned error: %s", k, err)
}

if !cmp.Equal(got, update, protocmp.Transform()) {
t.Errorf("Get(%q) returned unexpected diff (-want +got):\n%s", k, cmp.Diff(update, got, protocmp.Transform()))
}
}

func TestCRUD(t *testing.T) {
ctx := context.TODO()

Expand Down

0 comments on commit 48a3101

Please sign in to comment.