go-gorm / gorm

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

GORM generates invalid SQL for sqlserver when deleting with composite primary keys #6782

Open sblackstone opened 8 months ago

sblackstone commented 8 months ago

GORM Playground Link

https://github.com/go-gorm/playground/pull/679


type MultiTable struct {
    Field1 string `gorm:"primarykey"`
    Field2 string `gorm:"primarykey"`
    Field3 string `gorm:"primarykey"`
}

func TestGORM(t *testing.T) {

    if err := DB.AutoMigrate(&MultiTable{}); err != nil {
        t.Fatalf("couldnt create multi_table")
    }

    DB.Exec("delete from multi_tables")

    rec := MultiTable{
        Field1: "val1",
        Field2: "val2",
        Field3: "val3",
    }

    if err := DB.Create(&rec).Error; err != nil {
        t.Error(err)
    }

    if err := DB.Delete(&rec).Error; err != nil {
        t.Error(err)
    }

}

Description

When using "delete" on a model that has a composite primary key, GORM generates invalid SQL for sqlserver... The playground PR above demonstrates this...

image

sblackstone commented 8 months ago

I took a look at fixing this issue - it seems a bit thorny due to the requirement that we also support "Soft Delete" and "AllowGlobalUpdate"

Soft delete generates the same kind of broken SQL at the moment......

The query will need to end up looking like this...

DELETE FROM multi_tables
WHERE EXISTS (
    SELECT 1
    FROM (VALUES ('val1', 'val2', 'val3')) AS Subquery(field1, field2, field3)
    WHERE multi_tables.field1 = Subquery.field1
      AND multi_tables.field2 = Subquery.field2
      AND multi_tables.field3 = Subquery.field3
);