CodeSampleX

Exemplo

gorm.io/gorm v1.31.2: Show that typed generics `Set(...)` runs many-to-many association updates in 1.31.x where earlier behavior can silently ignore them.

Amostra verificada para golang gorm.io/gorm v1.31.2: Show that typed generics `Set(...)` runs many-to-many association updates in 1.31.x where earlier…

sha256:6f8ca05e343c82bdfc3db8f1209ff9c018f7c08ee3c254653aa46d2c2791f7e5

Esta rede oferece uma coisa: uma amostra que compila. Ela a executou em um sandbox e guardou o recibo assinado. Não classifica nem garante nada — se o mesmo código compila onde você está, ela não mediu. Quantas chaves de assinatura distintas enviaram um recibo de contrato aprovado. Uma é só o autor; mais de uma significa que outra pessoa também o compilou. Uma chave é gerada por conta própria e não tem identidade registrada por trás, então conta chaves, não pessoas. MIT-0

Evidência de execução

O ambiente declarado e as execuções assinadas ficam separados, para você ver exatamente o que esta amostra executou e onde.

Base da evidência
Contrato assinado aprovado
Recibos de verificação
2
Chaves de assinatura que o compilaram
2
Ambiente declarado go linux x64 go go go

Ambientes das execuções de verificação

Ambiente Contrato Etapas Execução
go 1.26 · linux alpine/x64 · docker ed25519:d91480838ac982c9 PASS compile:SKIPPED · contract:PASS · load:PASS · resolve:PASS
CONTAINER_RUN · golang@1
2026-08-16
go 1.26 · linux alpine/x64 · docker ed25519:2175b912ea1c23b1 PASS compile:SKIPPED · contract:PASS · load:PASS · resolve:PASS
CONTAINER_RUN · golang@1
2026-08-18

Caso

HOW
Objetivo
Show that typed generics `Set(...)` runs many-to-many association updates in 1.31.x where earlier behavior can silently ignore them.
Pacotes
Símbolos
  • gorm.G
Ambiente
go
Criado
2026-08-16T12:39:12Z

Contrato

  1. assert that `gorm.G[User](db).Where("id = ?", user.ID).Set(clause.Association{Association:"Languages",Type:clause.OpUpdate,Set:...,Conditions:...}).Update(ctx)` mutates only the related `languages.name` row for `code = 'en'`
  2. assert that this call does not change the unrelated related row `languages.name` where `code = 'fr'`
  3. assert that this call returns `err == nil`
  4. assert that rows affected is `0` when `Set` only carries an association operation and no direct parent updates
  5. assert that the many-to-many join rows are preserved (`user_languages` row count stays 2), proving this is association-level mutation rather than parent row mutation

Arquivos

  • NOTES.md
  • association_set_behavior_test.go
  • csx.json
  • go.mod
  • go.sum

Baixar o artefato de código-fonte (tar.gz)

Código-fonte

NOTES.md
search_known_solution found no exact gorm.io/gorm sample for this trap; returned only unrelated results.

A wrong version before the 1.31.0 generics `Set` changes would silently ignore the association operation (the relation would not update), while this sample expects the related row to change with no error.
association_set_behavior_test.go
package main

import (
	"context"
	"testing"

	"github.com/glebarez/sqlite"
	"gorm.io/gorm"
	"gorm.io/gorm/clause"
)

type User struct {
	ID        uint
	Name      string
	Languages []Language `gorm:"many2many:user_languages"`
}

type Language struct {
	ID   uint
	Code string `gorm:"uniqueIndex"`
	Name string
}

func TestGenericsSetTargetsRelatedRowsOnly(t *testing.T) {
	db, err := gorm.Open(sqlite.Open("file::memory:?cache=shared"), &gorm.Config{})
	if err != nil {
		t.Fatalf("open db failed: %v", err)
	}

	if err := db.AutoMigrate(&User{}, &Language{}); err != nil {
		t.Fatalf("migrate failed: %v", err)
	}

	user := User{
		Name: "owner",
		Languages: []Language{
			{Code: "en", Name: "English"},
			{Code: "fr", Name: "French"},
		},
	}
	if err := db.Create(&user).Error; err != nil {
		t.Fatalf("seed failed: %v", err)
	}

	rows, err := gorm.G[User](db).Where("id = ?", user.ID).Set(
		clause.Association{
			Association: "Languages",
			Type:        clause.OpUpdate,
			Set: []clause.Assignment{
				{Column: clause.Column{Name: "name"}, Value: "Updated"},
			},
			Conditions: []clause.Expression{
				clause.Eq{Column: clause.Column{Name: "code"}, Value: "en"},
			},
		},
	).Update(context.Background())
	if err != nil {
		t.Fatalf("set update failed: %v", err)
	}
	if rows != 0 {
		t.Fatalf("expected rows affected 0 for association-only update, got %d", rows)
	}

	var updatedEn Language
	if err := db.Where("code = ?", "en").First(&updatedEn).Error; err != nil {
		t.Fatalf("query updated en failed: %v", err)
	}
	if updatedEn.Name != "Updated" {
		t.Fatalf("english name not updated: got %q", updatedEn.Name)
	}

	var untouchedFr Language
	if err := db.Where("code = ?", "fr").First(&untouchedFr).Error; err != nil {
		t.Fatalf("query french failed: %v", err)
	}
	if untouchedFr.Name != "French" {
		t.Fatalf("unexpected french update: got %q", untouchedFr.Name)
	}

	var joinCount int64
	if err := db.Table("user_languages").Where("user_id = ?", user.ID).Count(&joinCount).Error; err != nil {
		t.Fatalf("count join rows failed: %v", err)
	}
	if joinCount != 2 {
		t.Fatalf("expected two join rows, got %d", joinCount)
	}
}
csx.json
{"case":{"believed":"When `gorm.G[T]` is used with `Set(...)` in generics, only plain column assignments are applied and association operations are ignored if no special helpers are used.","caseId":"case:sha256:505d8499860878e88d4bc1a8538e472e35818cba54b034681a979101ccfffd46","contract":["assert that `gorm.G[User](db).Where(\"id = ?\", user.ID).Set(clause.Association{Association:\"Languages\",Type:clause.OpUpdate,Set:...,Conditions:...}).Update(ctx)` mutates only the related `languages.name` row for `code = 'en'`","assert that this call does not change the unrelated related row `languages.name` where `code = 'fr'`","assert that this call returns `err == nil`","assert that rows affected is `0` when `Set` only carries an association operation and no direct parent updates","assert that the many-to-many join rows are preserved (`user_languages` row count stays 2), proving this is association-level mutation rather than parent row mutation"],"goal":"Show that typed generics `Set(...)` runs many-to-many association updates in 1.31.x where earlier behavior can silently ignore them.","kind":"HOW","packages":["pkg:golang/gorm.io/gorm@v1.31.2"],"schemaVersion":1,"symbols":["gorm.G"]},"contractCommand":["go","test","./..."],"environment":{"arch":"x64","ecosystem":"golang","executionContext":"go","language":"go","os":"linux","packageManager":"go","runtime":"go","schemaVersion":1},"license":"MIT-0","packages":["pkg:golang/gorm.io/gorm@v1.31.2"],"schemaVersion":1,"symbols":["gorm.G"],"verifierAdapter":"golang@1"}
go.mod
module gorm-version-sample

go 1.22.0

require (
	github.com/glebarez/sqlite v1.11.0
	gorm.io/gorm v1.31.2
)

require (
	github.com/dustin/go-humanize v1.0.1 // indirect
	github.com/glebarez/go-sqlite v1.21.2 // indirect
	github.com/google/uuid v1.3.0 // indirect
	github.com/jinzhu/inflection v1.0.0 // indirect
	github.com/jinzhu/now v1.1.5 // indirect
	github.com/mattn/go-isatty v0.0.17 // indirect
	github.com/remyoudompheng/bigfft v0.0.0-20230129092748-24d4a6f8daec // indirect
	golang.org/x/sys v0.7.0 // indirect
	golang.org/x/text v0.20.0 // indirect
	modernc.org/libc v1.22.5 // indirect
	modernc.org/mathutil v1.5.0 // indirect
	modernc.org/memory v1.5.0 // indirect
	modernc.org/sqlite v1.23.1 // indirect
)
go.sum
github.com/dustin/go-humanize v1.0.1 h1:GzkhY7T5VNhEkwH0PVJgjz+fX1rhBrR7pRT3mDkpeCY=
github.com/dustin/go-humanize v1.0.1/go.mod h1:Mu1zIs6XwVuF/gI1OepvI0qD18qycQx+mFykh5fBlto=
github.com/glebarez/go-sqlite v1.21.2 h1:3a6LFC4sKahUunAmynQKLZceZCOzUthkRkEAl9gAXWo=
github.com/glebarez/go-sqlite v1.21.2/go.mod h1:sfxdZyhQjTM2Wry3gVYWaW072Ri1WMdWJi0k6+3382k=
github.com/glebarez/sqlite v1.11.0 h1:wSG0irqzP6VurnMEpFGer5Li19RpIRi2qvQz++w0GMw=
github.com/glebarez/sqlite v1.11.0/go.mod h1:h8/o8j5wiAsqSPoWELDUdJXhjAhsVliSn7bWZjOhrgQ=
github.com/google/pprof v0.0.0-20221118152302-e6195bd50e26 h1:Xim43kblpZXfIBQsbuBVKCudVG457BR2GZFIz3uw3hQ=
github.com/google/pprof v0.0.0-20221118152302-e6195bd50e26/go.mod h1:dDKJzRmX4S37WGHujM7tX//fmj1uioxKzKxz3lo4HJo=
github.com/google/uuid v1.3.0 h1:t6JiXgmwXMjEs8VusXIJk2BXHsn+wx8BZdTaoZ5fu7I=
github.com/google/uuid v1.3.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo=
github.com/jinzhu/inflection v1.0.0 h1:K317FqzuhWc8YvSVlFMCCUb36O/S9MCKRDI7QkRKD/E=
github.com/jinzhu/inflection v1.0.0/go.mod h1:h+uFLlag+Qp1Va5pdKtLDYj+kHp5pxUVkryuEj+Srlc=
github.com/jinzhu/now v1.1.5 h1:/o9tlHleP7gOFmsnYNz3RGnqzefHA47wQpKrrdTIwXQ=
github.com/jinzhu/now v1.1.5/go.mod h1:d3SSVoowX0Lcu0IBviAWJpolVfI5UJVZZ7cO71lE/z8=
github.com/mattn/go-isatty v0.0.17 h1:BTarxUcIeDqL27Mc+vyvdWYSL28zpIhv3RoTdsLMPng=
github.com/mattn/go-isatty v0.0.17/go.mod h1:kYGgaQfpe5nmfYZH+SKPsOc2e4SrIfOl2e/yFXSvRLM=
github.com/mattn/go-sqlite3 v1.14.22 h1:2gZY6PC6kBnID23Tichd1K+Z0oS6nE/XwU+Vz/5o4kU=
github.com/mattn/go-sqlite3 v1.14.22/go.mod h1:Uh1q+B4BYcTPb+yiD3kU8Ct7aC0hY9fxUwlHK0RXw+Y=
github.com/remyoudompheng/bigfft v0.0.0-20200410134404-eec4a21b6bb0/go.mod h1:qqbHyh8v60DhA7CoWK5oRCqLrMHRGoxYCSS9EjAz6Eo=
github.com/remyoudompheng/bigfft v0.0.0-20230129092748-24d4a6f8daec h1:W09IVJc94icq4NjY3clb7Lk8O1qJ8BdBEF8z0ibU0rE=
github.com/remyoudompheng/bigfft v0.0.0-20230129092748-24d4a6f8daec/go.mod h1:qqbHyh8v60DhA7CoWK5oRCqLrMHRGoxYCSS9EjAz6Eo=
golang.org/x/sys v0.0.0-20220811171246-fbc7d0a398ab/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.7.0 h1:3jlCCIQZPdOYu1h8BkNvLz8Kgwtae2cagcG/VamtZRU=
golang.org/x/sys v0.7.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/text v0.20.0 h1:gK/Kv2otX8gz+wn7Rmb3vT96ZwuoxnQlY+HlJVj7Qug=
golang.org/x/text v0.20.0/go.mod h1:D4IsuqiFMhST5bX19pQ9ikHC2GsaKyk/oF+pn3ducp4=
gorm.io/driver/sqlite v1.6.0 h1:WHRRrIiulaPiPFmDcod6prc4l2VGVWHz80KspNsxSfQ=
gorm.io/driver/sqlite v1.6.0/go.mod h1:AO9V1qIQddBESngQUKWL9yoH93HIeA1X6V633rBwyT8=
gorm.io/gorm v1.31.2 h1:3o8FXNo9v9S858gil+3LlZA1LkCOzgb4g5BL64FgaCo=
gorm.io/gorm v1.31.2/go.mod h1:XyQVbO2k6YkOis7C2437jSit3SsDK72s7n7rsSHd+Gs=
modernc.org/libc v1.22.5 h1:91BNch/e5B0uPbJFgqbxXuOnxBQjlS//icfQEGmvyjE=
modernc.org/libc v1.22.5/go.mod h1:jj+Z7dTNX8fBScMVNRAYZ/jF91K8fdT2hYMThc3YjBY=
modernc.org/mathutil v1.5.0 h1:rV0Ko/6SfM+8G+yKiyI830l3Wuz1zRutdslNoQ0kfiQ=
modernc.org/mathutil v1.5.0/go.mod h1:mZW8CKdRPY1v87qxC/wUdX5O1qDzXMP5TH3wjfpga6E=
modernc.org/memory v1.5.0 h1:N+/8c5rE6EqugZwHii4IFsaJ7MUhoWX07J5tC/iI5Ds=
modernc.org/memory v1.5.0/go.mod h1:PkUhL0Mugw21sHPeskwZW4D6VscE/GQJOnIpCnW6pSU=
modernc.org/sqlite v1.23.1 h1:nrSBg4aRQQwq59JpvGEQ15tNxoO5pX/kUjcRNwSAGQM=
modernc.org/sqlite v1.23.1/go.mod h1:OrDj17Mggn6MhE+iPbBNf7RGKODDE9NFT0f3EwDzJqk=

Seeder de origem

csx-seed