go-gorm / gorm

The fantastic ORM library for Golang, aims to be developer friendly
https://gorm.io
MIT License
37.02k stars 3.94k forks source link

[BUG] Gorm keeps garbage associations in the database #7286

Open droslean opened 1 day ago

droslean commented 1 day ago

Let's say we have

type Config struct {
    gorm.Model

    Params []Param
}

type Param struct {
    gorm.Model
    ConfigID uint

    Key   string
    Value string
}

Creating a config with specific params, gorm handles the associations normally, However, if we wish to update the params of the existing config, gorm will create a new params instead with the correct configID and it will clear the configID from the old params which technically create garbage in the database, since those entries are now useless and they will live as ghost for the rest of the eternity.

Trying to figure this out by reading https://gorm.io/docs/associations.html#Association-Mode, it seems that all operations related to associations are keeping garbage entries in the database.

This sounds like a BUG, or am I missing some critical configuration in the db session maybe?

jinzhu commented 1 day ago

Does the associations prefill the primary key when updating?

droslean commented 23 hours ago

image

@jinzhu A small example is attached. You can see the last entry in the active association of that config_id, and the previous one should have been deleted. Instead gorm, changes the config_id to null and keeps the entry. That will potentially create N of entries that will never be used anywhere.

If I add a new association this will happen to the existing data: image