Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Creating multiple objects referencing a shared object results in that object getting created multiple times #7365

Open
NeariX67 opened this issue Feb 3, 2025 · 0 comments
Assignees
Labels
type:with reproduction steps with reproduction steps

Comments

@NeariX67
Copy link

NeariX67 commented Feb 3, 2025

GORM Playground Link

go-gorm/playground#788

Description

I use the terms from the playground to explain this:

Multiple users have the same manager.

manager := &user{
	name: "manager",
}
user1 := user{
	Name: "jinzhu1",
	Manager: manager,
}
user2 := user{
	Name: "jinzhu2",
	Manager: manager,
}
user3 := user{
	Name: "jinzhu3",
	Manager: manager,
}

Since all users have the same manager, the manager only needs to be created once and referenced via its ID in users 1-3. However, this does not work as expected when using

func (x *user) BeforeCreate(tx *gorm.DB) error {
	if x.ID == 0 {
		x.ID = uint(rand.Uint32())
	}

	return nil
}

The manager is assigned an ID based on BeforeCreate and gorm creates it with the same ID for every user (3 times).
This is not a problem for MariaDB or Postgres, as they simply ignore the superfluous, identical users. For MS SQL (sqlserver), however, it is a problem as it refuses to create multiple tuples with the same ID and therefore rejects all three users (no rows are inserted).
As the manager is not created but referenced in the next SQL statement (creation of users 1-3), an error occurs as the referenced manager is missing.

Expected behavior:
Gorm should create a SQL statement to insert only one manager.

Actual behavior:
Gorm creates a sql statement to insert a manager for each user, even if it is the same for each user.

Additional information

Database: MSSQL
Go version: 1.23.3

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
type:with reproduction steps with reproduction steps
Projects
None yet
Development

No branches or pull requests

2 participants