go-gorm / sqlite

GORM sqlite driver
MIT License
179 stars 184 forks source link

Fix columnType.Unique() returns true for non-unique index DDL. #154

Closed jortel closed 1 year ago

jortel commented 1 year ago

What did this pull request do?

Fixes an issue where the migrator determines that a column is unique (true) when referenced in an index DDL without further determining whether the index is unique. As a result, a model with a non-unique index tag is always be deemed different than the DDL which always triggers a table migration. The fix is to determine the column uniqueness based on whether the referencing index DDL is CREATE UNIQUE INDEX ... and not CREATE INDEX.

Set the ColumnType.UniqueValue based on the column being referenced in a UNIQUE index (not just any index).

User Case Description

Common use case of to add a non unique index on a foreign key to support cascade delete. As a result, the auto-migrate detecting a difference and ALWAYS is migrating the table.

The use case: model defined as Person with 1-* relation to Parent (so the index cannot be unique).

type Person struct {
    ParentID uint `gorm:"index;not-null"`
}
CREATE INDEX idx_person ON person (parentid)

Results in: ColumnType.UniqueValue = true.