Skip to content

IDs of child table is invalid when update with FullSaveAssociations mode in MySQL #7478

@isutare412

Description

@isutare412

GORM Playground Link

go-gorm/playground#805

Description

Environment

  • MySQL

Symptom

// Create app
appInitial := &App{
	Name: "foo",
	Envs: []*Env{
		{Key: "KEY1", Value: "value1"},
	},
}
DB.Create(appInitial)
t.Logf("appInitial: %+v", appInitial)
for i, env := range appInitial.Envs {
	t.Logf("  env[%d]: %+v", i, env)
}

// Update app
appUpdated := &App{
	ID:   appInitial.ID,
	Name: "foo",
	Envs: []*Env{
		{Key: "KEY1", Value: "value1-updated"}, // KEY1 should be updated
		{Key: "KEY2", Value: "value2-added"},  // KEY2 should be added
	},
}
DB.Session(&gorm.Session{FullSaveAssociations: true}).Updates(appUpdated)
t.Logf("appUpdated: %+v", appUpdated)
for i, env := range appUpdated.Envs {
	t.Logf("  env[%d]: %+v", i, env)
}

// Get latest app from database
appFetched := &App{ID: appInitial.ID}
DB.Preload("Envs").First(appFetched)
t.Logf("appFetched: %+v", appFetched)
for i, env := range appFetched.Envs {
	t.Logf("  env[%d]: %+v", i, env)
}

for i := range appFetched.Envs {
	envFetched := appFetched.Envs[i]
	envUpdated := appUpdated.Envs[i]

	if envFetched.Key != envUpdated.Key {
		t.Errorf("Expected env key %s, got %s", envFetched.Key, envUpdated.Key)
	}
	if envFetched.Value != envUpdated.Value {
		t.Errorf("Expected env value %s, got %s", envFetched.Value, envUpdated.Value)
	}
	if envFetched.ID != envUpdated.ID {
		t.Errorf("Expected env ID %d, got %d", envFetched.ID, envUpdated.ID)
	}
}
  1. App has many Envs
  2. Create an app with envs
  3. Update the app with FullSaveAssociations mode.
  4. The updated app's envs have different IDs compared to database.

IDs of child table after Update() is not same as those saved in database.
As you see, IDs in database is 1, 2 but IDs of updated results are 2, 3.

appUpdated: &{ID:1 Name:foo Envs:[0x140002a3e90 0x140002a3ec0]}
  env[0]: &{ID:2 AppID:1 Key:KEY1 Value:value1-updated}
  env[1]: &{ID:3 AppID:1 Key:KEY2 Value:value2-added}
appFetched: &{ID:1 Name:foo Envs:[0x140002f28a0 0x140002f2930]}
  env[0]: &{ID:1 AppID:1 Key:KEY1 Value:value1-updated}
  env[1]: &{ID:2 AppID:1 Key:KEY2 Value:value2-added}
Expected env ID 1, got 2
Expected env ID 2, got 3
FAIL

Metadata

Metadata

Assignees

Type

No type

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions