gorm icon indicating copy to clipboard operation
gorm copied to clipboard

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

Open sblackstone opened this issue 1 year ago • 1 comments

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 avatar Jan 05 '24 17:01 sblackstone

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
);

sblackstone avatar Jan 08 '24 14:01 sblackstone