Skip to content

fix: generics updates arg use map#7734

Open
philhuan wants to merge 1 commit intogo-gorm:masterfrom
philhuan:fix/updates_arg_type
Open

fix: generics updates arg use map#7734
philhuan wants to merge 1 commit intogo-gorm:masterfrom
philhuan:fix/updates_arg_type

Conversation

@philhuan
Copy link
Contributor

@philhuan philhuan commented Mar 16, 2026

  • Do only one thing
  • Non breaking API changes
  • Tested

What did this pull request do?

This pull request fixes issue #7709.

It relaxes the parameter type of the Updates method in the generic API gorm.G[T] to any. This change aligns the generic method's behavior with the polymorphic nature of gorm.DB.Updates, enabling it to correctly handle updates from both map[string]interface{} and struct types. Previously, the strict type constraint limited the method's usability in dynamic field update scenarios.

The implementation involves modifying the Updates method signature in the CreateInterface[T] and ChainInterface[T] interfaces. The core logic in chainG[T].Updates is adjusted to first set the model with Model(r) (where r is of type *T) and then apply the updates. This ensures the correct table schema is targeted before executing the update operation with the provided values.

// In CreateInterface[T] and ChainInterface[T]
Updates(ctx context.Context, values any) (rowsAffected int, err error)

// In chainG[T]
func (c chainG[T]) Updates(ctx context.Context, values any) (rowsAffected int, err error) {
    var r *T
    res := c.g.apply(ctx).Model(r).Updates(values)
    return int(res.RowsAffected), res.Error
}

Verification was completed by adding new tests in tests/generics_test.go, which cover both map and struct update paths. This change is non-breaking and maintains the behavior of existing calls while enhancing functionality for dynamic updates.

User Case Description

Example 1: Updating with a map

update specific fields by passing a map[string]interface{}.

// User wants to update only name and age
updates := map[string]interface{}{"name": "hello", "age": 18}
gorm.G[User](DB).Where("id = ?", user.ID).Updates(context.Background(), updates)

Example 2: Updating with a struct

The existing behavior of updating from a struct instance remains fully supported.

// User updates the name and saves the object
user.Name = "world"
gorm.G[User](DB).Where("id = ?", user.ID).Updates(context.Background(), user)

Copy link
Contributor

@propel-code-bot propel-code-bot bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

No issues found; updates appear correct and well-covered by tests.

Status: No Issues Found | Risk: Low

Review Details

📁 2 files reviewed | 💬 0 comments

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant